hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f4aef88cf32cde12ced412931608263def713ce6
| 1,686
|
cpp
|
C++
|
Utility/lib/src/utility/math_utils.cpp
|
tdenis8/S3DR
|
fb8f4c0c98b5571abb12a51e03229978115b099b
|
[
"MIT"
] | 1
|
2019-07-10T04:25:45.000Z
|
2019-07-10T04:25:45.000Z
|
Utility/lib/src/utility/math_utils.cpp
|
tdenis8/S3DR
|
fb8f4c0c98b5571abb12a51e03229978115b099b
|
[
"MIT"
] | null | null | null |
Utility/lib/src/utility/math_utils.cpp
|
tdenis8/S3DR
|
fb8f4c0c98b5571abb12a51e03229978115b099b
|
[
"MIT"
] | null | null | null |
#include "math_utils.hpp"
#include <cmath>
glm::vec3 MeanPoint(const std::vector<glm::vec3> & points){
glm::vec3 result(0.0, 0.0, 0.0);
auto size=points.size();
for(auto it=points.begin(); it<points.end(); ++it){
result += *it;
}
if(size>0){
result /= size;
}
return result;
}
float DegToRad(float angle_deg)
{
const float deg_to_rad = 3.14159f * 2.0f / 360.0f;
return angle_deg * deg_to_rad;
}
bool IsNull(float value){
if(value < 0.000000001){
return true;
}
return false;
}
glm::vec3 CircleCenterFromCirclePoints(const std::vector<glm::vec3> & points){
if(points.size()!=3){
return glm::vec3(0.0, 0.0, 0.0);
}
const glm::vec3 & p1 = points[0];
const glm::vec3 & p2 = points[1];
const glm::vec3 & p3 = points[2];
auto tmp = glm::length(glm::cross(p1-p2, p2-p3));
if(IsNull(tmp)){
return glm::vec3(0.0, 0.0, 0.0);
}
auto k = 1/(2*tmp*tmp);
tmp = glm::length(p2-p3);
glm::vec3 a = (tmp*tmp) * glm::cross(p1-p2,p1-p3) * k;
tmp = glm::length(p1-p3);
glm::vec3 b = (tmp*tmp) * glm::cross(p2-p1,p2-p3) * k;
tmp = glm::length(p1-p2);
glm::vec3 c = (tmp*tmp) * glm::cross(p3-p1,p3-p2) * k;
return a*p1 + b*p2 + c*p3;
}
float CircleRadiusFromCirclePoints(const std::vector<glm::vec3> & points){
if(points.size()!=3){
return 0.0;;
}
const glm::vec3 & p1 = points[0];
const glm::vec3 & p2 = points[1];
const glm::vec3 & p3 = points[2];
float tmp1 = glm::length(p1-p2) * glm::length(p2-p3) * glm::length(p3-p1);
float tmp2 = 2 * glm::length(glm::cross(p1-p2, p2-p3));
if(IsNull(tmp2)){
return 0.0;
}
return tmp1/tmp2;
}
| 21.896104
| 78
| 0.578885
|
tdenis8
|
f4b24fd42585dcb7dc04986e92fbbad1563f21a0
| 944
|
cc
|
C++
|
dreal/util/infty.cc
|
martinjos/dlinear4
|
c0569f49762393eab2cd5d8823db8decb3cbe15e
|
[
"Apache-2.0"
] | 2
|
2020-07-12T18:01:24.000Z
|
2020-10-02T21:11:51.000Z
|
dreal/util/infty.cc
|
martinjos/dlinear4
|
c0569f49762393eab2cd5d8823db8decb3cbe15e
|
[
"Apache-2.0"
] | null | null | null |
dreal/util/infty.cc
|
martinjos/dlinear4
|
c0569f49762393eab2cd5d8823db8decb3cbe15e
|
[
"Apache-2.0"
] | null | null | null |
/// @file infty.cc
///
#include "dreal/util/infty.h"
namespace dreal {
namespace util {
mpq_class* mpq_class_infinity = nullptr;
mpq_class* mpq_class_ninfinity = nullptr;
void InftyStart(double val) {
mpq_class_infinity = new mpq_class(val);
mpq_class_ninfinity = new mpq_class(-val);
}
void InftyStart(const mpq_class& val) {
mpq_class_infinity = new mpq_class(val);
mpq_class_ninfinity = new mpq_class(-val);
}
void InftyStart(const mpq_t infty, const mpq_t ninfty) {
mpq_class_infinity = new mpq_class(infty);
mpq_class_ninfinity = new mpq_class(ninfty);
}
void InftyFinish() {
delete mpq_class_infinity;
delete mpq_class_ninfinity;
}
// Important: must call InftyStart() first!
// Also, if using QSXStart(), must call it before InftyStart().
const mpq_class& mpq_infty() {
return *mpq_class_infinity;
}
const mpq_class& mpq_ninfty() {
return *mpq_class_ninfinity;
}
} // namespace util
} // namespace dreal
| 20.977778
| 63
| 0.739407
|
martinjos
|
f4b9f8ed45470d551028eb05368f1f2c8ae8d057
| 2,856
|
cpp
|
C++
|
naklibsrc/src/core/MessageHash/Base58EncDec.cpp
|
murphyj8/testNakStructure
|
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
|
[
"Unlicense"
] | 1
|
2021-07-01T02:01:27.000Z
|
2021-07-01T02:01:27.000Z
|
naklibsrc/src/core/MessageHash/Base58EncDec.cpp
|
murphyj8/testNakStructure
|
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
|
[
"Unlicense"
] | 1
|
2020-09-23T12:34:34.000Z
|
2020-09-23T12:34:34.000Z
|
naklibsrc/src/core/MessageHash/Base58EncDec.cpp
|
murphyj8/testNakStructure
|
fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a
|
[
"Unlicense"
] | null | null | null |
#include "MessageHash/Base58EncDec.h"
#include "MessageHash/Base58EncDecImpl.h"
Base58EncDec::Base58EncDec() : m_pImpl(new Base58EncDecImpl){
return ;
}
Base58EncDec::~Base58EncDec(){
return ;
}
std::string Base58EncDec::encode (const std::vector<uint8_t>& vch){
return (m_pImpl->encode(vch));
}
std::string Base58EncDec::encodeCheck (const std::vector<uint8_t>& vch){
return (m_pImpl->encodeCheck(vch));
}
messageVec Base58EncDec::decode (const std::string& msg){
return (m_pImpl->decode(msg));
}
messageVec Base58EncDec::decodeCheck(const std::string& msg){
return (m_pImpl->decodeCheck(msg));
}
std::string EncodeBase58 (const std::string& msg)
{
std::vector<uint8_t> vec;
for (std::string::const_iterator iter = msg.begin(); iter != msg.end(); ++ iter)
{
vec.push_back(*iter);
}
Base58EncDec encdec ;
std::string encVal = encdec.encode (vec);
return encVal ;
}
std::string DecodeBase58 (const std::string& msg)
{
std::string nonConstMsg ( msg );
nonConstMsg = nonConstMsg.erase(nonConstMsg.find_last_not_of("\t\n\v\f\r ")+1);
std::unique_ptr<unsigned char[]> msgPtr ( new unsigned char [nonConstMsg.length()+1]);
std::fill_n(msgPtr.get(), msg.length()+1, 0x00);
std::string::const_iterator iter = nonConstMsg.begin();
for (unsigned int i = 0; i < nonConstMsg.size();++i)
{
msgPtr.get()[i] = *iter ; ++ iter ;
}
Base58EncDec encdec;
std::vector<uint8_t> decodedVal = encdec.decode(nonConstMsg);
std::string retVal;
for(std::vector<uint8_t>::const_iterator iter = decodedVal.begin();iter != decodedVal.end(); ++ iter)
{
retVal.push_back(*iter);
}
return retVal ;
}
std::string EncodeBase58Checked (const std::string& msg)
{
std::vector<uint8_t> vec;
for (std::string::const_iterator iter = msg.begin(); iter != msg.end(); ++ iter)
{
vec.push_back(*iter);
}
Base58EncDec encdec ;
std::string encVal = encdec.encodeCheck (vec);
return encVal ;
}
std::string DecodeBase58Checked (const std::string& msg)
{
std::string nonConstMsg ( msg );
nonConstMsg = nonConstMsg.erase(nonConstMsg.find_last_not_of("\t\n\v\f\r ")+1);
std::unique_ptr<unsigned char> msgPtr ( new unsigned char [nonConstMsg.length()+1]);
std::fill_n(msgPtr.get(), msg.length()+1, 0x00);
std::string::const_iterator iter = nonConstMsg.begin();
for (unsigned int i = 0; i < nonConstMsg.size();++i)
{
msgPtr.get()[i] = *iter ; ++ iter ;
}
Base58EncDec encdec;
std::vector<uint8_t> decodedVal = encdec.decodeCheck(nonConstMsg);
std::string retVal;
for(std::vector<uint8_t>::const_iterator iter = decodedVal.begin();iter != decodedVal.end(); ++ iter)
{
retVal.push_back(*iter);
}
return retVal ;
}
| 30.382979
| 105
| 0.644258
|
murphyj8
|
f4bafce0eb4329174202ea4c22b8e6b84b9afafe
| 94,230
|
cpp
|
C++
|
src/raven_src/src/StandardOutput.cpp
|
Okanagan-Basin-Water-Board/obwb-hydro-modelling
|
91ee6b914e344de65a495093c3b9427986182ef2
|
[
"Artistic-2.0"
] | null | null | null |
src/raven_src/src/StandardOutput.cpp
|
Okanagan-Basin-Water-Board/obwb-hydro-modelling
|
91ee6b914e344de65a495093c3b9427986182ef2
|
[
"Artistic-2.0"
] | null | null | null |
src/raven_src/src/StandardOutput.cpp
|
Okanagan-Basin-Water-Board/obwb-hydro-modelling
|
91ee6b914e344de65a495093c3b9427986182ef2
|
[
"Artistic-2.0"
] | null | null | null |
/*----------------------------------------------------------------
Raven Library Source Code
Copyright (c) 2008-2020 the Raven Development Team
Includes CModel routines for writing output headers and contents:
CModel::CloseOutputStreams()
CModel::WriteOutputFileHeaders()
CModel::WriteMinorOutput()
CModel::WriteMajorOutput()
CModel::SummarizeToScreen()
CModel::RunDiagnostics()
Ensim output routines
NetCDF output routines
----------------------------------------------------------------*/
#include "Model.h"
#include "StateVariables.h"
#if defined(_WIN32)
#include <direct.h>
#elif defined(__linux__)
#include <sys/stat.h>
#endif
int NetCDFAddMetadata (const int fileid,const int time_dimid, string shortname,string longname,string units);
int NetCDFAddMetadata2D(const int fileid,const int time_dimid,int nbasins_dimid,string shortname,string longname,string units);
void WriteNetCDFGlobalAttributes(const int out_ncid,const optStruct &Options,const string descript);
void AddSingleValueToNetCDF (const int out_ncid,const string &label,const size_t time_index,const double &value);
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the flow series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousFlowObs(CTimeSeriesABC *pObs,long SBID)
{
// clears up terribly ugly repeated if statements
if(pObs==NULL){return false;}
if (s_to_l(pObs->GetTag().c_str()) != SBID){ return false; }//SBID is correct
if(pObs->GetType() != CTimeSeriesABC::TS_REGULAR){ return false; }
return (!strcmp(pObs->GetName().c_str(),"HYDROGRAPH")); //name ="HYDROGRAPH"
}
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the reservoir stage series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousStageObs(CTimeSeriesABC *pObs,long SBID)
{
// clears up terribly ugly repeated if statements
if(pObs==NULL){return false;}
return (
(!strcmp(pObs->GetName().c_str(),"RESERVOIR_STAGE")) &&
(s_to_l(pObs->GetTag().c_str()) == SBID) &&
(pObs->GetType() == CTimeSeriesABC::TS_REGULAR)
);
}
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the reservoir inflow series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousInflowObs(CTimeSeriesABC *pObs, long SBID)
{
// clears up terribly ugly repeated if statements
if (pObs == NULL) { return false; }
return (
(!strcmp(pObs->GetName().c_str(), "RESERVOIR_INFLOW")) &&
(s_to_l(pObs->GetTag().c_str()) == SBID) &&
(pObs->GetType() == CTimeSeriesABC::TS_REGULAR)
);
}
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the reservoir inflow series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousNetInflowObs(CTimeSeriesABC *pObs, long SBID)
{
// clears up terribly ugly repeated if statements
if (pObs == NULL) { return false; }
return (
(!strcmp(pObs->GetName().c_str(), "RESERVOIR_NETINFLOW")) &&
(s_to_l(pObs->GetTag().c_str()) == SBID) &&
(pObs->GetType() == CTimeSeriesABC::TS_REGULAR)
);
}
//////////////////////////////////////////////////////////////////
/// \brief Adds output directory & prefix to base file name
/// \param filebase [in] base filename, with extension, no directory information
/// \param &Options [in] Global model options information
//
string FilenamePrepare(string filebase, const optStruct &Options)
{
string fn;
if (Options.run_name==""){fn=Options.output_dir+filebase;}
else {fn=Options.output_dir+Options.run_name+"_"+filebase;}
return fn;
}
//////////////////////////////////////////////////////////////////
/// \brief Closes output file streams
/// \details after end of simulation from Main() or in ExitGracefully; All file streams are opened in WriteOutputFileHeaders() routine
//
void CModel::CloseOutputStreams()
{
for (int c=0;c<_nCustomOutputs;c++){
_pCustomOutputs[c]->CloseFiles();
}
_pTransModel->CloseOutputFiles();
if(_pGWModel!=NULL) {
_pGWModel->CloseOutputFiles();
}
if ( _STORAGE.is_open()){ _STORAGE.close();}
if ( _HYDRO.is_open()){ _HYDRO.close();}
if (_FORCINGS.is_open()){_FORCINGS.close();}
if (_RESSTAGE.is_open()){_RESSTAGE.close();}
if ( _DEMANDS.is_open()){ _DEMANDS.close();}
#ifdef _RVNETCDF_
/* close netcdfs */
int retval; // error value for NetCDF routines
if (_HYDRO_ncid != -9) {retval = nc_close(_HYDRO_ncid); HandleNetCDFErrors(retval); }
_HYDRO_ncid = -9;
if (_STORAGE_ncid != -9) {retval = nc_close(_STORAGE_ncid); HandleNetCDFErrors(retval); }
_STORAGE_ncid = -9;
if (_FORCINGS_ncid != -9) {retval = nc_close(_FORCINGS_ncid); HandleNetCDFErrors(retval); }
_FORCINGS_ncid = -9;
#endif // end compilation if NetCDF library is available
}
//////////////////////////////////////////////////////////////////
/// \brief Write output file headers
/// \details Called prior to simulation (but after initialization) from CModel::Initialize()
/// \param &Options [in] Global model options information
//
void CModel::WriteOutputFileHeaders(const optStruct &Options)
{
int i,j,p;
string tmpFilename;
if(!Options.silent) { cout<<" Writing Output File Headers..."<<endl; }
if (Options.output_format==OUTPUT_STANDARD)
{
//WatershedStorage.csv
//--------------------------------------------------------------
if (Options.write_watershed_storage)
{
tmpFilename=FilenamePrepare("WatershedStorage.csv",Options);
_STORAGE.open(tmpFilename.c_str());
if (_STORAGE.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
_STORAGE<<"time [d],date,hour,rainfall [mm/day],snowfall [mm/d SWE],Channel Storage [mm],Reservoir Storage [mm],Rivulet Storage [mm]";
for (i=0;i<GetNumStateVars();i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i])){
if (i!=iAtmPrecip){
_STORAGE<<","<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
//_STORAGE<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
}
}
}
_STORAGE<<", Total [mm], Cum. Inputs [mm], Cum. Outflow [mm], MB Error [mm]"<<endl;
}
//Hydrographs.csv
//--------------------------------------------------------------
tmpFilename=FilenamePrepare("Hydrographs.csv",Options);
_HYDRO.open(tmpFilename.c_str());
if (_HYDRO.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_HYDRO<<"time,date,hour";
_HYDRO<<",precip [mm/day]";
for (p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && _pSubBasins[p]->IsEnabled()){
string name;
if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" [m3/s]";}
else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" [m3/s]";}
//if (Options.print_obs_hydro)
{
for (i = 0; i < _nObservedTS; i++){
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" (observed) [m3/s]";}
else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" (observed) [m3/s]";}
}
}
}
if (_pSubBasins[p]->GetReservoir() != NULL){
if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" (res. inflow) [m3/s]";}
else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" (res. inflow) [m3/s]";}
}
}
}
_HYDRO<<endl;
}
else if (Options.output_format==OUTPUT_ENSIM)
{
WriteEnsimStandardHeaders(Options);
}
else if (Options.output_format==OUTPUT_NETCDF)
{
WriteNetcdfStandardHeaders(Options); // creates NetCDF files, writes dimensions and creates variables (without writing actual values)
}
//WatershedEnergyStorage.csv
//--------------------------------------------------------------
if (Options.write_energy)
{
ofstream EN_STORAGE;
tmpFilename=FilenamePrepare("WatershedEnergyStorage.csv",Options);
EN_STORAGE.open(tmpFilename.c_str());
if (EN_STORAGE.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
EN_STORAGE<<"time[d],date,hour,temp[C],net incoming [MJ/m2/d]";
for (i=0;i<GetNumStateVars();i++){
if (CStateVariable::IsEnergyStorage(_aStateVarType[i])){
EN_STORAGE<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [MJ/m2]";
}
}
EN_STORAGE<<", Total [MJ/m2], Cum. In [MJ/m2], Cum. Out [MJ/m2], EB Error [MJ/m2]"<<endl;
EN_STORAGE.close();
}
//ReservoirStages.csv
//--------------------------------------------------------------
if((Options.write_reservoir) && (Options.output_format!=OUTPUT_NONE))
{
tmpFilename=FilenamePrepare("ReservoirStages.csv",Options);
_RESSTAGE.open(tmpFilename.c_str());
if(_RESSTAGE.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_RESSTAGE<<"time,date,hour";
_RESSTAGE<<",precip [mm/day]";
for(p=0;p<_nSubBasins;p++){
if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
string name;
if(_pSubBasins[p]->GetName()==""){ _RESSTAGE<<",ID="<<_pSubBasins[p]->GetID() <<" "; }
else { _RESSTAGE<<"," <<_pSubBasins[p]->GetName()<<" "; }
}
//if (Options.print_obs_hydro)
{
for(i = 0; i < _nObservedTS; i++){
if(IsContinuousStageObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
if(_pSubBasins[p]->GetName()==""){ _RESSTAGE<<",ID="<<_pSubBasins[p]->GetID() <<" (observed) [m3/s]"; }
else { _RESSTAGE<<"," <<_pSubBasins[p]->GetName()<<" (observed) [m3/s]"; }
}
}
}
}
_RESSTAGE<<endl;
}
//ReservoirStages.csv
//--------------------------------------------------------------
if((Options.write_demandfile) && (Options.output_format!=OUTPUT_NONE))
{
tmpFilename=FilenamePrepare("Demands.csv",Options);
_DEMANDS.open(tmpFilename.c_str());
if(_DEMANDS.fail()) {
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_DEMANDS<<"time,date,hour";
for(p=0;p<_nSubBasins;p++) {
if((_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->HasIrrigationDemand())) {
string name;
if(_pSubBasins[p]->GetName()=="") { name="ID="+to_string(_pSubBasins[p]->GetID()); }
else { name=_pSubBasins[p]->GetName(); }
_DEMANDS<<","<<name<<" [m3/s]";
_DEMANDS<<","<<name<<" (demand) [m3/s]";
_DEMANDS<<","<<name<<" (min.) [m3/s]";
_DEMANDS<<","<<name<<" (unmet) [m3/s]";
}
}
_DEMANDS<<endl;
}
//ReservoirMassBalance.csv
//--------------------------------------------------------------
if ((Options.write_reservoirMB) && (Options.output_format!=OUTPUT_NONE))
{
ofstream RES_MB;
string name;
tmpFilename=FilenamePrepare("ReservoirMassBalance.csv",Options);
RES_MB.open(tmpFilename.c_str());
if (RES_MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
RES_MB<<"time,date,hour";
RES_MB<<",precip [mm/day]";
for(p=0;p<_nSubBasins;p++){
if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
if(_pSubBasins[p]->GetName()==""){ name=to_string(_pSubBasins[p]->GetID())+"="+to_string(_pSubBasins[p]->GetID()); }
else { name=_pSubBasins[p]->GetName(); }
RES_MB<<"," <<name<<" inflow [m3]";
RES_MB<<"," <<name<<" outflow [m3]";
RES_MB<<"," <<name<<" volume [m3]";
RES_MB<<"," <<name<<" losses [m3]";
RES_MB<<"," <<name<<" MB error [m3]";
RES_MB<<"," <<name<<" constraint";
}
}
RES_MB<<endl;
RES_MB.close();
}
//WatershedMassEnergyBalance.csv
//--------------------------------------------------------------
if (Options.write_mass_bal)
{
ofstream MB;
tmpFilename=FilenamePrepare("WatershedMassEnergyBalance.csv",Options);
MB.open(tmpFilename.c_str());
if (MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
MB<<"time [d],date,hour";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());
MB<<"["<<CStateVariable::GetStateVarUnits(_aStateVarType[_pProcesses[j]->GetFromIndices()[q]])<<"]";
}
}
MB<<endl;
MB<<",,from:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetFromIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetFromIndices()[q]);
MB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
MB<<endl;
MB<<",,to:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetToIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetToIndices()[q]);
MB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
MB<<endl;
MB.close();
}
//WatershedMassEnergyBalance.csv
//--------------------------------------------------------------
if (Options.write_group_mb!=DOESNT_EXIST)
{
int kk=Options.write_group_mb;
ofstream HGMB;
tmpFilename=FilenamePrepare(_pHRUGroups[kk]->GetName()+"_MassEnergyBalance.csv",Options);
HGMB.open(tmpFilename.c_str());
if (HGMB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
HGMB<<"time [d],date,hour";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
HGMB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());
HGMB<<"["<<CStateVariable::GetStateVarUnits(_aStateVarType[_pProcesses[j]->GetFromIndices()[q]])<<"]";
}
}
HGMB<<endl;
HGMB<<",,from:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetFromIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetFromIndices()[q]);
HGMB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
HGMB<<endl;
HGMB<<",,to:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetToIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetToIndices()[q]);
HGMB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
HGMB<<endl;
HGMB.close();
}
//ExhaustiveMassBalance.csv
//--------------------------------------------------------------
if (Options.write_exhaustiveMB)
{
ofstream MB;
tmpFilename=FilenamePrepare("ExhaustiveMassBalance.csv",Options);
MB.open(tmpFilename.c_str());
if (MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
MB<<"time[d],date,hour";
bool first;
for (i=0;i<_nStateVars;i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i]))
{
MB<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i]);
first=true;
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetFromIndices()[q]==i){
if (!first){MB<<",";}first=false;
}
}
}
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetToIndices()[q]==i){
if (!first){MB<<",";}first=false;
}
}
}
for(j=0;j<_nProcesses;j++){
for(int q=0;q<_pProcesses[j]->GetNumLatConnections();q++){
CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]);
if(pProc->GetLateralToIndices()[q]==i){
if(!first){ MB<<","; }first=false;break;
}
if (pProc->GetLateralFromIndices()[q]==i){
if (!first){MB<<",";}first=false;break;
}
}
}
MB<<",,,";//cum, stor, error
}
}
MB<<endl;
MB<<",,";//time,date,hour
for (i=0;i<_nStateVars;i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i]))
{
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetFromIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());}
}
}
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetToIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());}
}
}
for(j=0;j<_nProcesses;j++){
for(int q=0;q<_pProcesses[j]->GetNumLatConnections();q++){
CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]);
if (pProc->GetLateralToIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());break;}
if (pProc->GetLateralFromIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());break;}
}
}
MB<<",cumulative,storage,error";
}
}
MB<<endl;
MB.close();
}
//ForcingFunctions.csv
//--------------------------------------------------------------
if (Options.write_forcings)
{
tmpFilename=FilenamePrepare("ForcingFunctions.csv",Options);
_FORCINGS.open(tmpFilename.c_str());
if (_FORCINGS.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_FORCINGS<<"time [d],date,hour,day_angle,";
_FORCINGS<<" rain [mm/d], snow [mm/d], temp [C], temp_daily_min [C], temp_daily_max [C],temp_daily_ave [C],temp_monthly_min [C],temp_monthly_max [C],";
_FORCINGS<<" air dens. [kg/m3], air pres. [KPa], rel hum. [-],";
_FORCINGS<<" cloud cover [-],";
_FORCINGS<<" ET radiation [MJ/m2/d], SW radiation [MJ/m2/d], net SW radiation [MJ/m2/d], LW radiation [MJ/m2/d], wind vel. [m/s],";
_FORCINGS<<" PET [mm/d], OW PET [mm/d],";
_FORCINGS<<" daily correction [-], potential melt [mm/d]";
_FORCINGS<<endl;
}
// HRU Storage files
//--------------------------------------------------------------
if (_pOutputGroup!=NULL){
for (int kk=0; kk<_pOutputGroup->GetNumHRUs();kk++)
{
ofstream HRUSTOR;
tmpFilename="HRUStorage_"+to_string(_pOutputGroup->GetHRU(kk)->GetID())+".csv";
tmpFilename=FilenamePrepare(tmpFilename,Options);
HRUSTOR.open(tmpFilename.c_str());
if (HRUSTOR.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
HRUSTOR<<"time [d],date,hour,rainfall [mm/day],snowfall [mm/d SWE]";
for (i=0;i<GetNumStateVars();i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i])){
if (i!=iAtmPrecip){
HRUSTOR<<","<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
//HRUSTOR<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
}
}
}
HRUSTOR<<", Total [mm]"<<endl;
HRUSTOR.close();
}
}
// Custom output files
//--------------------------------------------------------------
for (int c=0;c<_nCustomOutputs;c++)
{
_pCustomOutputs[c]->WriteFileHeader(Options);
}
// Transport output files
//--------------------------------------------------------------
if (Options.output_format==OUTPUT_STANDARD)
{
_pTransModel->WriteOutputFileHeaders(Options);
}
else if (Options.output_format==OUTPUT_ENSIM)
{
_pTransModel->WriteEnsimOutputFileHeaders(Options);
}
// Groundwater output files
//-------------------------------------------------------------
_pGWModel->WriteOutputFileHeaders(Options);
//raven_debug.csv
//--------------------------------------------------------------
if (Options.debug_mode)
{
ofstream DEBUG;
tmpFilename=FilenamePrepare("raven_debug.csv",Options);
DEBUG.open(tmpFilename.c_str());
if (DEBUG.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
DEBUG<<"time[d],date,hour,debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10"<<endl;
DEBUG.close();
}
//opens and closes diagnostics.csv so that this warning doesn't show up at end of simulation
//--------------------------------------------------------------
if ((_nObservedTS>0) && (_nDiagnostics>0))
{
ofstream DIAG;
tmpFilename=FilenamePrepare("Diagnostics.csv",Options);
DIAG.open(tmpFilename.c_str());
if(DIAG.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
DIAG.close();
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes minor output to file at the end of each timestep (or multiple thereof)
/// \note only thing this modifies should be output streams
/// \param &Options [in] Global model options information
/// \param &tt [in] Local (model) time *at the end of* the pertinent time step
//
void CModel::WriteMinorOutput(const optStruct &Options,const time_struct &tt)
{
int i,iCumPrecip,k;
double output_int = 0.0;
double mod_final = 0.0;
double S,currentWater;
string thisdate;
string thishour;
bool silent=true;
bool quiet=true;
double t;
string tmpFilename;
if ((tt.model_time==0) && (Options.suppressICs)){return;}
//converts the 'write every x timesteps' into a 'write at time y' value
output_int = Options.output_interval * Options.timestep;
mod_final = ffmod(tt.model_time,output_int);
iCumPrecip=GetStateVarIndex(ATMOS_PRECIP);
if(fabs(mod_final) <= 0.5*Options.timestep) //checks to see if sufficiently close to timestep
//(this should account for any roundoff error in timestep calcs)
{
thisdate=tt.date_string; //refers to date and time at END of time step
thishour=DecDaysToHours(tt.julian_day);
t =tt.model_time;
time_struct prev;
JulianConvert(t-Options.timestep,Options.julian_start_day,Options.julian_start_year,Options.calendar,prev); //get start of time step, prev
double usetime=tt.model_time;
string usedate=thisdate;
string usehour=thishour;
if(Options.period_starting){
usedate=prev.date_string;
usehour=DecDaysToHours(prev.julian_day);
usetime=tt.model_time-Options.timestep;
}
// Console output
//----------------------------------------------------------------
if ((quiet) && (!Options.silent) && (tt.day_of_month==1) && ((tt.julian_day)-floor(tt.julian_day+TIME_CORRECTION)<Options.timestep/2))
{
cout<<thisdate <<endl;
}
if(!silent)
{
cout <<thisdate<<" "<<thishour<<":";
if (t!=0){cout <<" | P: "<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<GetAveragePrecip();}
else {cout <<" | P: ------";}
}
//Write current state of water storage in system to WatershedStorage.csv (ALWAYS DONE if not switched OFF)
//----------------------------------------------------------------
if (Options.output_format==OUTPUT_STANDARD)
{
if (Options.write_watershed_storage)
{
double snowfall =GetAverageSnowfall();
double precip =GetAveragePrecip();
double channel_stor =GetTotalChannelStorage();
double reservoir_stor=GetTotalReservoirStorage();
double rivulet_stor =GetTotalRivuletStorage();
_STORAGE<<tt.model_time <<","<<thisdate<<","<<thishour; //instantaneous, so thishour rather than usehour used.
if (t!=0){_STORAGE<<","<<precip-snowfall<<","<<snowfall;}//precip
else {_STORAGE<<",---,---";}
_STORAGE<<","<<channel_stor<<","<<reservoir_stor<<","<<rivulet_stor;
currentWater=0.0;
for (i=0;i<GetNumStateVars();i++)
{
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip))
{
S=GetAvgStateVar(i);
if (!silent){cout<<" |"<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<S;}
_STORAGE<<","<<FormatDouble(S);
currentWater+=S;
}
}
currentWater+=channel_stor+rivulet_stor+reservoir_stor;
if(t==0){
// \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it
// JRC: I think somehow this is being double counted in the delta V calculations in the first timestep
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->GetReservoir()!=NULL){
currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
}
}
}
_STORAGE<<","<<currentWater<<","<<_CumulInput<<","<<_CumulOutput<<","<<FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput));
_STORAGE<<endl;
}
//Write hydrographs for gauged watersheds (ALWAYS DONE)
//----------------------------------------------------------------
if ((Options.ave_hydrograph) && (t!=0.0))
{
_HYDRO<<usetime<<","<<usedate<<","<<usehour<<","<<GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<","<<_pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
//if (Options.print_obs_hydro)
{
for (i = 0; i < _nObservedTS; i++)
{
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep); //time shift handled in CTimeSeries::Parse
if ((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _HYDRO << "," << val; }
else { _HYDRO << ","; }
}
}
}
if (_pSubBasins[p]->GetReservoir() != NULL){
_HYDRO<<","<<_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
}
}
}
_HYDRO<<endl;
}
else //point value hydrograph or t==0
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
_HYDRO<<t<<","<<thisdate<<","<<thishour;
if(t!=0){ _HYDRO<<","<<GetAveragePrecip(); }//watershed-wide precip
else { _HYDRO<<",---"; }
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<","<<_pSubBasins[p]->GetOutflowRate();
//if (Options.print_obs_hydro)
{
for(i = 0; i < _nObservedTS; i++){
if(IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep);
if((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _HYDRO << "," << val; }
else { _HYDRO << ","; }
}
}
}
if(_pSubBasins[p]->GetReservoir() != NULL){
_HYDRO<<","<<_pSubBasins[p]->GetReservoirInflow();
}
}
}
_HYDRO<<endl;
}
}
}
else if (Options.output_format==OUTPUT_ENSIM)
{
WriteEnsimMinorOutput(Options,tt);
}
else if (Options.output_format==OUTPUT_NETCDF)
{
WriteNetcdfMinorOutput(Options,tt);
}
//Write cumulative mass balance info to HRUGroup_MassEnergyBalance.csv
//----------------------------------------------------------------
if (Options.write_group_mb!=DOESNT_EXIST)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
double sum;
int kk=Options.write_group_mb;
ofstream HGMB;
tmpFilename=FilenamePrepare(_pHRUGroups[kk]->GetName()+"_MassEnergyBalance.csv",Options);
HGMB.open(tmpFilename.c_str(),ios::app);
HGMB<<usetime<<","<<usedate<<","<<usehour;
double areasum=0.0;
for(k = 0; k < _nHydroUnits; k++){
if(_pHRUGroups[kk]->IsInGroup(k)){
areasum+=_pHydroUnits[k]->GetArea();
}
}
for(int js=0;js<_nTotalConnections;js++)
{
sum=0.0;
for(k = 0; k < _nHydroUnits; k++){
if(_pHRUGroups[kk]->IsInGroup(k)){
sum += _aCumulativeBal[k][js] * _pHydroUnits[k]->GetArea();
}
}
HGMB<<","<<sum/areasum;
}
HGMB<<endl;
HGMB.close();
}
}
//Write cumulative mass balance info to WatershedMassEnergyBalance.csv
//----------------------------------------------------------------
if (Options.write_mass_bal)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
double sum;
ofstream MB;
tmpFilename=FilenamePrepare("WatershedMassEnergyBalance.csv",Options);
MB.open(tmpFilename.c_str(),ios::app);
MB<<usetime<<","<<usedate<<","<<usehour;
for(int js=0;js<_nTotalConnections;js++)
{
sum=0.0;
for(k=0;k<_nHydroUnits;k++){
if(_pHydroUnits[k]->IsEnabled())
{
sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea();
}
}
MB<<","<<sum/_WatershedArea;
}
MB<<endl;
MB.close();
}
}
//ReservoirStages.csv
//--------------------------------------------------------------
if ((Options.write_reservoir) && (Options.output_format!=OUTPUT_NONE))
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
_RESSTAGE<< t<<","<<thisdate<<","<<thishour<<","<<GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++){
if ((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
_RESSTAGE<<","<<_pSubBasins[p]->GetReservoir()->GetResStage();
}
//if (Options.print_obs_hydro)
{
for (i = 0; i < _nObservedTS; i++){
if (IsContinuousStageObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep);
if ((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _RESSTAGE << "," << val; }
else { _RESSTAGE << ","; }
}
}
}
}
_RESSTAGE<<endl;
}
}
//Demands.csv
//----------------------------------------------------------------
if((Options.write_demandfile) && (Options.output_format!=OUTPUT_NONE))
{
if((Options.period_starting) && (t==0)) {}//don't write anything at time zero
else {
_DEMANDS<< t<<","<<thisdate<<","<<thishour;
for(int p=0;p<_nSubBasins;p++) {
if((_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->HasIrrigationDemand()))
{
double irr =_pSubBasins[p]->GetIrrigationDemand(tt.model_time);
double eF =_pSubBasins[p]->GetEnviroMinFlow (tt.model_time);
double Q =_pSubBasins[p]->GetOutflowRate (); //AFTER irrigation removed
double Qirr=_pSubBasins[p]->GetIrrigationRate ();
double unmet=max(irr-Qirr,0.0);
_DEMANDS<<","<<Q<<","<<irr<<","<<eF<<","<<unmet;
}
}
_DEMANDS<<endl;
}
}
//ReservoirMassBalance.csv
//----------------------------------------------------------------
if((Options.write_reservoirMB) && (Options.output_format!=OUTPUT_NONE))
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
ofstream RES_MB;
tmpFilename=FilenamePrepare("ReservoirMassBalance.csv",Options);
RES_MB.open(tmpFilename.c_str(),ios::app);
if(RES_MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
RES_MB<< usetime<<","<<usedate<<","<<usehour<<","<<GetAveragePrecip();
double in,out,loss,stor,oldstor;
for(int p=0;p<_nSubBasins;p++){
if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
string name,constraint_str;
if(_pSubBasins[p]->GetName()==""){ name=to_string(_pSubBasins[p]->GetID())+"="+to_string(_pSubBasins[p]->GetID()); }
else { name=_pSubBasins[p]->GetName(); }
in =_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep);//m3
out =_pSubBasins[p]->GetIntegratedOutflow(Options.timestep);//m3
stor =_pSubBasins[p]->GetReservoir()->GetStorage();//m3
oldstor=_pSubBasins[p]->GetReservoir()->GetOldStorage();//m3
loss =_pSubBasins[p]->GetReservoir()->GetReservoirLosses(Options.timestep);//m3
constraint_str=_pSubBasins[p]->GetReservoir()->GetCurrentConstraint();
if(tt.model_time==0.0){ in=0.0; }
RES_MB<<","<<in<<","<<out<<","<<stor<<","<<loss<<","<<in-out-loss-(stor-oldstor)<<","<<constraint_str;
}
}
RES_MB<<endl;
RES_MB.close();
}
}
// WatershedEnergyStorage.csv
//----------------------------------------------------------------
double sum=0.0;
if (Options.write_energy)
{
force_struct F=GetAverageForcings();
ofstream EN_STORAGE;
tmpFilename=FilenamePrepare("WatershedEnergyStorage.csv",Options);
EN_STORAGE.open(tmpFilename.c_str(),ios::app);
EN_STORAGE<<t<<","<<thisdate<<","<<thishour;
EN_STORAGE<<","<<F.temp_ave;
EN_STORAGE<<",TMP_DEBUG";
// STOR<<","<<GetAverageNetRadiation();//TMP DEBUG
for (i=0;i<GetNumStateVars();i++)
{
if (CStateVariable::IsEnergyStorage(_aStateVarType[i]))
{
S=GetAvgStateVar(i);
if (!silent){cout<<" |"<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<S;}
EN_STORAGE<<","<<S;
sum+=S;
}
}
EN_STORAGE<<","<<sum<<","<<_CumEnergyGain<<","<<_CumEnergyLoss<<","<<_CumEnergyGain-sum-_CumEnergyLoss;
EN_STORAGE<<endl;
EN_STORAGE.close();
}
if (!silent){cout<<endl;}
// ExhaustiveMassBalance.csv
//--------------------------------------------------------------
if (Options.write_exhaustiveMB)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
int j,js,q;
double cumsum;
ofstream MB;
tmpFilename=FilenamePrepare("ExhaustiveMassBalance.csv",Options);
MB.open(tmpFilename.c_str(),ios::app);
MB<<usetime<<","<<usedate<<","<<usehour;
for(i=0;i<_nStateVars;i++)
{
if(CStateVariable::IsWaterStorage(_aStateVarType[i]))
{
cumsum=0.0;
js=0;
for(j=0;j<_nProcesses;j++){
for(q=0;q<_pProcesses[j]->GetNumConnections();q++){
if(_pProcesses[j]->GetFromIndices()[q]==i)
{
sum=0.0;
for(k=0;k<_nHydroUnits;k++){
if(_pHydroUnits[k]->IsEnabled())
{
sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea();
}
}
MB<<","<<-sum/_WatershedArea;
cumsum-=sum/_WatershedArea;
}
js++;
}
}
js=0;
for(j=0;j<_nProcesses;j++){
for(q=0;q<_pProcesses[j]->GetNumConnections();q++){
if(_pProcesses[j]->GetToIndices()[q]==i)
{
sum=0.0;
for(k=0;k<_nHydroUnits;k++){
if(_pHydroUnits[k]->IsEnabled())
{
sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea();
}
}
MB<<","<<sum/_WatershedArea;
cumsum+=sum/_WatershedArea;
}
js++;
}
}
js=0;
bool found;
for(j=0;j<_nProcesses;j++){
sum=0;
found=false;
for(q=0;q<_pProcesses[j]->GetNumLatConnections();q++){
CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]);
if (pProc->GetLateralToIndices()[q]==i){
sum+=_aCumulativeLatBal[js];found=true;
}
if (pProc->GetLateralFromIndices()[q]==i){
sum-=_aCumulativeLatBal[js];found=true;
}
js++;
}
if((_pProcesses[j]->GetNumLatConnections()>0) && (found==true)){
MB<<","<<sum/_WatershedArea;
cumsum+=sum/_WatershedArea;
}
}
//Cumulative, storage, error
double Initial_i=0.0; //< \todo [bug] need to evaluate and store initial storage actross watershed!!!
MB<<","<<cumsum<<","<<GetAvgStateVar(i)<<","<<cumsum-GetAvgStateVar(i)-Initial_i;
}
}
MB<<endl;
MB.close();
}
}
// ForcingFunctions.csv
//----------------------------------------------------------------
if (Options.write_forcings)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
force_struct *pFave;
force_struct faveStruct = GetAverageForcings();
pFave = &faveStruct;
_FORCINGS<<usetime<<","<<usedate<<","<<usehour<<",";
_FORCINGS<<pFave->day_angle<<",";
_FORCINGS<<pFave->precip*(1-pFave->snow_frac) <<",";
_FORCINGS<<pFave->precip*(pFave->snow_frac) <<",";
_FORCINGS<<pFave->temp_ave<<",";
_FORCINGS<<pFave->temp_daily_min<<",";
_FORCINGS<<pFave->temp_daily_max<<",";
_FORCINGS<<pFave->temp_daily_ave<<",";
_FORCINGS<<pFave->temp_month_min<<",";
_FORCINGS<<pFave->temp_month_max<<",";
_FORCINGS<<pFave->air_dens<<",";
_FORCINGS<<pFave->air_pres<<",";
_FORCINGS<<pFave->rel_humidity<<",";
_FORCINGS<<pFave->cloud_cover<<",";
_FORCINGS<<pFave->ET_radia<<",";
_FORCINGS<<pFave->SW_radia<<",";
_FORCINGS<<pFave->SW_radia_net<<",";
//_FORCINGS<<pFave->LW_incoming<<",";
_FORCINGS<<pFave->LW_radia_net<<",";
_FORCINGS<<pFave->wind_vel<<",";
_FORCINGS<<pFave->PET<<",";
_FORCINGS<<pFave->OW_PET<<",";
_FORCINGS<<pFave->subdaily_corr<<",";
_FORCINGS<<pFave->potential_melt;
_FORCINGS<<endl;
}
}
// Transport output files
//--------------------------------------------------------------
if (Options.output_format==OUTPUT_STANDARD)
{
_pTransModel->WriteMinorOutput(Options,tt);
}
else if (Options.output_format==OUTPUT_ENSIM)
{
_pTransModel->WriteEnsimMinorOutput(Options,tt);
}
// Groundwater output files
//--------------------------------------------------------------
_pGWModel->WriteMinorOutput(Options,tt);
// raven_debug.csv
//--------------------------------------------------------------
if (Options.debug_mode)
{
ofstream DEBUG;
tmpFilename=FilenamePrepare("raven_debug.csv",Options);
DEBUG.open(tmpFilename.c_str(),ios::app);
DEBUG<<t<<","<<thisdate<<","<<thishour;
for(i=0;i<10;i++){DEBUG<<","<<g_debug_vars[i];}
DEBUG<<endl;
DEBUG.close();
}
// HRU storage output
//--------------------------------------------------------------
if (_pOutputGroup!=NULL)
{
for (int kk=0;kk<_pOutputGroup->GetNumHRUs();kk++)
{
ofstream HRUSTOR;
tmpFilename="HRUStorage_"+to_string(_pOutputGroup->GetHRU(kk)->GetID())+".csv";
tmpFilename=FilenamePrepare(tmpFilename,Options);
HRUSTOR.open(tmpFilename.c_str(),ios::app);
const force_struct *F=_pOutputGroup->GetHRU(kk)->GetForcingFunctions();
HRUSTOR<<tt.model_time <<","<<thisdate<<","<<thishour;//instantaneous -no period starting correction
if (t!=0){HRUSTOR<<","<<F->precip*(1-F->snow_frac)<<","<<F->precip*(F->snow_frac);}//precip
else {HRUSTOR<<",---,---";}
currentWater=0;
for (i=0;i<GetNumStateVars();i++)
{
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip))
{
S=_pOutputGroup->GetHRU(kk)->GetStateVarValue(i);
HRUSTOR<<","<<S;
currentWater+=S;
}
}
HRUSTOR<<","<<currentWater;
HRUSTOR<<endl;
HRUSTOR.close();
}
}
} // end of write output interval if statement
// Custom output files
//--------------------------------------------------------------
for (int c=0;c<_nCustomOutputs;c++)
{
_pCustomOutputs[c]->WriteCustomOutput(tt,Options);
}
// Write major output, if necessary
//--------------------------------------------------------------
if ((_nOutputTimes>0) && (tt.model_time>_aOutputTimes[_currOutputTimeInd]-0.5*Options.timestep))
{
_currOutputTimeInd++;
tmpFilename="state_"+tt.date_string;
WriteMajorOutput(tmpFilename,Options,tt,false);
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes major output to file at the end of simulation
/// \details Writes:
/// - Solution file of all state variables; and
/// - Autogenerated parameters
///
/// \param &Options [in] Global model options information
//
void CModel::WriteMajorOutput(string solfile, const optStruct &Options, const time_struct &tt, bool final) const
{
int i,k;
string tmpFilename;
// WRITE {RunName}_solution.rvc - final state variables file
ofstream OUT;
tmpFilename=FilenamePrepare(solfile+".rvc",Options);
OUT.open(tmpFilename.c_str());
if (OUT.fail()){
WriteWarning(("CModel::WriteMajorOutput: Unable to open output file "+tmpFilename+" for writing.").c_str(),Options.noisy);
}
OUT<<":TimeStamp "<<tt.date_string<<" "<<DecDaysToHours(tt.julian_day)<<endl;
//Header--------------------------
OUT<<":HRUStateVariableTable"<<endl;
OUT<<" :Attributes,";
for (i=0;i<GetNumStateVars();i++)
{
OUT<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i]);
if (i!=GetNumStateVars()-1){OUT<<",";}
}
OUT<<endl;
OUT<<" :Units,";
for (i=0;i<GetNumStateVars();i++)
{
OUT<<CStateVariable::GetStateVarUnits(_aStateVarType[i]);
if (i!=GetNumStateVars()-1){OUT<<",";}
}
OUT<<endl;
//Data----------------------------
for (k=0;k<_nHydroUnits;k++)
{
OUT<<std::fixed; OUT.precision(5);
OUT<<" "<<_pHydroUnits[k]->GetID()<<",";
for (i=0;i<GetNumStateVars();i++)
{
OUT<<_pHydroUnits[k]->GetStateVarValue(i);
if (i!=GetNumStateVars()-1){OUT<<",";}
}
OUT<<endl;
}
OUT<<":EndHRUStateVariableTable"<<endl;
//By basin------------------------
OUT<<":BasinStateVariables"<<endl;
for (int p=0;p<_nSubBasins;p++){
OUT<<" :BasinIndex "<<_pSubBasins[p]->GetID()<<",";
_pSubBasins[p]->WriteToSolutionFile(OUT);
}
OUT<<":EndBasinStateVariables"<<endl;
OUT.close();
if(Options.write_channels){
CChannelXSect::WriteRatingCurves();
}
if(Options.write_basinfile) {
ofstream BASIN;
tmpFilename=FilenamePrepare("SubbasinParams.csv",Options);
BASIN.open(tmpFilename.c_str());
if(BASIN.fail()) {
WriteWarning(("CModel::WriteMajorOutput: Unable to open output file "+tmpFilename+" for writing.").c_str(),Options.noisy);
}
BASIN<<"SBID,Reference Discharge [m3/s],Reach Length [m],Reach Celerity [m/s],Reach Diffusivity [m2/s]"<<endl;
for(int p=0;p<_nSubBasins;p++) {
BASIN<<_pSubBasins[p]->GetID()<<","<<_pSubBasins[p]->GetReferenceFlow()<<","<<_pSubBasins[p]->GetReachLength()<<",";
BASIN<<_pSubBasins[p]->GetReferenceCelerity()<<","<<_pSubBasins[p]->GetDiffusivity()<<endl;
}
BASIN.close();
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes progress file in JSON format (mainly for PAVICS runs)
/// Looks like:
/// {
/// "% progress": 65,
/// "seconds remaining": 123
/// }
///
/// \note Does not account for initialization (reading) and final writing of model outputs. Only pure modeling time.
///
/// \param &Options [in] Global model options information
/// \param &elapsed_time [in] elapsed time (computational time markers)
/// \param elapsed_steps [in] elapsed number of simulation steps to perform (to determine % progress)
/// \param total_steps [in] total number of simulation steps to perform (to determine % progress)
//
void CModel::WriteProgressOutput(const optStruct &Options, clock_t elapsed_time, int elapsed_steps, int total_steps)
{
if (Options.pavics)
{
ofstream PROGRESS;
PROGRESS.open((Options.main_output_dir+"Raven_progress.txt").c_str());
if (PROGRESS.fail()){
PROGRESS.close();
ExitGracefully("ParseInput:: Unable to open Raven_progress.txt. Bad output directory specified?",RUNTIME_ERR);
}
float total_time = (float(total_steps) * float(elapsed_time) / float(elapsed_steps)) / CLOCKS_PER_SEC;
if (Options.benchmarking){ total_time =float(elapsed_time);}
PROGRESS<<"{"<<endl;
PROGRESS<<" \"% progress\": " << int( float(elapsed_steps) * 100.0 / float(total_steps) ) <<","<< endl;
PROGRESS<<" \"seconds remaining\": "<< total_time - float(elapsed_time) / CLOCKS_PER_SEC <<endl;
PROGRESS<<"}"<<endl;
PROGRESS.close();
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes model summary information to screen
/// \param &Options [in] Global model options information
//
void CModel::SummarizeToScreen (const optStruct &Options) const
{
int rescount=0;
for (int p = 0; p < _nSubBasins; p++){
if (_pSubBasins[p]->GetReservoir() != NULL){rescount++;}
}
int disablecount=0;
double allarea=0.0;
for(int k=0;k<_nHydroUnits; k++){
if(!_pHydroUnits[k]->IsEnabled()){disablecount++;}
allarea+=_pHydroUnits[k]->GetArea();
}
int SBdisablecount=0;
for(int p=0;p<_nSubBasins; p++){
if(!_pSubBasins[p]->IsEnabled()){SBdisablecount++;}
}
if(!Options.silent){
cout <<"==MODEL SUMMARY======================================="<<endl;
cout <<" Model Run: "<<Options.run_name <<endl;
cout <<" rvi filename: "<<Options.rvi_filename<<endl;
cout <<"Output Directory: "<<Options.main_output_dir <<endl;
cout <<" # SubBasins: "<<GetNumSubBasins() << " ("<< rescount << " reservoirs) ("<<SBdisablecount<<" disabled)"<<endl;
cout <<" # HRUs: "<<GetNumHRUs() << " ("<<disablecount<<" disabled)"<<endl;
cout <<" # Gauges: "<<GetNumGauges() <<endl;
cout <<"#State Variables: "<<GetNumStateVars() <<endl;
for (int i=0;i<GetNumStateVars();i++){
//don't write if convolution storage or advection storage?
cout<<" - ";
cout<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" (";
cout<<CStateVariable::SVTypeToString (_aStateVarType[i],_aStateVarLayer[i])<<")"<<endl;
}
cout <<" # Processes: "<<GetNumProcesses() <<endl;
for (int j=0;j<GetNumProcesses();j++)
{
cout<<" - ";
cout<<GetProcessName(GetProcessType(j))<<endl;
}
cout <<" #Connections: "<<_nTotalConnections <<endl;
cout <<"#Lat.Connections: "<<_nTotalLatConnections <<endl;
cout <<" Duration: "<<Options.duration <<" d"<<endl;
cout <<" Time step: "<<Options.timestep <<" d"<<endl;
cout <<" Watershed Area: "<<_WatershedArea <<" km2 (simulated) of "<<allarea<<" km2"<<endl;
cout <<"======================================================"<<endl;
cout <<endl;
if((Options.modeltype == MODELTYPE_COUPLED) || (Options.modeltype == MODELTYPE_GROUNDWATER))
{
cout <<"==GROUNDWATER SUMMARY================================"<<endl;
//CAquiferStack::SummarizeToScreen();
CGWGeometryClass::SummarizeToScreen();
CGWStressPeriodClass::SummarizeToScreen();
COverlapExchangeClass::SummarizeToScreen();
cout <<"====================================================="<<endl;
}
}
}
//////////////////////////////////////////////////////////////////
/// \brief run model diagnostics (at end of simulation)
///
/// \param &Options [in] global model options
//
void CModel::RunDiagnostics (const optStruct &Options)
{
if ((_nObservedTS==0) || (_nDiagnostics==0)) {return;}
ofstream DIAG;
string tmpFilename;
tmpFilename=FilenamePrepare("Diagnostics.csv",Options);
DIAG.open(tmpFilename.c_str());
if (DIAG.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
//header
DIAG<<"observed data series,filename,";
for (int j=0; j<_nDiagnostics;j++){
DIAG<<_pDiagnostics[j]->GetName()<<",";
}
DIAG<<endl;
//body
for (int i=0;i<_nObservedTS;i++)
{
DIAG<<_pObservedTS[i]->GetName()<<","<<_pObservedTS[i]->GetSourceFile() <<",";
for (int j=0; j<_nDiagnostics;j++){
DIAG<<_pDiagnostics[j]->CalculateDiagnostic(_pModeledTS[i],_pObservedTS[i],_pObsWeightTS[i],Options)<<",";
}
DIAG<<endl;
}
DIAG.close();
}
//////////////////////////////////////////////////////////////////
/// \brief Writes output headers for WatershedStorage.tb0 and Hydrographs.tb0
///
/// \param &Options [in] global model options
//
void CModel::WriteEnsimStandardHeaders(const optStruct &Options)
{
int i;
time_struct tt, tt2;
JulianConvert(0.0, Options.julian_start_day, Options.julian_start_year, Options.calendar, tt);//start of the timestep
JulianConvert(Options.timestep, Options.julian_start_day, Options.julian_start_year, Options.calendar, tt2);//end of the timestep
//WatershedStorage.tb0
//--------------------------------------------------------------
int iAtmPrecip = GetStateVarIndex(ATMOS_PRECIP);
string tmpFilename;
if (Options.write_watershed_storage)
{
tmpFilename = FilenamePrepare("WatershedStorage.tb0", Options);
_STORAGE.open(tmpFilename.c_str());
if (_STORAGE.fail()){
ExitGracefully(("CModel::WriteEnsimStandardHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_STORAGE << "#########################################################################" << endl;
_STORAGE << ":FileType tb0 ASCII EnSim 1.0" << endl;
_STORAGE << "#" << endl;
_STORAGE << ":Application Raven" << endl;
if(!Options.benchmarking){
_STORAGE << ":Version " << Options.version << endl;
_STORAGE << ":CreationDate " << GetCurrentTime() << endl;
}
_STORAGE << "#" << endl;
_STORAGE << "#------------------------------------------------------------------------" << endl;
_STORAGE << "#" << endl;
_STORAGE << ":RunName " << Options.run_name << endl;
_STORAGE << ":Format Instantaneous" << endl;
_STORAGE << "#" << endl;
if (Options.suppressICs){
_STORAGE << ":StartTime " << tt2.date_string << " " << DecDaysToHours(tt2.julian_day) << endl;
}
else{
_STORAGE << ":StartTime " << tt.date_string << " " << DecDaysToHours(tt.julian_day) << endl;
}
if (Options.timestep != 1.0){ _STORAGE << ":DeltaT " << DecDaysToHours(Options.timestep) << endl; }
else { _STORAGE << ":DeltaT 24:00:00.00" << endl; }
_STORAGE << "#" << endl;
_STORAGE<<":ColumnMetaData"<<endl;
_STORAGE<<" :ColumnName rainfall snowfall \"Channel storage\" \"Rivulet storage\"";
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){
_STORAGE<<" \""<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<"\"";}}
_STORAGE<<" \"Total storage\" \"Cum. precip\" \"Cum. outflow\" \"MB error\""<<endl;
_STORAGE<<" :ColumnUnits mm/d mm/d mm mm ";
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){_STORAGE<<" mm";}}
_STORAGE<<" mm mm mm mm"<<endl;
_STORAGE<<" :ColumnType float float float float";
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){_STORAGE<<" float";}}
_STORAGE<<" float float float float"<<endl;
_STORAGE << " :ColumnFormat -1 -1 0 0";
for (i = 0; i < GetNumStateVars(); i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i != iAtmPrecip)){
_STORAGE << " 0";
}
}
_STORAGE << " 0 0 0 0" << endl;
_STORAGE << ":EndColumnMetaData" << endl;
_STORAGE << ":EndHeader" << endl;
}
//Hydrographs.tb0
//--------------------------------------------------------------
tmpFilename = FilenamePrepare("Hydrographs.tb0", Options);
_HYDRO.open(tmpFilename.c_str());
if (_HYDRO.fail()){
ExitGracefully(("CModel::WriteEnsimStandardHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_HYDRO << "#########################################################################" << endl;
_HYDRO << ":FileType tb0 ASCII EnSim 1.0" << endl;
_HYDRO << "#" << endl;
_HYDRO << ":Application Raven" << endl;
if(!Options.benchmarking){
_HYDRO << ":Version " << Options.version << endl;
_HYDRO << ":CreationDate " << GetCurrentTime() << endl;
}
_HYDRO << "#" << endl;
_HYDRO << "#------------------------------------------------------------------------" << endl;
_HYDRO << "#" << endl;
_HYDRO << ":RunName " << Options.run_name << endl;
_HYDRO << "#" << endl;
if (Options.ave_hydrograph){
_HYDRO << ":Format PeriodEnding" << endl;
}
else{
_HYDRO << ":Format Instantaneous" << endl;
}
if (((Options.period_ending) && (Options.ave_hydrograph)) || (Options.suppressICs )){
_HYDRO << ":StartTime " << tt2.date_string << " " << DecDaysToHours(tt2.julian_day) << endl;
}
else{
_HYDRO << ":StartTime " << tt.date_string << " " << DecDaysToHours(tt.julian_day) << endl;
}
if (Options.timestep!=1.0){_HYDRO<<":DeltaT " <<DecDaysToHours(Options.timestep)<<endl;}
else {_HYDRO<<":DeltaT 24:00:00.00" <<endl;}
_HYDRO<<"#"<<endl;
double val = 0; //snapshot hydrograph
double val2=1;
if (Options.ave_hydrograph){ val = 1; } //continuous hydrograph
if (Options.period_ending) { val *= -1; val2*=-1;}//period ending
_HYDRO<<":ColumnMetaData"<<endl;
_HYDRO<<" :ColumnName precip";
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" Q_"<<_pSubBasins[p]->GetID();}_HYDRO<<endl;
_HYDRO<<" :ColumnUnits mm/d";
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" m3/s";}_HYDRO<<endl;
_HYDRO<<" :ColumnType float";
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" float";}_HYDRO<<endl;
_HYDRO<<" :ColumnFormat "<<val2;
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" "<<val;}_HYDRO<<endl;
_HYDRO<<":EndColumnMetaData"<<endl;
_HYDRO<<":EndHeader"<<endl;
}
//////////////////////////////////////////////////////////////////
/// \brief Writes output headers for WatershedStorage.nc and Hydrographs.nc
///
/// \param &Options [in] global model options
/// original code developed by J. Mai
//
void CModel::WriteNetcdfStandardHeaders(const optStruct &Options)
{
#ifdef _RVNETCDF_
time_struct tt; // start time structure
const int ndims1 = 1;
const int ndims2 = 2;
int dimids1[ndims1]; // array which will contain all dimension ids for a variable
int ncid, varid_pre; // When we create netCDF variables and dimensions, we get back an ID for each one.
int time_dimid, varid_time; // dimension ID (holds number of time steps) and variable ID (holds time values) for time
int nSim, nbasins_dimid, varid_bsim; // # of sub-basins with simulated outflow, dimension ID, and
// // variable to write basin IDs for simulated outflows
int varid_qsim; // variable ID for simulated outflows
int varid_qobs; // variable ID for observed outflows
int varid_qin; // variable ID for observed inflows
int retval; // error value for NetCDF routines
string tmpFilename;
int ibasin, p; // loop over all sub-basins
size_t start[1], count[1]; // determines where and how much will be written to NetCDF
const char *current_basin_name[1]; // current time in days since start time
string tmp,tmp2,tmp3;
// initialize all potential file IDs with -9 == "not existing and hence not opened"
_HYDRO_ncid = -9; // output file ID for Hydrographs.nc (-9 --> not opened)
_STORAGE_ncid = -9; // output file ID for WatershedStorage.nc (-9 --> not opened)
_FORCINGS_ncid = -9; // output file ID for ForcingFunctions.nc (-9 --> not opened)
//converts start day into "days since YYYY-MM-DD HH:MM:SS" (model start time)
char starttime[200]; // start time string in format 'days since YYY-MM-DD HH:MM:SS'
JulianConvert( 0.0,Options.julian_start_day, Options.julian_start_year, Options.calendar, tt);
strcpy(starttime, "days since ") ;
strcat(starttime, tt.date_string.c_str()) ;
strcat(starttime, " ");
strcat(starttime, DecDaysToHours(tt.julian_day,true).c_str());
if(Options.time_zone!=0) { strcat(starttime,TimeZoneToString(Options.time_zone).c_str()); }
//====================================================================
// Hydrographs.nc
//====================================================================
// Create the file.
tmpFilename = FilenamePrepare("Hydrographs.nc", Options);
retval = nc_create(tmpFilename.c_str(), NC_CLOBBER|NC_NETCDF4, &ncid); HandleNetCDFErrors(retval);
_HYDRO_ncid = ncid;
// ----------------------------------------------------------
// global attributes
// ----------------------------------------------------------
WriteNetCDFGlobalAttributes(_HYDRO_ncid,Options,"Standard Output");
// ----------------------------------------------------------
// time
// ----------------------------------------------------------
// (a) Define the DIMENSIONS. NetCDF will hand back an ID
retval = nc_def_dim(_HYDRO_ncid, "time", NC_UNLIMITED, &time_dimid); HandleNetCDFErrors(retval);
/// Define the time variable. Assign units attributes to the netCDF VARIABLES.
dimids1[0] = time_dimid;
retval = nc_def_var(_HYDRO_ncid, "time", NC_DOUBLE, ndims1,dimids1, &varid_time); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_time, "units" , strlen(starttime) , starttime); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_time, "calendar", strlen("gregorian"), "gregorian"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_time, "standard_name", strlen("time"), "time"); HandleNetCDFErrors(retval);
// define precipitation variable
varid_pre= NetCDFAddMetadata(_HYDRO_ncid, time_dimid,"precip","Precipitation","mm d**-1");
// ----------------------------------------------------------
// simulated/observed outflows
// ----------------------------------------------------------
// (a) count number of simulated outflows "nSim"
nSim = 0;
for (p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){nSim++;}
}
if (nSim > 0)
{
// (b) create dimension "nbasins"
retval = nc_def_dim(_HYDRO_ncid, "nbasins", nSim, &nbasins_dimid); HandleNetCDFErrors(retval);
// (c) create variable and set attributes for"basin_name"
dimids1[0] = nbasins_dimid;
retval = nc_def_var(_HYDRO_ncid, "basin_name", NC_STRING, ndims1, dimids1, &varid_bsim); HandleNetCDFErrors(retval);
tmp ="Name/ID of sub-basins with simulated outflows";
tmp2="timeseries_id";
tmp3="1";
retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "long_name", tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "cf_role" , tmp2.length(),tmp2.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "units" , tmp3.length(),tmp3.c_str()); HandleNetCDFErrors(retval);
varid_qsim= NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_sim","Simulated outflows","m**3 s**-1");
varid_qobs= NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_obs","Observed outflows" ,"m**3 s**-1");
varid_qin = NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_in" ,"Observed inflows" ,"m**3 s**-1");
}// end if nSim>0
// End define mode. This tells netCDF we are done defining metadata.
retval = nc_enddef(_HYDRO_ncid); HandleNetCDFErrors(retval);
// write values to NetCDF
// (a) write gauged basin names/IDs to variable "basin_name"
ibasin = 0;
for(p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){
if(_pSubBasins[p]->GetName()==""){ current_basin_name[0] = (to_string(_pSubBasins[p]->GetID())).c_str(); }
else { current_basin_name[0] = (_pSubBasins[p]->GetName()).c_str(); }
// write sub-basin name
start[0] = ibasin;
count[0] = 1;
retval = nc_put_vara_string(_HYDRO_ncid,varid_bsim,start,count,¤t_basin_name[0]); HandleNetCDFErrors(retval);
ibasin++;
}
}
//====================================================================
// WatershedStorage.nc
//====================================================================
if (Options.write_watershed_storage)
{
tmpFilename = FilenamePrepare("WatershedStorage.nc", Options);
retval = nc_create(tmpFilename.c_str(), NC_CLOBBER|NC_NETCDF4, &ncid); HandleNetCDFErrors(retval);
_STORAGE_ncid = ncid;
// ----------------------------------------------------------
// global attributes
// ----------------------------------------------------------
WriteNetCDFGlobalAttributes(_STORAGE_ncid,Options,"Standard Output");
// ----------------------------------------------------------
// time vector
// ----------------------------------------------------------
// Define the DIMENSIONS. NetCDF will hand back an ID
retval = nc_def_dim(_STORAGE_ncid, "time", NC_UNLIMITED, &time_dimid); HandleNetCDFErrors(retval);
/// Define the time variable.
dimids1[0] = time_dimid;
retval = nc_def_var(_STORAGE_ncid, "time", NC_DOUBLE, ndims1,dimids1, &varid_time); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_STORAGE_ncid, varid_time, "units" , strlen(starttime) , starttime); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_STORAGE_ncid, varid_time, "calendar", strlen("gregorian"), "gregorian"); HandleNetCDFErrors(retval);
// ----------------------------------------------------------
// precipitation / channel storage / state vars / MB diagnostics
// ----------------------------------------------------------
int varid;
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"rainfall","rainfall","mm d**-1");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"snowfall","snowfall","mm d**-1");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Channel Storage","Channel Storage","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Reservoir Storage","Reservoir Storage","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Rivulet Storage","Rivulet Storage","mm");
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
for(int i=0;i<_nStateVars;i++){
if((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){
string name =CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i]);
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,name,name,"mm");
}
}
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Total","total water storage","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Cum. Input","cumulative water input","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Cum. Outflow","cumulative water output","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"MB Error","mass balance error","mm");
// End define mode. This tells netCDF we are done defining metadata.
retval = nc_enddef(_STORAGE_ncid); HandleNetCDFErrors(retval);
}
//====================================================================
// ForcingFunctions.nc
//====================================================================
if(Options.write_forcings)
{
tmpFilename = FilenamePrepare("ForcingFunctions.nc",Options);
retval = nc_create(tmpFilename.c_str(),NC_CLOBBER|NC_NETCDF4,&ncid); HandleNetCDFErrors(retval);
_FORCINGS_ncid = ncid;
WriteNetCDFGlobalAttributes(_FORCINGS_ncid,Options,"Standard Output");
// ----------------------------------------------------------
// time vector
// ----------------------------------------------------------
retval = nc_def_dim(_FORCINGS_ncid,"time",NC_UNLIMITED,&time_dimid); HandleNetCDFErrors(retval);
dimids1[0] = time_dimid;
retval = nc_def_var(_FORCINGS_ncid,"time",NC_DOUBLE,ndims1,dimids1,&varid_time); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_FORCINGS_ncid,varid_time,"units",strlen(starttime),starttime); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_FORCINGS_ncid,varid_time,"calendar",strlen("gregorian"),"gregorian"); HandleNetCDFErrors(retval);
// ----------------------------------------------------------
int varid;
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"rainfall","rainfall","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"snowfall","snowfall","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp","temp","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_min","temp_daily_min","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_max","temp_daily_max","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_ave","temp_daily_ave","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"air density","air density","kg m**-3");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"air pressure","air pressure","kPa");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"relative humidity","relative humidity","");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"cloud cover","cloud cover","");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"ET radiation","ET radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"SW radiation","SW radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"net SW radiation","net SW radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"LW radiation","LW radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"wind velocity","wind velocity","m s**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"PET","PET","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"OW PET","OW PET","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"potential melt","potential melt","mm d**-1");
// End define mode. This tells netCDF we are done defining metadata.
retval = nc_enddef(_FORCINGS_ncid); HandleNetCDFErrors(retval);
}
#endif // end compilation if NetCDF library is available
}
//////////////////////////////////////////////////////////////////
/// \brief Writes minor output data to WatershedStorage.tb0 and Hydrographs.tb0
///
/// \param &Options [in] global model options
/// \param &tt [in] current time structure
/// \todo [reorg] merge with WriteMinorOutput - too much complex code repetition here when only difference is (1) delimeter and (2) timestep info included in the .csv file
//
void CModel::WriteEnsimMinorOutput (const optStruct &Options,
const time_struct &tt)
{
double currentWater;
double S;
int i;
int iCumPrecip=GetStateVarIndex(ATMOS_PRECIP);
double snowfall =GetAverageSnowfall();
double precip =GetAveragePrecip();
double channel_stor =GetTotalChannelStorage();
double reservoir_stor=GetTotalReservoirStorage();
double rivulet_stor =GetTotalRivuletStorage();
if ((tt.model_time==0) && (Options.suppressICs==true) && (Options.period_ending)){return;}
//----------------------------------------------------------------
// write watershed state variables (WatershedStorage.tb0)
if (Options.write_watershed_storage)
{
if (tt.model_time!=0){_STORAGE<<" "<<precip-snowfall<<" "<<snowfall;}//precip
else {_STORAGE<<" 0.0 0.0";}
_STORAGE<<" "<<channel_stor+reservoir_stor<<" "<<rivulet_stor;
currentWater=0.0;
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip)){
S=GetAvgStateVar(i);_STORAGE<<" "<<FormatDouble(S);currentWater+=S;
}
}
currentWater+=channel_stor+rivulet_stor;
if(tt.model_time==0){
// \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it
// JRC: I think somehow this is being double counted in the delta V calculations in the first timestep
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->GetReservoir()!=NULL){
currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
}
}
}
_STORAGE<<" "<<currentWater<<" "<<_CumulInput<<" "<<_CumulOutput<<" "<<FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput));
_STORAGE<<endl;
}
//----------------------------------------------------------------
//Write hydrographs for gauged watersheds (ALWAYS DONE) (Hydrographs.tb0)
if ((Options.ave_hydrograph) && (tt.model_time!=0))
{
_HYDRO<<" "<<GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<" "<<_pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
}
}
_HYDRO<<endl;
}
else
{
if (tt.model_time!=0){_HYDRO<<" "<<GetAveragePrecip();}
else {_HYDRO<<" 0.0";}
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<" "<<_pSubBasins[p]->GetOutflowRate();
}
}
_HYDRO<<endl;
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes minor output data to WatershedStorage.nc and Hydrographs.nc
///
/// \param &Options [in] global model options
/// \param &tt [in] current time structure
//
void CModel::WriteNetcdfMinorOutput ( const optStruct &Options,
const time_struct &tt)
{
#ifdef _RVNETCDF_
int retval; // error value for NetCDF routines
int time_id; // variable id in NetCDF for time
size_t time_index[1], count1[1]; // determines where and how much will be written to NetCDF; 1D variable (pre, time)
size_t start2[2], count2[2]; // determines where and how much will be written to NetCDF; 2D variable (qsim, qobs, qin)
double current_time[1]; // current time in days since start time
double current_prec[1]; // precipitation of current time step
size_t time_ind2;
current_time[0] = tt.model_time;
time_index [0] = int(round(tt.model_time/Options.timestep)); // element of NetCDF array that will be written
time_ind2 =int(round(tt.model_time/Options.timestep));
count1[0] = 1; // writes exactly one time step
//====================================================================
// Hydrographs.nc
//====================================================================
int precip_id; // variable id in NetCDF for precipitation
int qsim_id; // variable id in NetCDF for simulated outflow
int qobs_id; // variable id in NetCDF for observed outflow
int qin_id; // variable id in NetCDF for observed inflow
// (a) count how many values need to be written for q_obs, q_sim, q_in
int iSim, nSim; // current and total # of sub-basins with simulated outflows
nSim = 0;
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){nSim++;}
}
// (b) allocate memory if necessary
double *outflow_obs=NULL; // q_obs
double *outflow_sim=NULL; // q_sim
double *inflow_obs =NULL; // q_in
if(nSim>0){
outflow_sim=new double[nSim];
outflow_obs=new double[nSim];
inflow_obs =new double[nSim];
}
// (c) obtain data
iSim = 0;
current_prec[0] = NETCDF_BLANK_VALUE;
if ((Options.ave_hydrograph) && (current_time[0] != 0.0))
{
current_prec[0] = GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++)
{
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){
outflow_sim[iSim] = _pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
outflow_obs[iSim] = NETCDF_BLANK_VALUE;
for (int i = 0; i < _nObservedTS; i++){
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(current_time[0],Options.timestep); //time shift handled in CTimeSeries::Parse
if ((val != RAV_BLANK_DATA) && (current_time[0]>0)){ outflow_obs[iSim] = val; }
}
}
inflow_obs[iSim] =NETCDF_BLANK_VALUE;
if (_pSubBasins[p]->GetReservoir() != NULL){
inflow_obs[iSim] = _pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
}
iSim++;
}
}
}
else { // point-value hydrograph
if (current_time[0] != 0.0){current_prec[0] = GetAveragePrecip();} //watershed-wide precip
else {current_prec[0] = NETCDF_BLANK_VALUE;} // was originally '---'
for (int p=0;p<_nSubBasins;p++)
{
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){
outflow_sim[iSim] = _pSubBasins[p]->GetOutflowRate();
outflow_obs[iSim] = NETCDF_BLANK_VALUE;
for (int i = 0; i < _nObservedTS; i++){
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(current_time[0],Options.timestep);
if ((val != RAV_BLANK_DATA) && (current_time[0]>0)){ outflow_obs[iSim] = val; }
}
}
inflow_obs[iSim] =NETCDF_BLANK_VALUE;
if (_pSubBasins[p]->GetReservoir() != NULL){
inflow_obs[iSim] = _pSubBasins[p]->GetReservoirInflow();
}
iSim++;
}
}
}
// write new time step
retval = nc_inq_varid (_HYDRO_ncid, "time", &time_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, time_id, time_index, count1, ¤t_time[0]); HandleNetCDFErrors(retval);
// write precipitation values
retval = nc_inq_varid (_HYDRO_ncid, "precip", &precip_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid,precip_id,time_index,count1,¤t_prec[0]); HandleNetCDFErrors(retval);
// write simulated outflow/obs outflow/obs inflow values
if (nSim > 0){
start2[0] = int(round(current_time[0]/Options.timestep)); // element of NetCDF array that will be written
start2[1] = 0; // element of NetCDF array that will be written
count2[0] = 1; // writes exactly one time step
count2[1] = nSim; // writes exactly nSim elements
retval = nc_inq_varid (_HYDRO_ncid, "q_sim", &qsim_id); HandleNetCDFErrors(retval);
retval = nc_inq_varid (_HYDRO_ncid, "q_obs", &qobs_id); HandleNetCDFErrors(retval);
retval = nc_inq_varid (_HYDRO_ncid, "q_in", &qin_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, qsim_id, start2, count2, &outflow_sim[0]); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, qobs_id, start2, count2, &outflow_obs[0]); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, qin_id, start2, count2, &inflow_obs[0]); HandleNetCDFErrors(retval);
}
delete[] outflow_obs;
delete[] outflow_sim;
delete[] inflow_obs;
//====================================================================
// WatershedStorage.nc
//====================================================================
if (Options.write_watershed_storage)
{
double snowfall =GetAverageSnowfall();
double precip =GetAveragePrecip();
double channel_stor =GetTotalChannelStorage();
double reservoir_stor=GetTotalReservoirStorage();
double rivulet_stor =GetTotalRivuletStorage();
// write new time step
retval = nc_inq_varid (_STORAGE_ncid, "time", &time_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_STORAGE_ncid, time_id, time_index, count1, ¤t_time[0]); HandleNetCDFErrors(retval);
if(tt.model_time!=0){
AddSingleValueToNetCDF(_STORAGE_ncid,"rainfall" ,time_ind2,precip-snowfall);
AddSingleValueToNetCDF(_STORAGE_ncid,"snowfall" ,time_ind2,snowfall);
}
AddSingleValueToNetCDF(_STORAGE_ncid,"Channel Storage" ,time_ind2,channel_stor);
AddSingleValueToNetCDF(_STORAGE_ncid,"Reservoir Storage",time_ind2,reservoir_stor);
AddSingleValueToNetCDF(_STORAGE_ncid,"Rivulet Storage" ,time_ind2,rivulet_stor);
double currentWater=0.0;
double S;string short_name;
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
for (int i=0;i<GetNumStateVars();i++)
{
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip))
{
S=FormatDouble(GetAvgStateVar(i));
short_name=CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i]);
AddSingleValueToNetCDF(_STORAGE_ncid, short_name.c_str(),time_ind2,S);
currentWater+=S;
}
}
currentWater+=channel_stor+rivulet_stor+reservoir_stor;
if(tt.model_time==0){
// \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it
// JRC: I think somehow this is being double counted in the delta V calculations in the first timestep
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->GetReservoir()!=NULL){
currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
}
}
}
AddSingleValueToNetCDF(_STORAGE_ncid,"Total" ,time_ind2,currentWater);
AddSingleValueToNetCDF(_STORAGE_ncid,"Cum. Input" ,time_ind2,_CumulInput);
AddSingleValueToNetCDF(_STORAGE_ncid,"Cum. Outflow" ,time_ind2,_CumulOutput);
AddSingleValueToNetCDF(_STORAGE_ncid,"MB Error" ,time_ind2,FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput)));
}
//====================================================================
// ForcingFunctions.nc
//====================================================================
if(Options.write_forcings)
{
force_struct *pFave;
force_struct faveStruct = GetAverageForcings();
pFave = &faveStruct;
// write new time step
retval = nc_inq_varid (_FORCINGS_ncid, "time", &time_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_FORCINGS_ncid, time_id, time_index, count1, ¤t_time[0]); HandleNetCDFErrors(retval);
// write data
AddSingleValueToNetCDF(_FORCINGS_ncid,"rainfall" ,time_ind2,pFave->precip*(1.0-pFave->snow_frac));
AddSingleValueToNetCDF(_FORCINGS_ncid,"snowfall" ,time_ind2,pFave->precip*( pFave->snow_frac));
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp" ,time_ind2,pFave->temp_ave);
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_min" ,time_ind2,pFave->temp_daily_min);
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_max" ,time_ind2,pFave->temp_daily_max);
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_ave" ,time_ind2,pFave->temp_daily_ave);
AddSingleValueToNetCDF(_FORCINGS_ncid,"air density" ,time_ind2,pFave->air_dens);
AddSingleValueToNetCDF(_FORCINGS_ncid,"air pressure" ,time_ind2,pFave->air_pres);
AddSingleValueToNetCDF(_FORCINGS_ncid,"relative humidity",time_ind2,pFave->rel_humidity);
AddSingleValueToNetCDF(_FORCINGS_ncid,"cloud cover" ,time_ind2,pFave->cloud_cover);
AddSingleValueToNetCDF(_FORCINGS_ncid,"ET radiation" ,time_ind2,pFave->ET_radia);
AddSingleValueToNetCDF(_FORCINGS_ncid,"SW radiation" ,time_ind2,pFave->SW_radia);
AddSingleValueToNetCDF(_FORCINGS_ncid,"net SW radiation" ,time_ind2,pFave->SW_radia_net);
AddSingleValueToNetCDF(_FORCINGS_ncid,"LW radiation" ,time_ind2,pFave->cloud_cover);
AddSingleValueToNetCDF(_FORCINGS_ncid,"wind velocity" ,time_ind2,pFave->wind_vel);
AddSingleValueToNetCDF(_FORCINGS_ncid,"PET" ,time_ind2,pFave->PET);
AddSingleValueToNetCDF(_FORCINGS_ncid,"OW PET" ,time_ind2,pFave->OW_PET);
AddSingleValueToNetCDF(_FORCINGS_ncid,"potential melt" ,time_ind2,pFave->potential_melt);
}
#endif
}
//////////////////////////////////////////////////////////////////
/// \brief creates specified output directory, if needed
///
/// \param &Options [in] global model options
//
void PrepareOutputdirectory(const optStruct &Options)
{
if (Options.output_dir!="")
{
#if defined(_WIN32)
_mkdir(Options.output_dir.c_str());
#elif defined(__linux__)
mkdir(Options.output_dir.c_str(), 0777);
#endif
}
g_output_directory=Options.main_output_dir;//necessary evil
}
//////////////////////////////////////////////////////////////////
/// \brief returns directory path given filename
///
/// \param fname [in] filename, e.g., C:\temp\thisfile.txt returns c:\temp
//
string GetDirectoryName(const string &fname)
{
size_t pos = fname.find_last_of("\\/");
if (std::string::npos == pos){ return ""; }
else { return fname.substr(0, pos);}
}
//////////////////////////////////////////////////////////////////
/// \brief returns directory path given filename and relative path
///
/// \param filename [in] filename, e.g., C:/temp/thisfile.txt returns c:/temp
/// \param relfile [in] filename of reference file
/// e.g.,
/// absolute path of reference file is adopted
/// if filename = something.txt and relfile= c:/temp/myfile.rvi, returns c:/temp/something.txt
///
/// relative path of reference file is adopted
/// if filename = something.txt and relfile= ../dir/myfile.rvi, returns ../dir/something.txt
///
/// if path of reference file is same as file, then nothing changes
/// if filename = ../temp/something.txt and relfile= ../temp/myfile.rvi, returns ../temp/something.txt
///
/// if absolute paths of file is given, nothing changes
/// if filename = c:/temp/something.txt and relfile= ../temp/myfile.rvi, returns c:/temp/something.txt
//
string CorrectForRelativePath(const string filename,const string relfile)
{
string filedir = GetDirectoryName(relfile); //if a relative path name, e.g., "/path/model.rvt", only returns e.g., "/path"
if (StringToUppercase(filename).find(StringToUppercase(filedir)) == string::npos)//checks to see if absolute dir already included in redirect filename
{
string firstchar = filename.substr(0, 1); // if '/' --> absolute path on UNIX systems
string secondchar = filename.substr(1, 1); // if ':' --> absolute path on WINDOWS system
if ( (firstchar.compare("/") != 0) && (secondchar.compare(":") != 0) ){
// cout << "This is not an absolute filename! --> " << filename << endl;
//+"//"
//cout << "StandardOutput: corrected filename: " << filedir + "//" + filename << endl;
return filedir + "//" + filename;
}
}
// cout << "StandardOutput: corrected filename: " << filename << endl;
return filename;
}
//////////////////////////////////////////////////////////////////
/// \brief adds metadata of attribute to NetCDF file
/// \param fileid [in] NetCDF output file id
/// \param time_dimid [in], identifier of time attribute
/// \param shortname [in] attribute short name
/// \param longname [in] attribute long name
/// \param units [in] attribute units as string
//
int NetCDFAddMetadata(const int fileid,const int time_dimid,string shortname,string longname,string units)
{
int varid(0);
#ifdef _RVNETCDF_
int retval;
int dimids[1];
dimids[0] = time_dimid;
static double fill_val[] = {NETCDF_BLANK_VALUE};
static double miss_val[] = {NETCDF_BLANK_VALUE};
// (a) create variable precipitation
retval = nc_def_var(fileid,shortname.c_str(),NC_DOUBLE,1,dimids,&varid); HandleNetCDFErrors(retval);
// (b) add attributes to variable
retval = nc_put_att_text (fileid,varid,"units",units.length(),units.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text (fileid,varid,"long_name",longname.length(),longname.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"_FillValue",NC_DOUBLE,1,fill_val); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"missing_value",NC_DOUBLE,1,miss_val); HandleNetCDFErrors(retval);
#endif
return varid;
}
//////////////////////////////////////////////////////////////////
/// \brief adds metadata of attribute to NetCDF file for 2D data (time,nbasins)
/// \param fileid [in] NetCDF output file id
/// \param time_dimid [in], identifier of time attribute
/// \param nbasins_dimid [in], identifier of # basins attribute
/// \param shortname [in] attribute short name
/// \param longname [in] attribute long name
/// \param units [in] attribute units as string
//
int NetCDFAddMetadata2D(const int fileid,const int time_dimid,int nbasins_dimid,string shortname,string longname,string units)
{
int varid(0);
#ifdef _RVNETCDF_
int retval;
int dimids2[2];
string tmp;
static double fill_val[] = {NETCDF_BLANK_VALUE};
static double miss_val[] = {NETCDF_BLANK_VALUE};
dimids2[0] = time_dimid;
dimids2[1] = nbasins_dimid;
// (a) create variable
retval = nc_def_var(fileid,shortname.c_str(),NC_DOUBLE,2,dimids2,&varid); HandleNetCDFErrors(retval);
tmp = "basin_name";
// (b) add attributes to variable
retval = nc_put_att_text( fileid,varid,"units", units.length(), units.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text( fileid,varid,"long_name", longname.length(),longname.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"_FillValue", NC_DOUBLE,1, fill_val); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"missing_value", NC_DOUBLE,1, miss_val); HandleNetCDFErrors(retval);
retval = nc_put_att_text( fileid,varid,"coordinates", tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval);
#endif
return varid;
}
//////////////////////////////////////////////////////////////////
/// \brief writes global attributes to netcdf file identified with out_ncid. Must be timeSeries featureType.
/// \param out_ncid [in] NetCDF file identifier
/// \param Options [in] model Options structure
/// \param descript [in] contents of NetCDF description attribute
//
void WriteNetCDFGlobalAttributes(const int out_ncid,const optStruct &Options,const string descript)
{
ExitGracefullyIf(out_ncid==-9,"WriteNetCDFGlobalAttributes: netCDF file not open",RUNTIME_ERR);
int retval(0);
string att,val;
#ifdef _RVNETCDF_
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "Conventions", strlen("CF-1.6"), "CF-1.6"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "featureType", strlen("timeSeries"), "timeSeries"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "history", strlen("Created by Raven"),"Created by Raven"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "description", strlen(descript.c_str()), descript.c_str()); HandleNetCDFErrors(retval);
for(int i=0;i<Options.nNetCDFattribs;i++){
att=Options.aNetCDFattribs[i].attribute;
val=Options.aNetCDFattribs[i].value;
retval = nc_put_att_text(out_ncid,NC_GLOBAL,att.c_str(),strlen(val.c_str()),val.c_str());
HandleNetCDFErrors(retval);
}
#endif
}
//////////////////////////////////////////////////////////////////
/// \brief adds single value of attribute 'shortname' linked to time time_index to NetCDF file
/// \param out_ncid [in] NetCDF file identifier
/// \param shortname [in] short name of attribute (e.g., 'rainfall')
/// \param time_index [in] index of current time step
/// \param value [in] value of attribute at current time step
//
void AddSingleValueToNetCDF(const int out_ncid,const string &shortname,const size_t time_index,const double &value)
{
static size_t count1[1]; //static for speed of execution
static size_t time_ind[1];
static double val[1];
int var_id(0),retval(0);
time_ind[0]=time_index;
count1[0]=1;
val[0]=value;
#ifdef _RVNETCDF_
retval = nc_inq_varid (out_ncid,shortname.c_str(),&var_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(out_ncid,var_id,time_ind,count1,&val[0]); HandleNetCDFErrors(retval);
#endif
}
| 43.10613
| 171
| 0.582575
|
Okanagan-Basin-Water-Board
|
f4bc121c4304525c02031b34fad39c65d8a34747
| 798
|
cpp
|
C++
|
src/modules/osg/generated_code/ClipPlaneList.pypp.cpp
|
JaneliaSciComp/osgpyplusplus
|
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
|
[
"BSD-3-Clause"
] | 17
|
2015-06-01T12:19:46.000Z
|
2022-02-12T02:37:48.000Z
|
src/modules/osg/generated_code/ClipPlaneList.pypp.cpp
|
JaneliaSciComp/osgpyplusplus
|
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
|
[
"BSD-3-Clause"
] | 7
|
2015-07-04T14:36:49.000Z
|
2015-07-23T18:09:49.000Z
|
src/modules/osg/generated_code/ClipPlaneList.pypp.cpp
|
JaneliaSciComp/osgpyplusplus
|
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
|
[
"BSD-3-Clause"
] | 7
|
2015-11-28T17:00:31.000Z
|
2020-01-08T07:00:59.000Z
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "indexing_suite/container_suite.hpp"
#include "indexing_suite/vector.hpp"
#include "wrap_osg.h"
#include "_ref_ptr_less__osg_scope_ClipPlane__greater___value_traits.pypp.hpp"
#include "clipplanelist.pypp.hpp"
namespace bp = boost::python;
void register_ClipPlaneList_class(){
{ //::std::vector< osg::ref_ptr<osg::ClipPlane> >
typedef bp::class_< std::vector< osg::ref_ptr<osg::ClipPlane> > > ClipPlaneList_exposer_t;
ClipPlaneList_exposer_t ClipPlaneList_exposer = ClipPlaneList_exposer_t( "ClipPlaneList" );
bp::scope ClipPlaneList_scope( ClipPlaneList_exposer );
ClipPlaneList_exposer.def( bp::indexing::vector_suite< std::vector< osg::ref_ptr<osg::ClipPlane> > >() );
}
}
| 36.272727
| 113
| 0.740602
|
JaneliaSciComp
|
f4bd24595ae54aaad502d864082ac65a7180b5d7
| 739
|
cpp
|
C++
|
Structure_and_pointer_using_arrow_operator.cpp
|
gptakhil/Cpp-Revision
|
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
|
[
"MIT"
] | null | null | null |
Structure_and_pointer_using_arrow_operator.cpp
|
gptakhil/Cpp-Revision
|
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
|
[
"MIT"
] | null | null | null |
Structure_and_pointer_using_arrow_operator.cpp
|
gptakhil/Cpp-Revision
|
ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
// Student structure
struct Student {
string name;
int roll_number;
int marks;
};
// main function
int main() {
// Declare structure variable
struct Student s1;
// Declare structure pointer
struct Student *ptrs1;
// Store address of structure variable in structure pointer
ptrs1 = &s1;
// Set value of name
ptrs1->name = "John";
// Set value of roll_number
ptrs1->roll_number = 1;
// Set value of marks
ptrs1->marks = 50;
// Print value of structure member
cout << "s1 Information:" << endl;
cout << "Name = " << ptrs1->name << endl;
cout << "Roll Number = " << ptrs1->roll_number << endl;
cout << "Marks = " << ptrs1->marks << endl;
return 0;
}
| 19.972973
| 61
| 0.640054
|
gptakhil
|
f4bd493befc9a42fcd2e0c51b941f91c214307bd
| 2,440
|
cpp
|
C++
|
metaforce-gui/CVarDialog.cpp
|
Jcw87/urde
|
fb9ea9092ad00facfe957ece282a86c194e9cbda
|
[
"MIT"
] | 267
|
2016-03-10T21:59:16.000Z
|
2021-03-28T18:21:03.000Z
|
metaforce-gui/CVarDialog.cpp
|
cobalt2727/metaforce
|
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
|
[
"MIT"
] | 129
|
2016-03-12T10:17:32.000Z
|
2021-04-05T20:45:19.000Z
|
metaforce-gui/CVarDialog.cpp
|
cobalt2727/metaforce
|
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
|
[
"MIT"
] | 31
|
2016-03-20T00:20:11.000Z
|
2021-03-10T21:14:11.000Z
|
#include "CVarDialog.hpp"
#include "ui_CVarDialog.h"
#include <utility>
enum class CVarType {
String,
Boolean,
};
struct CVarItem {
QString m_name;
CVarType m_type;
QVariant m_defaultValue;
CVarItem(QString name, CVarType type, QVariant defaultValue)
: m_name(std::move(name)), m_type(type), m_defaultValue(std::move(defaultValue)) {}
};
static std::array cvarList{
CVarItem{QStringLiteral("tweak.game.FieldOfView"), CVarType::String, 55},
CVarItem{QStringLiteral("debugOverlay.playerInfo"), CVarType::Boolean, false},
CVarItem{QStringLiteral("debugOverlay.areaInfo"), CVarType::Boolean, false},
// TODO expand
};
CVarDialog::CVarDialog(QWidget* parent) : QDialog(parent), m_ui(std::make_unique<Ui::CVarDialog>()) {
m_ui->setupUi(this);
QStringList list;
for (const auto& item : cvarList) {
list << item.m_name;
}
m_model.setStringList(list);
m_ui->cvarList->setModel(&m_model);
connect(m_ui->cvarList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(handleSelectionChanged(QItemSelection)));
}
CVarDialog::~CVarDialog() = default;
void CVarDialog::on_buttonBox_accepted() {
const QModelIndexList& list = m_ui->cvarList->selectionModel()->selectedIndexes();
if (list.isEmpty()) {
reject();
} else {
accept();
}
}
void CVarDialog::on_buttonBox_rejected() { reject(); }
void CVarDialog::handleSelectionChanged(const QItemSelection& selection) {
const QModelIndexList& list = selection.indexes();
if (list.isEmpty()) {
return;
}
const auto item = cvarList[(*list.begin()).row()];
m_ui->valueStack->setCurrentIndex(static_cast<int>(item.m_type));
if (item.m_type == CVarType::String) {
m_ui->stringValueField->setText(item.m_defaultValue.toString());
} else if (item.m_type == CVarType::Boolean) {
m_ui->booleanValueField->setChecked(item.m_defaultValue.toBool());
}
}
QString CVarDialog::textValue() {
const QModelIndexList& list = m_ui->cvarList->selectionModel()->selectedIndexes();
if (list.isEmpty()) {
return QStringLiteral("");
}
const auto item = cvarList[(*list.begin()).row()];
QVariant value;
if (item.m_type == CVarType::String) {
value = m_ui->stringValueField->text();
} else if (item.m_type == CVarType::Boolean) {
value = m_ui->booleanValueField->isChecked();
}
return QStringLiteral("+") + item.m_name + QStringLiteral("=") + value.toString();
}
| 30.886076
| 107
| 0.703279
|
Jcw87
|
f4bddf3d7b8570b8edff54fcafb5860712621925
| 2,097
|
hpp
|
C++
|
ziomon/ziorep_framer.hpp
|
nikita-dubrovskii/s390-tools
|
074de1e14ed785c18f55ecf9762ac3f5de3465b4
|
[
"MIT"
] | 43
|
2017-08-21T12:18:57.000Z
|
2021-01-21T09:20:59.000Z
|
ziomon/ziorep_framer.hpp
|
nikita-dubrovskii/s390-tools
|
074de1e14ed785c18f55ecf9762ac3f5de3465b4
|
[
"MIT"
] | 99
|
2017-08-21T20:41:13.000Z
|
2021-01-27T16:23:07.000Z
|
ziomon/ziorep_framer.hpp
|
nikita-dubrovskii/s390-tools
|
074de1e14ed785c18f55ecf9762ac3f5de3465b4
|
[
"MIT"
] | 37
|
2017-08-21T20:37:32.000Z
|
2021-02-02T10:10:45.000Z
|
/*
* FCP report generators
*
* Class for reading messages into frames.
*
* Copyright IBM Corp. 2008, 2017
*
* s390-tools is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef ZIOREP_FRAMER
#define ZIOREP_FRAMER
#include <list>
#include "ziorep_filters.hpp"
#include "ziorep_frameset.hpp"
using std::list;
extern "C" {
#include "ziomon_dacc.h"
}
class Framer {
public:
/**
* Note: Filter parameters transfer memory ownership to class.
* 'filter_types' is an optional list of message types that should
* be processed exclusively, anything else will be ignored. If not set,
* all messages will be processed.
*/
Framer(__u64 begin, __u64 end, __u32 interval_length,
list<MsgTypes> *filter_types, DeviceFilter *devFilter,
const char *filename, int *rc);
~Framer();
/**
* Retrieve the next set of messages.
* Returns 0 in case of success, <0 in case of failure
* and >0 in case end of data has been reached.
* Set 'replace_missing' to fill in for non-present datasets.
* E.g. if no utilization data was found in the interval (since there
* was no traffic), a dataset with the expected number of samples
* (but all 0s for the values) will be generated.
*/
int get_next_frameset(Frameset &frameset, bool replace_missing = false);
private:
void handle_msg(struct message *msg, Frameset &frameset) const;
bool handle_agg_data(Frameset &frameset) const;
/* timestamps of samples to consider
* These are exact timestamps, we shift them a bit to make sure that
* we catch any late or early messages as well */
__u64 m_begin;
__u64 m_end;
/// user-specified interval length
__u32 m_interval_length;
/* Criteria to identify the right messages */
MsgTypeFilter *m_type_filter;
DeviceFilter *m_device_filter;
// filename without extension
const char *m_filename;
FILE *m_fp;
struct file_header m_fhdr;
struct aggr_data *m_agg_data;
/// indicates whether the .agg file was already read or not
bool m_agg_read;
};
#endif
| 25.573171
| 73
| 0.72103
|
nikita-dubrovskii
|
f4bfc17b377b3c5017fcc97a6105b03afe47b3c0
| 27,119
|
cpp
|
C++
|
src/SphinxService.cpp
|
ExpandingDev/PyramidASR
|
dbfddc13bb6dde7a8e349e87e4ca9df229d64703
|
[
"Unlicense"
] | null | null | null |
src/SphinxService.cpp
|
ExpandingDev/PyramidASR
|
dbfddc13bb6dde7a8e349e87e4ca9df229d64703
|
[
"Unlicense"
] | 10
|
2019-07-08T03:38:52.000Z
|
2019-11-20T20:57:17.000Z
|
src/SphinxService.cpp
|
ExpandingDev/PyramidASR
|
dbfddc13bb6dde7a8e349e87e4ca9df229d64703
|
[
"Unlicense"
] | null | null | null |
#include "SphinxService.h"
#include "ReplyType.h"
#include "Buckey.h"
#include "HypothesisEventData.h"
#include <chrono>
using namespace std::chrono;
SphinxService * SphinxService::instance;
std::atomic<bool> SphinxService::instanceSet(false);
unsigned long SphinxService::onEnterPromptEventHandlerID;
unsigned long SphinxService::onConversationEndEventHandlerID;
SphinxService * SphinxService::getInstance() {
if(!instanceSet) {
instance = new SphinxService();
instanceSet.store(true);
}
return instance;
}
std::string SphinxService::getName() const {
return "sphinx";
}
void SphinxService::setupAssets(cppfs::FileHandle aDir) {
cppfs::FileHandle confirmGram = aDir.open("confirm.gram");
if(!confirmGram.writeFile("#JSGF v1.0;\n\
grammar confirm;\n\
public <command> = <positive> {yes} | <deny> {no};\n\
<positive> = yes | yeah | ok | positive | confirm | of course | please do | yes sir;\n\
<deny> = no | deny | reject | [please] don't | nope | do not;")) {
///TODO: Error setting up confirm.gram
Buckey::logError("SphinxService failed to create confirm.gram asset file.");
}
}
void SphinxService::setupConfig(cppfs::FileHandle cDir) {
YAML::Node n;
n["logfile"] = "/dev/null";
n["max-frame-size"] = 2048;
n["hmm-dir"] = "/usr/local/share/pocketsphinx/model/en-us/en-us";
n["dict-dir"] = "/usr/local/share/pocketsphinx/model/en-us/cmudict-en-us.dict";
// n["speech-device"] = "default";
n["default-lm"] = "/usr/local/share/pocketsphinx/model/en-us/en-us.lm.bin";
n["max-decoders"] = 2;
n["samples-per-second"] = 16000; // Taken from libsphinxad ad.h is usually 16000
cppfs::FileHandle cFile = cDir.open("decoder.conf");
YAML::Emitter e;
e << n;
cFile.writeFile(e.c_str());
}
SphinxService::SphinxService() : manageThreadRunning(false), currentDecoderIndex(0), inUtterance(false), endLoop(false), paused(false), pressToSpeakMode(false), pressToSpeakPressed(false) {
}
SphinxService::~SphinxService()
{
endLoop.store(true);
//usleep(100); // TODO: Windows portability
if(manageThreadRunning.load() || recognizerLoop.joinable()) {
recognizerLoop.join();
}
for(std::thread & t : miscThreads) {
t.join();
}
for(SphinxDecoder * sd : decoders) {
delete sd;
}
instanceSet.store(false);
}
void SphinxService::start() {
setState(ServiceState::STARTING);
endLoop.store(false);
voiceDetected.store(false);
recognizing.store(false);
isRecording.store(false);
paused.store(false);
pressToSpeakMode.store(false);
pressToSpeakPressed.store(false);
config = YAML::LoadFile(configDir.open("decoder.conf").path());
maxDecoders = config["max-decoders"].as<unsigned int>();
deviceName = "";
if(config["speech-device"]) {
deviceName = config["speech-device"].as<std::string>();
}
for(unsigned short i = 0; i < maxDecoders; i++) {
SphinxDecoder * sd = new SphinxDecoder("base-grammar", config["default-lm"].as<std::string>(), SphinxHelper::SearchMode::LM, config["hmm-dir"].as<std::string>(), config["dict-dir"].as<std::string>(), config["logfile"].as<std::string>(), true);
decoders.push_back(sd);
}
startPressToSpeakRecognition(deviceName);
///TODO: Set listeners
onEnterPromptEventHandlerID = Buckey::getInstance()->addListener("onEnterPromptEvent", onEnterPromptEventHandler);
onConversationEndEventHandlerID = Buckey::getInstance()->addListener("onExitPromptEvent", onConversationEndEventHandler);
setState(ServiceState::RUNNING);
}
void SphinxService::stop() {
if(getState() == ServiceState::RUNNING) {
Buckey::getInstance()->unsetListener("onEnterPromptEvent", onEnterPromptEventHandlerID);
Buckey::getInstance()->unsetListener("onExitPromptEvent", onConversationEndEventHandlerID);
stopRecognition();
}
setState(ServiceState::STOPPED);
}
void SphinxService::stopRecognition() {
Buckey::logInfo("Received request to stop recognition.");
endLoop.store(true);
if(manageThreadRunning.load()) {
recognizerLoop.join();
}
}
void SphinxService::pauseRecognition() {
paused.store(true);
triggerEvents(ON_PAUSE, new EventData());
}
void SphinxService::resumeRecognition() {
triggerEvents(ON_RESUME, new EventData());
paused.store(false);
}
bool SphinxService::isRecordingToFile() {
return isRecording;
}
void SphinxService::stopRecordingToFile() {
isRecording.store(false);
fflush(recordingFileHandle);
fclose(recordingFileHandle);
}
bool SphinxService::startRecordingToFile() {
if(recordingFileHandle != NULL) {
isRecording.store(false);
return true;
}
else {
return false;
}
}
void SphinxService::onEnterPromptEventHandler(EventData * data, std::atomic<bool> * done) {
PromptEventData * d = (PromptEventData *) data;
Buckey::logInfo("enter prompt event handler");
if(d->getType() == "confirm") {
SphinxService::getInstance()->updateJSGFPath(SphinxService::getInstance()->assetsDir.open("confirm.gram").path());
SphinxService::getInstance()->applyUpdates();
Buckey::logInfo("switched grammars");
}
done->store(true);
}
void SphinxService::onConversationEndEventHandler(EventData * data, std::atomic<bool> * done) {
Buckey::logInfo("exit prompt event handler");
SphinxService::getInstance()->setJSGF(Buckey::getInstance()->getRootGrammar());
SphinxService::getInstance()->applyUpdates();
done->store(true);
}
bool SphinxService::recordAudioToFile(std::string pathToAudioFile) {
recordingFile = pathToAudioFile;
recordingFileHandle = fopen(pathToAudioFile.c_str(), "wb");
//TODO: Implement proper file closing when stop recording method is called. Currently stops recording when it reaches the end of an audio file, but does not close it when the stop function is called.
if(recordingFileHandle == NULL) {
Buckey::logError("Unable to open raw audio file to write recorded audio! " + pathToAudioFile);
return false;
}
else {
isRecording.store(true);
return true;
}
}
///Static loop that runs during non-continuous/push to speak recognition
void SphinxService::manageNonContinuousDecoders(SphinxService * sr) {
//Lock all mutexes and flags first
sr->manageThreadRunning.store(true);
sr->updateLock.lock();
Buckey * b = Buckey::getInstance();
ad_rec_t *ad = nullptr; // Audio source
int16 adbuf[sr->config["max-frame-size"].as<int>()]; //buffer that audio frames are copied into
int32 frameCount = 0; // Number of frames read into the adbuf
sr->endLoop.store(false);
sr->inUtterance.store(false);
sr->voiceDetected.store(false); // Reset this as its used to keep track of state
Buckey::logInfo("Decoder management thread started");
if (sr->source == SphinxHelper::DEVICE) {
Buckey::logInfo("Opening audio device for recognition");
if(sr->deviceName == "") {
if ((ad = ad_open_sps(sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
}
else if((ad = ad_open_dev(sr->deviceName.c_str(), sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
}
else {
Buckey::logWarn("Cannot open noncontinuous decoding for FILE!");
sr->recognizing.store(false);
return;
}
sr->currentDecoderIndex.store(0);
Buckey::logInfo("Starting Utterances...");
// Start up all of the utterances
for(SphinxDecoder * sd : sr->decoders) {
sd->startUtterance();
}
Buckey::logInfo("Done starting Utterances.");
while(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::NOT_INITIALIZED) {
//Wait until the decoder is ready
}
sr->recognizing.store(false);
sr->triggerEvents(ON_READY, new EventData());
Buckey::getInstance()->reply("Sphinx Speech Recognition Ready", ReplyType::CONSOLE);
sr->updateLock.unlock();
sr->triggerEvents(ON_SERVICE_READY, new EventData());
while(!b->isKilled() && !sr->endLoop.load()) {
while(!b->isKilled() && !sr->endLoop.load() && !sr->pressToSpeakPressed.load()) {
//Wait until press to speak is pressed or we have to stop
}
//Make sure we didn't exit the loop because we have to stop
if(b->isKilled() || sr->endLoop.load()) {
break;
}
sr->recognizing.store(true);
auto start = high_resolution_clock::now();
//Start recording from audio device
if (ad_start_rec(ad) < 0) {
Buckey::logError("Failed to start recording");
sr->recognizing.store(false);
break;
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
std::cout << "Time to start recording: " << duration.count() << std::endl;
// Read from the audio buffer while press to speak is pressed
while(sr->pressToSpeakPressed.load() && !sr->endLoop.load() && !b->isKilled()) {
frameCount = ad_read(ad, adbuf, AUDIO_FRAME_SIZE);
//Check to make sure we got frames from the audio device
if(frameCount < 0 ) {
if(sr->source == SphinxHelper::DEVICE) {
Buckey::logError("Failed to read from audio device for sphinx recognizer!");
/// TODO: Maybe fail a bit more gracefully
sr->killThreads();
break;
}
}
else if(sr->isRecording) {
fwrite(adbuf, sizeof(int16), frameCount, sr->recordingFileHandle);
fflush(sr->recordingFileHandle);
}
// Check to make sure our current decoder has not errored out
if(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::ERROR) {
Buckey::logError("Decoder is errored out! Trying next decoder...");
bool found = false;
for(unsigned short i = sr->currentDecoderIndex; i < sr->maxDecoders - 1; i++) {
if(sr->decoders[sr->currentDecoderIndex]->isReady()) {
sr->currentDecoderIndex.store(sr->currentDecoderIndex + i);
found = true;
break;
}
}
if(!found) {
Buckey::logError("No more good decoders to use! Stopping speech recognition!");
sr->killThreads();
break;
}
}
/*
// Check to make sure our current decoder is still ready to process speech (make sure the utterance has been started)
if(sr->decoders[sr->currentDecoderIndex]->state != SphinxHelper::DecoderState::UTTERANCE_STARTED) {
sr->decoders[sr->currentDecoderIndex]->startUtterance();
}
*/
// Process the frames
sr->voiceDetected.store(sr->decoders[sr->currentDecoderIndex]->processRawAudio(adbuf, frameCount));
// Silence to speech transition
// Trigger onSpeechStart
if(sr->voiceDetected && !sr->inUtterance) {
sr->triggerEvents(ON_START_SPEECH, new EventData());
sr->inUtterance.store(true);
b->playSoundEffect(SoundEffects::READY, false);
}
}
//Make sure we didn't exit the loop because we have to stop
if(b->isKilled() || sr->endLoop.load()) {
break;
}
//Stop recording
ad_stop_rec(ad);
//End and get hypothesis
sr->decoderIndexLock.lock();
sr->inUtterance.store(false);
sr->recognizing.store(false);
sr->decoders[sr->currentDecoderIndex]->ready = false;
sr->miscThreads.push_back(std::thread(endAndGetHypothesis, sr, sr->decoders[sr->currentDecoderIndex]));
sr->decoderIndexLock.unlock();
//Refresh decoders
sr->decoderIndexLock.lock();
for(unsigned short i = 0; i < sr->maxDecoders; i++) {
if(sr->decoders[i]->isReady()) {
sr->currentDecoderIndex.store(i);
}
}
sr->decoderIndexLock.unlock();
}
//Close the device audio source
Buckey::logInfo("Closing audio device");
ad_close(ad);
sr->recognizing.store(false);
sr->pressToSpeakMode.store(false);
sr->pressToSpeakPressed.store(false);
sr->manageThreadRunning.store(false);
}
bool SphinxService::inPressToSpeak() {
return pressToSpeakMode.load();
}
bool SphinxService::pressToSpeakIsPressed() {
return pressToSpeakPressed.load();
}
bool SphinxService::isPaused() {
return paused.load();
}
/// Static loop that runs during continuous recognition
void SphinxService::manageContinuousDecoders(SphinxService * sr) {
Buckey * b = Buckey::getInstance();
sr->manageThreadRunning.store(true);
sr->updateLock.lock();
Buckey::logInfo("Decoder management thread started");
sr->endLoop.store(false);
ad_rec_t *ad = nullptr; // Audio source
int16 adbuf[sr->config["max-frame-size"].as<int>()]; //buffer that audio frames are copied into
int32 frameCount = 0; // Number of frames read into the adbuf
sr->inUtterance.store(false);
sr->voiceDetected.store(false); // Reset this as its used to keep track of state
if(sr->source == SphinxHelper::FILE) {
Buckey::logInfo("Opening file for recognition");
// TODO: Implement opening the file, reliant upon specifying the args passed during startFileRecognition
}
else if (sr->source == SphinxHelper::DEVICE) {
Buckey::logInfo("Opening audio device for recognition");
// TODO: Use ad_open_dev without pocketsphinx's terrible configuration functions
//if ((ad = ad_open_dev(NULL,(int) cmd_ln_float32_r(sr->decoders[0]->getConfig(),"-samprate"))) == NULL) {
Buckey::logInfo("Opening audio device for recognition");
if(sr->deviceName == "") {
if ((ad = ad_open_sps(sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
}
else if((ad = ad_open_dev(sr->deviceName.c_str(), sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
if (ad_start_rec(ad) < 0) {
Buckey::logError("Failed to start recording\n");
sr->recognizing.store(false);
return;
}
}
sr->currentDecoderIndex.store(0);
Buckey::logInfo("Starting Utterances...");
// Start up all of the utterances
for(SphinxDecoder * sd : sr->decoders) {
sd->startUtterance();
}
Buckey::logInfo("Done starting Utterances.");
while(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::NOT_INITIALIZED) {
//Wait until the decoder is ready
}
sr->recognizing.store(true);
sr->triggerEvents(ON_READY, new EventData());
Buckey::getInstance()->reply("Sphinx Speech Recognition Ready", ReplyType::CONSOLE);
sr->updateLock.unlock();
sr->triggerEvents(ON_SERVICE_READY, new EventData());
while(!sr->endLoop.load()) {
// Read from the audio buffer
if(sr->source == SphinxHelper::DEVICE) {
if(sr->paused.load()) {
sr->decoderIndexLock.lock();
sr->decoders[sr->currentDecoderIndex]->endUtterance();
sr->inUtterance.store(false);
sr->decoders[sr->currentDecoderIndex]->startUtterance();
sr->decoderIndexLock.unlock();
}
while(sr->paused.load() && !sr->endLoop) {
//Wait until not paused, but continue reading frames so that we only read current frames when we resume recognition
frameCount = ad_read(ad, adbuf, AUDIO_FRAME_SIZE);
}
if(sr->endLoop) {
break;
}
frameCount = ad_read(ad, adbuf, AUDIO_FRAME_SIZE);
}
else if (sr->source == SphinxHelper::FILE) {
///NOTE: Pausing and resuming recognition only works from a device, not a file.
frameCount = fread(adbuf, sizeof(int16), AUDIO_FRAME_SIZE, sr->sourceFile);
}
if(frameCount < 0 ) {
if(sr->source == SphinxHelper::DEVICE) {
Buckey::logError("Failed to read from audio device for sphinx recognizer!");
// TODO: Maybe fail a bit more gracefully
sr->killThreads();
exit(-1);
}
}
else if(sr->isRecording) {
fwrite(adbuf, sizeof(int16), frameCount, sr->recordingFileHandle);
fflush(sr->recordingFileHandle);
}
// Check to make sure our current decoder has not errored out
if(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::ERROR) {
Buckey::logError("Decoder is errored out! Trying next decoder...");
bool found = false;
for(unsigned short i = sr->currentDecoderIndex; i < sr->maxDecoders - 1; i++) {
if(sr->decoders[sr->currentDecoderIndex]->isReady()) {
sr->currentDecoderIndex.store(sr->currentDecoderIndex + i);
found = true;
break;
}
}
if(!found) {
Buckey::logError("No more good decoders to use! Stopping speech recognition!");
sr->killThreads();
return;
}
}
if(frameCount <= 0 && sr->source == SphinxHelper::FILE) {
Buckey::logInfo("Reached end of audio file, stopping speech recognition...");
if(sr->inUtterance) { // Reached end of file before end of speech, so stop recognition and get the hypothesis
sr->decoderIndexLock.lock();
sr->triggerEvents(ON_END_SPEECH, new EventData()); // TODO: Add event data
sr->inUtterance.store(false);
sr->decoders[sr->currentDecoderIndex]->ready = false;
sr->miscThreads.push_back(std::thread(endAndGetHypothesis, sr, sr->decoders[sr->currentDecoderIndex]));
sr->decoderIndexLock.unlock();
if(sr->isRecording) {
sr->isRecording.store(false);
fflush(sr->recordingFileHandle);
fclose(sr->recordingFileHandle);
}
break;
}
}
// Process the frames
sr->voiceDetected.store(sr->decoders[sr->currentDecoderIndex]->processRawAudio(adbuf, frameCount));
// Silence to speech transition
// Trigger onSpeechStart
if(sr->voiceDetected && !sr->inUtterance) {
sr->triggerEvents(ON_START_SPEECH, new EventData());
sr->inUtterance.store(true);
b->playSoundEffect(SoundEffects::READY, false);
}
//Speech to silence transition
//Trigger onSpeechEnd
//And get hypothesis
if(!sr->voiceDetected && sr->inUtterance) {
sr->decoderIndexLock.lock();
sr->triggerEvents(ON_END_SPEECH, new EventData()); //TODO: Add event data
sr->inUtterance.store(false);
sr->decoders[sr->currentDecoderIndex]->ready = false;
sr->miscThreads.push_back(std::thread(endAndGetHypothesis, sr, sr->decoders[sr->currentDecoderIndex]));
sr->decoderIndexLock.unlock();
usleep(100); // TODO: Windows portability
sr->decoderIndexLock.lock();
for(unsigned short i = 0; i < sr->maxDecoders; i++) {
if(sr->decoders[i]->isReady()) {
sr->currentDecoderIndex.store(i);
}
}
sr->decoderIndexLock.unlock();
}
}
if(sr->source == SphinxHelper::FILE) {
fclose(sr->sourceFile);
}
//Close the device audio source
if (sr->source == SphinxHelper::DEVICE) {
Buckey::logInfo("Closing audio device");
ad_close(ad);
}
sr->recognizing.store(false);
sr->manageThreadRunning.store(false);
}
void SphinxService::startContinuousDeviceRecognition(std::string device) {
Buckey::logInfo("Starting device recognition");
if(!recognizing) {
source = SphinxHelper::DEVICE;
if(device != "") {
deviceName = device;
}
else {
// deviceName = config["speech-device"].as<std::string>();
device = "";
}
if(recognizerLoop.joinable()) {
recognizerLoop.join();
}
pressToSpeakMode.store(false);
recognizerLoop = std::thread(manageContinuousDecoders, this);
}
else {
Buckey::logWarn("Calling start device recognition while recognition already in progress!");
}
}
void SphinxService::startPressToSpeakRecognition(std::string device) {
Buckey::logInfo("Starting press to speak device recognition");
if(!recognizing) {
source = SphinxHelper::DEVICE;
if(device != "") {
deviceName = device;
}
else {
// deviceName = config["speech-device"].as<std::string>();
deviceName = "";
}
if(recognizerLoop.joinable()) {
recognizerLoop.join();
}
pressToSpeakMode.store(true);
recognizerLoop = std::thread(manageNonContinuousDecoders, this);
}
else {
Buckey::logWarn("Calling start device recognition while recognition already in progress!");
}
}
void SphinxService::pressToSpeakButtonDown() {
pressToSpeakPressed.store(true);
}
void SphinxService::pressToSpeakButtonUp() {
pressToSpeakPressed.store(false);
}
void SphinxService::endAndGetHypothesis(SphinxService * sr, SphinxDecoder * sd) {
sd->endUtterance();
std::string hyp = sd->getHypothesis();
if(hyp != "") { // Ignore false alarms
Buckey::logInfo("Got hypothesis: " + hyp);
Buckey::getInstance()->playSoundEffect(SoundEffects::OK, false);
sr->triggerEvents(ON_HYPOTHESIS, new HypothesisEventData(hyp));
Buckey::getInstance()->passInput(hyp);
}
sd->startUtterance();
}
void SphinxService::startFileRecognition(std::string pathToFile) {
if((sourceFile = fopen(pathToFile.c_str(), "rb")) == NULL) {
Buckey::logError("Unable to open file for speech recognition: " + pathToFile);
stopRecognition();
for(std::thread & t : miscThreads) {
t.join();
}
for(SphinxDecoder * sd : decoders) {
delete sd;
}
exit(-1);
}
else {
source = SphinxHelper::FILE;
Buckey::logInfo("Opened file for speech recognition: " + pathToFile);
}
recognizerLoop = std::thread(manageContinuousDecoders, this);
}
bool SphinxService::wordExists(std::string word) {
bool res = false;
bool found = false;
while(!found) {
for(unsigned short i = 0; i < maxDecoders - 1; i++) {
if(decoders[currentDecoderIndex]->isReady()) {
res = decoders[currentDecoderIndex]->wordExists(word);
found = true;
break;
}
}
}
return res;
}
void SphinxService::addWord(std::string word, std::string phones) {
for(unsigned short i = 0; i < maxDecoders - 1; i++) {
if(decoders[currentDecoderIndex]->getState() != SphinxHelper::DecoderState::ERROR && decoders[currentDecoderIndex]->getState() != SphinxHelper::DecoderState::NOT_INITIALIZED) {
decoders[currentDecoderIndex]->addWord(word, phones);
}
else {
Buckey::logWarn("Unable to add word " + word + " to decoder because it was not initialized or errored out!");
}
}
}
void SphinxService::updateDictionary(std::string pathToDictionary) {
for(SphinxDecoder * sd : decoders) {
sd->updateDictionary(pathToDictionary, false);
}
}
void SphinxService::updateAcousticModel(std::string pathToHMM) {
for(SphinxDecoder * sd : decoders) {
sd->updateAcousticModel(pathToHMM, false);
}
}
void SphinxService::updateJSGFPath(std::string pathToJSGF) {
for(SphinxDecoder * sd : decoders) {
sd->updateJSGF(pathToJSGF, false);
}
}
void SphinxService::updateLMPath(std::string pathToLM) {
for(SphinxDecoder * sd : decoders) {
sd->updateLM(pathToLM, false);
}
}
void SphinxService::updateLogPath(std::string pathToLog) {
for(SphinxDecoder * sd : decoders) {
sd->updateLoggingFile(pathToLog, false);
}
}
void SphinxService::updateSearchMode(SphinxHelper::SearchMode mode) {
for(SphinxDecoder * sd : decoders) {
sd->updateSearchMode(mode, false);
}
}
void SphinxService::setJSGF(Grammar * g) {
///TODO: Save Grammar to a temp file, pass the path of the temp file on to the sphinx decoders
cppfs::FileHandle t = Buckey::getInstance()->getTempFile(".gram");
t.writeFile("#JSGF V1.0;\n" + g->getText());
updateJSGFPath(t.path());
}
/// Applies previous updates and also initializes decoders if there weren't already when this object was constructed.
void SphinxService::applyUpdates() {
updateLock.lock();
Buckey::logInfo("Starting to apply updates.");
auto start = high_resolution_clock::now();
if(isRecognizing()) { // Decoders are in use so reload the ones not in use
Buckey::logInfo("Attempting to update while recognizing...");
unsigned short k = decoders.size();
unsigned short decodersDone[k];
unsigned short decoderDoneCount = 0;
while(decoderDoneCount != decoders.size()) {
for(unsigned short i = 0; i < decoders.size(); i++) {
unsigned short * c = std::find(decodersDone, decodersDone+k, i);
if(c != decodersDone+k) {
// This one was already updated, let it go
}
else {
//Not updated yet
if(i == currentDecoderIndex) {
if(!inUtterance) {
if(decoderDoneCount > 0) {
decoderIndexLock.lock();
currentDecoderIndex.store(decodersDone[0]);
decoderIndexLock.unlock();
}
}
}
else {
if(decoders[i]->getState() == SphinxHelper::DecoderState::UTTERANCE_STARTED) {
decoders[i]->reloadDecoder();
decoders[i]->startUtterance();
decodersDone[decoderDoneCount] = i;
decoderDoneCount++;
}
}
}
}
}
}
else { // Decoders are not in use so restart them all now
Buckey::logInfo("Applying updates while not recognizing...");
for(unsigned short i = 0; i < decoders.size(); i++) {
decoders[i]->reloadDecoder();
decoders[i]->startUtterance();
if(i == 0) { // Select the first decoder that we update so it is ready ASAP
decoderIndexLock.lock();
currentDecoderIndex.store(0);
decoderIndexLock.unlock();
}
}
}
Buckey::logInfo("Decoder Update Applied");
updateLock.unlock();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
std::cout << "Time to apply decoder update: " << duration.count() << std::endl;
}
bool SphinxService::isRecognizing() {
return recognizing;
}
bool SphinxService::voiceFound() {
return voiceDetected.load();
}
SphinxDecoder * SphinxService::getDecoder(unsigned short decoderIndex) {
return decoders[decoderIndex];
}
void SphinxService::addOnSpeechStart(void(*handler)(EventData *, std::atomic<bool> *)) {
addListener(ON_START_SPEECH, handler);
}
void SphinxService::addOnSpeechEnd(void(*handler)(EventData *, std::atomic<bool> *)) {
addListener(ON_END_SPEECH, handler);
}
void SphinxService::addOnHypothesis(void(*handler)(EventData *, std::atomic<bool> *)) {
addListener(ON_HYPOTHESIS, handler);
}
void SphinxService::clearSpeechStartListeners() {
clearListeners(ON_START_SPEECH);
}
void SphinxService::clearSpeechEndListeners() {
clearListeners(ON_END_SPEECH);
}
void SphinxService::clearOnHypothesisListeners() {
clearListeners(ON_HYPOTHESIS);
}
void SphinxService::clearOnPauseListeners() {
clearListeners(ON_PAUSE);
}
void SphinxService::clearOnResumeListeners() {
clearListeners(ON_RESUME);
}
| 32.911408
| 245
| 0.668424
|
ExpandingDev
|
f4c255172c3cff4a99ca1c0952190ae2834d4131
| 848
|
hpp
|
C++
|
Object.hpp
|
LinarAbdrazakov/MIPT_GAME
|
55d96906cb60752c3907fb83ce70910879dc4ed8
|
[
"MIT"
] | null | null | null |
Object.hpp
|
LinarAbdrazakov/MIPT_GAME
|
55d96906cb60752c3907fb83ce70910879dc4ed8
|
[
"MIT"
] | null | null | null |
Object.hpp
|
LinarAbdrazakov/MIPT_GAME
|
55d96906cb60752c3907fb83ce70910879dc4ed8
|
[
"MIT"
] | null | null | null |
#ifndef OBJECT_HPP
#define OBJECT_HPP
#include <SFML/Graphics.hpp>
class Object
{
private:
int id_;
sf::Sprite* sprite_;
sf::Vector2f coordinate_;
sf::Vector2f speed_;
sf::Vector2i size_;
float* dt_;
public:
explicit Object();
Object(const Object&);
Object(int, sf::Vector2f, sf::Vector2f, sf::Vector2i, float*);
~Object();
const int GetId() const;
sf::Sprite* GetSprite() const;
const sf::Vector2f GetCoordinate() const;
const sf::Vector2f GetSpeed() const;
const sf::Vector2i GetSize() const;
float* GetDt() const;
void SetId (int);
void SetSprite (sf::Sprite*);
void SetCoordinate(sf::Vector2f);
void SetSpeed (sf::Vector2f);
void SetSize (sf::Vector2i);
void SetDt (float*);
};
#endif
| 22.315789
| 64
| 0.595519
|
LinarAbdrazakov
|
f4c3d5422d8acf9ab1abf0cfabafd06a5f731f38
| 1,493
|
hpp
|
C++
|
lib/qt/LocationListComboBox.hpp
|
ncorgan/libpkmn
|
c683bf8b85b03eef74a132b5cfdce9be0969d523
|
[
"MIT"
] | 4
|
2017-06-10T13:21:44.000Z
|
2019-10-30T21:20:19.000Z
|
lib/qt/LocationListComboBox.hpp
|
PMArkive/libpkmn
|
c683bf8b85b03eef74a132b5cfdce9be0969d523
|
[
"MIT"
] | 12
|
2017-04-05T11:13:34.000Z
|
2018-06-03T14:31:03.000Z
|
lib/qt/LocationListComboBox.hpp
|
PMArkive/libpkmn
|
c683bf8b85b03eef74a132b5cfdce9be0969d523
|
[
"MIT"
] | 2
|
2019-01-22T21:02:31.000Z
|
2019-10-30T21:20:20.000Z
|
/*
* Copyright (c) 2016,2018 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#ifndef PKMN_QT_LOCATIONLISTCOMBOBOX_HPP
#define PKMN_QT_LOCATIONLISTCOMBOBOX_HPP
#include <pkmn/config.hpp>
#ifdef PKMN_ENABLE_QT
#include <QComboBox>
#include <QString>
#else
#error Qt support is not enabled in this build of LIbPKMN.
#endif
namespace pkmn { namespace qt {
/*!
* @brief A ComboBox populated with an alphabetized list of locations available in the given
* game (or generation).
*/
class PKMN_API LocationListComboBox: public QComboBox
{
Q_OBJECT
public:
/*!
* @brief Constructor.
*
* Note: even if wholeGeneration is set to true, Game Boy Advance locations will not appear in
* a list of Gamecube locations, and vice versa.
*
* \param game which game
* \param wholeGeneration include locations from all games in this generation
* \param parent parent widget
* \throws std::invalid_argument if the given game is invalid
*/
LocationListComboBox(
const QString& game,
bool wholeGeneration,
QWidget* parent
);
signals:
public slots:
};
}}
#endif /* PKMN_QT_LOCATIONLISTCOMBOBOX_HPP */
| 27.145455
| 106
| 0.618218
|
ncorgan
|
f4c4917cbb9b86920862bb09496beeb71e3ec2c3
| 3,786
|
cpp
|
C++
|
src/VideoDevice.cpp
|
nayanavenkataramana/earlyapp
|
eafd8ae8507dee79d2b751f7c5d9320f5519029b
|
[
"MIT"
] | 5
|
2019-01-02T18:34:52.000Z
|
2021-05-13T16:09:10.000Z
|
src/VideoDevice.cpp
|
nayanavenkataramana/earlyapp
|
eafd8ae8507dee79d2b751f7c5d9320f5519029b
|
[
"MIT"
] | 10
|
2018-10-26T06:11:45.000Z
|
2019-06-24T06:25:43.000Z
|
src/VideoDevice.cpp
|
nayanavenkataramana/earlyapp
|
eafd8ae8507dee79d2b751f7c5d9320f5519029b
|
[
"MIT"
] | 20
|
2018-10-26T02:16:51.000Z
|
2021-02-17T11:39:59.000Z
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018 Intel Corporation
//
// 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.
//
// SPDX-License-Identifier: MIT
//
////////////////////////////////////////////////////////////////////////////////
#include <string>
#include <boost/format.hpp>
#include "EALog.h"
#include "OutputDevice.hpp"
#include "VideoDevice.hpp"
#include "Configuration.hpp"
// A log tag for video device.
#define TAG "VIDEO"
namespace earlyapp
{
/*
Define a device instance variable.
*/
VideoDevice* VideoDevice::m_pVDev = nullptr;
/*
Destructor.
*/
VideoDevice::~VideoDevice(void)
{
if(m_pVDev != nullptr)
{
delete m_pVDev;
}
}
/*
A static function to get an instance(singleton).
*/
VideoDevice* VideoDevice::getInstance(void)
{
if(m_pVDev == nullptr)
{
LINF_(TAG, "Creating a VideoDevice instance");
m_pVDev = new VideoDevice();
}
return m_pVDev;
}
/*
Intialize
*/
void VideoDevice::init(std::shared_ptr<Configuration> pConf)
{
OutputDevice::init(pConf);
m_pDecPipeline = new CDecodingPipeline(m_pGPIOCtrl);
if(m_pDecPipeline == nullptr)
{
LERR_(TAG, "Failed to create decoder instance.");
return;
}
m_Params.bUseHWLib = true;
m_Params.bUseFullColorRange = false;
m_Params.videoType = MFX_CODEC_AVC;
m_Params.mode = MODE_RENDERING;
m_Params.memType = D3D9_MEMORY;
m_Params.mode = MODE_RENDERING;
// File path.
strcpy(m_Params.strSrcFile, pConf->videoSplashPath().c_str());
// Width
m_Params.Width = pConf->displayWidth();
// Height
m_Params.Height = pConf->displayHeight();
// Default ASync depth.
m_Params.nAsyncDepth = 4;
// Initialize decoding pipeline.
m_pDecPipeline->Init(&m_Params);
LINF_(TAG, "VideoDevice initialized.");
}
/*
Play the video device.
*/
void VideoDevice::play(void)
{
LINF_(TAG, "VideoDevice play");
// Start decoding and display.
m_pDecPipeline->RunDecoding();
}
/*
Stop.
*/
void VideoDevice::stop(void)
{
LINF_(TAG, "VideoDevice stop");
// Stop play
if(m_pDecPipeline)
{
delete m_pDecPipeline;
m_pDecPipeline = nullptr;
}
}
/*
Terminate
*/
void VideoDevice::terminate(void)
{
LINF_(TAG, "VideoDevice terminate");
// TODO: release resources.
}
} // namespace
| 25.409396
| 80
| 0.596408
|
nayanavenkataramana
|
f4c4ea6bac0a1d4a5e6e89bd188e9b83f1d875cb
| 7,360
|
cpp
|
C++
|
src/caffe/layers/cross_correlation_layer.cpp
|
NicoleWang/caffe-for-rfcn
|
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
|
[
"BSD-2-Clause"
] | null | null | null |
src/caffe/layers/cross_correlation_layer.cpp
|
NicoleWang/caffe-for-rfcn
|
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
|
[
"BSD-2-Clause"
] | null | null | null |
src/caffe/layers/cross_correlation_layer.cpp
|
NicoleWang/caffe-for-rfcn
|
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
|
[
"BSD-2-Clause"
] | null | null | null |
#include <algorithm>
#include <cfloat>
#include <vector>
#include "caffe/layers/cross_correlation_layer.hpp"
#include "caffe/util/math_functions.hpp"
#define DEBUG_INFO
#undef DEBUG_INFO
namespace caffe {
template <typename Dtype>
void CrossCorrelationLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
// std::cout << "Enter cross relation reshape function" << std::endl;
//delete bottom size constraint
//bottom[0]: feature map from last layer
//bottom[1]: kernel
const int first_spatial_axis = this->channel_axis_ + 1;
CHECK_EQ(bottom[0]->num_axes(), first_spatial_axis + this->num_spatial_axes_)
<< "bottom num_axes may not change.";
this->num_ = bottom[0]->count(0, this->channel_axis_);
CHECK_EQ(bottom[0]->shape(this->channel_axis_), this->channels_)
<< "Input size incompatible with convolution kernel.";
// TODO: generalize to handle inputs of different shapes.
// for (int bottom_id = 1; bottom_id < bottom.size(); ++bottom_id) {
// CHECK(bottom[0]->shape() == bottom[bottom_id]->shape())
// << "All inputs must have the same shape.";
// }
// Shape the tops.
this->bottom_shape_ = &bottom[0]->shape();
this->compute_output_shape();
vector<int> top_shape(bottom[0]->shape().begin(),
bottom[0]->shape().begin() + this->channel_axis_);
top_shape.push_back(this->num_output_);
for (int i = 0; i < this->num_spatial_axes_; ++i) {
top_shape.push_back(this->output_shape_[i]);
}
for (int top_id = 0; top_id < top.size(); ++top_id) {
top[top_id]->Reshape(top_shape);
}
if (this->reverse_dimensions()) {
this->conv_out_spatial_dim_ = bottom[0]->count(first_spatial_axis);
} else {
this->conv_out_spatial_dim_ = top[0]->count(first_spatial_axis);
}
this->col_offset_ = this->kernel_dim_ * this->conv_out_spatial_dim_;
this->output_offset_ = this->conv_out_channels_ * this->conv_out_spatial_dim_ / this->group_;
// Setup input dimensions (conv_input_shape_).
vector<int> bottom_dim_blob_shape(1, this->num_spatial_axes_ + 1);
this->conv_input_shape_.Reshape(bottom_dim_blob_shape);
int* conv_input_shape_data = this->conv_input_shape_.mutable_cpu_data();
for (int i = 0; i < this->num_spatial_axes_ + 1; ++i) {
if (this->reverse_dimensions()) {
conv_input_shape_data[i] = top[0]->shape(this->channel_axis_ + i);
} else {
conv_input_shape_data[i] = bottom[0]->shape(this->channel_axis_ + i);
}
}
// The im2col result buffer will only hold one image at a time to avoid
// overly large memory usage. In the special case of 1x1 convolution
// it goes lazily unused to save memory.
this->col_buffer_shape_.clear();
this->col_buffer_shape_.push_back(this->kernel_dim_ * this->group_);
for (int i = 0; i < this->num_spatial_axes_; ++i) {
if (this->reverse_dimensions()) {
this->col_buffer_shape_.push_back(this->input_shape(i + 1));
} else {
this->col_buffer_shape_.push_back(this->output_shape_[i]);
}
}
this->col_buffer_.Reshape(this->col_buffer_shape_);
this->bottom_dim_ = bottom[0]->count(this->channel_axis_);
this->top_dim_ = top[0]->count(this->channel_axis_);
this->num_kernels_im2col_ = this->conv_in_channels_ * this->conv_out_spatial_dim_;
this->num_kernels_col2im_ = this->reverse_dimensions() ? this->top_dim_ : this->bottom_dim_;
// Set up the all ones "bias multiplier" for adding biases by BLAS
this->out_spatial_dim_ = top[0]->count(first_spatial_axis);
if (this->bias_term_) {
vector<int> bias_multiplier_shape(1, this->out_spatial_dim_);
this->bias_multiplier_.Reshape(bias_multiplier_shape);
caffe_set(this->bias_multiplier_.count(), Dtype(1),
this->bias_multiplier_.mutable_cpu_data());
}
}
template <typename Dtype>
void CrossCorrelationLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
const Dtype* weight = bottom[1]->cpu_data();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
for (int n = 0; n < this->num_; ++n) {
this->forward_cpu_gemm(bottom_data + n * this->bottom_dim_, weight,
top_data + n * this->top_dim_);
if (this->bias_term_) {
const Dtype* bias = this->blobs_[1]->cpu_data();
this->forward_cpu_bias(top_data + n * this->top_dim_, bias);
}
}
}
template <typename Dtype>
void CrossCorrelationLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
const Dtype* weight = bottom[1]->cpu_data();
Dtype* weight_diff = bottom[1]->mutable_cpu_diff();
for (int i = 0; i < 1; ++i) {
Dtype* top_diff = top[i]->mutable_cpu_diff();
/*
const Dtype* tdata = top[i]->cpu_diff();
std::cout << " CROSS WEIGHT DIFF: " << std::endl;
for (int j = 0; j < top[i]->count(); ++j) {
std::cout << tdata[j] << " ";
}
std::cout << std::endl << std::endl << std::endl;
*/
const Dtype* bottom_data = bottom[i]->cpu_data();
Dtype* bottom_diff = bottom[i]->mutable_cpu_diff();
// Bias gradient, if necessary.
if (this->bias_term_) {
Dtype* bias_diff = this->blobs_[1]->mutable_cpu_diff();
for (int n = 0; n < this->num_; ++n) {
this->backward_cpu_bias(bias_diff, top_diff + n * this->top_dim_);
}
}
if (this->param_propagate_down_[0] || propagate_down[i]) {
for (int n = 0; n < this->num_; ++n) {
// gradient w.r.t. weight. Note that we will accumulate diffs.
if (this->param_propagate_down_[0] || true) {
this->weight_cpu_gemm(bottom_data + n * this->bottom_dim_,
top_diff + n * this->top_dim_, weight_diff);
}
// gradient w.r.t. bottom data, if necessary.
if (propagate_down[i]) {
this->backward_cpu_gemm(top_diff + n * this->top_dim_, weight,
bottom_diff + n * this->bottom_dim_);
}
}
}
}//end of for
#ifdef DEBUG_INFO
if (this->layer_param().name() == "cross" || true) {
const Dtype* top_diff_0 = top[0]->cpu_diff();
const Dtype* bottom_diff_0 = bottom[0]->cpu_data();
const Dtype* bottom_diff_1 = bottom[1]->cpu_data();
Dtype sum_top_0 = 0.0, sum_bottom_0 = 0.0, sum_bottom_1 = 0.0;
std::cout << "top diff: " << std::endl;
for (int i = 0; i < top[0]->count(); ++i) {
//std::cout << top_diff_0[i] << " ";
sum_top_0 += top_diff_0[i];
}
std::cout << std::endl;
std::cout << "bottom 0 diff: " << std::endl;
for (int i = 0; i < 50; ++i) {
std::cout << bottom_diff_0[i * 50] << " ";
sum_bottom_0 += bottom_diff_0[i];
}
std::cout << std::endl;
std::cout << "bottom 1 diff: " << std::endl;
for (int i = 0; i < 50; ++i) {
std::cout << bottom_diff_1[i * 50] << " ";
sum_bottom_1 += bottom_diff_1[i];
}
std::cout << std::endl;
//std::cout << this->layer_param().name() << " cross top 0 bottom 0 1 diff: ";
//std::cout << sum_top_0 << " " << sum_bottom_0 << " " << sum_bottom_1 << std::endl;
}
#endif
}
#ifdef CPU_ONLY
STUB_GPU(CrossCorrelationLayer);
#endif
INSTANTIATE_CLASS(CrossCorrelationLayer);
REGISTER_LAYER_CLASS(CrossCorrelation);
} // namespace caffe
| 40.43956
| 95
| 0.640353
|
NicoleWang
|
f4c62a895f625fee35ffda86d37a343556908493
| 4,779
|
cxx
|
C++
|
PWG/FLOW/Tasks/AliAnalysisTaskLYZEventPlane.cxx
|
maroozm/AliPhysics
|
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
|
[
"BSD-3-Clause"
] | 114
|
2017-03-03T09:12:23.000Z
|
2022-03-03T20:29:42.000Z
|
PWG/FLOW/Tasks/AliAnalysisTaskLYZEventPlane.cxx
|
maroozm/AliPhysics
|
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
|
[
"BSD-3-Clause"
] | 19,637
|
2017-01-16T12:34:41.000Z
|
2022-03-31T22:02:40.000Z
|
PWG/FLOW/Tasks/AliAnalysisTaskLYZEventPlane.cxx
|
maroozm/AliPhysics
|
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
|
[
"BSD-3-Clause"
] | 1,021
|
2016-07-14T22:41:16.000Z
|
2022-03-31T05:15:51.000Z
|
/*************************************************************************
* Copyright(c) 1998-2008, 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 <stdlib.h>
#include "Riostream.h" //needed as include
#include "TChain.h"
#include "TTree.h"
#include "TProfile.h"
#include "TFile.h"
#include "TList.h"
class AliAnalysisTaskSE;
#include "AliAnalysisManager.h"
#include "AliFlowEventSimple.h"
#include "AliAnalysisTaskLYZEventPlane.h"
#include "AliFlowCommonHist.h"
#include "AliFlowCommonHistResults.h"
#include "AliFlowLYZEventPlane.h"
#include "AliFlowAnalysisWithLYZEventPlane.h"
// AliAnalysisTaskLYZEventPlane:
//
// analysis task for Lee Yang Zeros Event Plane
//
// Author: Naomi van der Kolk (kolk@nikhef.nl)
using std::cout;
using std::endl;
ClassImp(AliAnalysisTaskLYZEventPlane)
//________________________________________________________________________
AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane(const char *name) :
AliAnalysisTaskSE(name),
fEvent(NULL),
fLyzEp(NULL),
fLyz(NULL),
fListHistos(NULL),
fSecondRunFile(NULL)
{
// Constructor
cout<<"AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane(const char *name)"<<endl;
// Define input and output slots here
// Input slot #0 works with an AliFlowEventSimple
DefineInput(0, AliFlowEventSimple::Class());
DefineInput(1, TList::Class());
// Output slot #0 writes into a TList container
DefineOutput(1, TList::Class());
}
//________________________________________________________________________
AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane() :
AliAnalysisTaskSE(),
fEvent(NULL),
fLyzEp(NULL),
fLyz(NULL),
fListHistos(NULL),
fSecondRunFile(NULL)
{
// Constructor
cout<<"AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane()"<<endl;
}
//________________________________________________________________________
AliAnalysisTaskLYZEventPlane::~AliAnalysisTaskLYZEventPlane()
{
//destructor
}
//________________________________________________________________________
void AliAnalysisTaskLYZEventPlane::UserCreateOutputObjects()
{
// Called once
cout<<"AliAnalysisTaskLYZEventPlane::CreateOutputObjects()"<<endl;
//lee yang zeros event plane
fLyzEp = new AliFlowLYZEventPlane() ;
//Analyser
fLyz = new AliFlowAnalysisWithLYZEventPlane() ;
// Get data from input slot
TList* pSecondRunList = (TList*)GetInputData(1);
if (pSecondRunList) {
fLyzEp -> SetSecondRunList(pSecondRunList);
fLyz -> SetSecondRunList(pSecondRunList);
} else { cout<<"No Second run List!"<<endl; exit(0); }
fLyzEp-> Init();
fLyz-> Init();
if (fLyz->GetHistList()) {
fListHistos = fLyz->GetHistList();
//fListHistos->Print();
}
else { cout<<"ERROR: Could not retrieve histogram list"<<endl;}
PostData(1,fListHistos);
}
//________________________________________________________________________
void AliAnalysisTaskLYZEventPlane::UserExec(Option_t *)
{
// Main loop
// Called for each event
fEvent = dynamic_cast<AliFlowEventSimple*>(GetInputData(0));
if (fEvent) {
fLyz->Make(fEvent,fLyzEp);
}
else {
cout << "Warning no input data!!!" << endl;}
PostData(1,fListHistos);
}
//________________________________________________________________________
void AliAnalysisTaskLYZEventPlane::Terminate(Option_t *)
{
// Called once at the end of the query
AliFlowAnalysisWithLYZEventPlane* lyzTerm = new AliFlowAnalysisWithLYZEventPlane() ;
fListHistos = (TList*)GetOutputData(1);
//cout << "histogram list in Terminate" << endl;
if (fListHistos) {
lyzTerm -> GetOutputHistograms(fListHistos);
lyzTerm -> Finish();
PostData(1,fListHistos);
//fListHistos->Print();
} else { cout << "histogram list pointer is empty" << endl;}
//cout<<".....finished LYZ EventPlane"<<endl;
delete lyzTerm;
}
| 31.235294
| 93
| 0.686545
|
maroozm
|
f4cab2b2c4c57009bb838b1d3b13e58fcdb8e847
| 787
|
cpp
|
C++
|
backend/sgx/trusted/src/encryption.cpp
|
alxshine/eNNclave
|
639aa7e8df9440922788d0c2a79846b198f117aa
|
[
"MIT"
] | null | null | null |
backend/sgx/trusted/src/encryption.cpp
|
alxshine/eNNclave
|
639aa7e8df9440922788d0c2a79846b198f117aa
|
[
"MIT"
] | null | null | null |
backend/sgx/trusted/src/encryption.cpp
|
alxshine/eNNclave
|
639aa7e8df9440922788d0c2a79846b198f117aa
|
[
"MIT"
] | null | null | null |
#include "encryption.h"
#include "sgxParameterLoader.h"
#include <memory>
#include "output.h"
using namespace eNNclave;
using namespace std;
namespace
{
std::unique_ptr<SgxParameterLoader> parameterLoader;
} // namespace
void open_encrypted_parameters()
{
parameterLoader = std::unique_ptr<SgxParameterLoader>(new SgxParameterLoader("backend/generated/parameters.bin.aes", true)); // TODO: handle potential exception
}
int encrypt_parameters(float *target_buffer, int num_elements){
try{
parameterLoader->WriteParameters(target_buffer, num_elements);
}catch(logic_error e){
print_err(e.what());
return 1;
}
return 0;
};
void close_encrypted_parameters()
{
auto *actualLoader = parameterLoader.release();
delete actualLoader;
}
| 23.848485
| 164
| 0.733164
|
alxshine
|
f4cb58df8bc7c0e402744e2a1a91c261ba5edabc
| 1,797
|
cpp
|
C++
|
src/Display.cpp
|
yann-boyer/OKUR
|
f575dbd3d06fa8f669bfadc2918e757168e231be
|
[
"Zlib"
] | 1
|
2022-03-22T15:10:44.000Z
|
2022-03-22T15:10:44.000Z
|
src/Display.cpp
|
yann-boyer/OKUR
|
f575dbd3d06fa8f669bfadc2918e757168e231be
|
[
"Zlib"
] | null | null | null |
src/Display.cpp
|
yann-boyer/OKUR
|
f575dbd3d06fa8f669bfadc2918e757168e231be
|
[
"Zlib"
] | null | null | null |
/*
This file is a part of OKUR.
This file contains code to emulate
Chip8 screen.
Copyright (c) 2022 - Yann BOYER.
*/
#include "Display.hpp"
Display::Display() {
chip8Window = SDL_CreateWindow(
"OKUR Chip8 Emu by Yann BOYER.",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WINDOW_WIDTH,
WINDOW_HEIGHT,
SDL_WINDOW_SHOWN |
SDL_WINDOW_OPENGL |
SDL_WINDOW_RESIZABLE |
SDL_WINDOW_ALLOW_HIGHDPI
);
if(chip8Window == nullptr) {
std::cerr << "Unable to create and initialize window !" << std::endl;
exit(EXIT_FAILURE);
}
chip8Renderer = SDL_CreateRenderer(chip8Window, -1, 0);
if(chip8Renderer == nullptr) {
std::cerr << "Unable to create and initialize renderer !" << std::endl;
exit(EXIT_FAILURE);
}
chip8Texture = SDL_CreateTexture(
chip8Renderer,
SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET,
SCREEN_WIDTH,
SCREEN_HEIGHT
);
if(chip8Texture == nullptr) {
std::cerr << "Unable to create and initialize texture !" << std::endl;
exit(EXIT_FAILURE);
}
SDL_SetRenderDrawColor(chip8Renderer, 0, 0, 0, 0);
SDL_RenderClear(chip8Renderer);
SDL_RenderPresent(chip8Renderer);
}
void Display::bufferGraphics(MMU &mmu) {
for(uint8_t y = 0; y < 32; y++) {
for(uint8_t x = 0; x < 64; x++) {
uint8_t pixel = mmu.gfx[y][x];
pixelBuffer[(y * SCREEN_WIDTH) + x] = (pixel * 0xFFFFFF00) | 0x000000FF;
}
}
}
void Display::drawGraphics(void) {
SDL_UpdateTexture(chip8Texture, NULL, pixelBuffer, SCREEN_WIDTH * sizeof(uint32_t));
SDL_RenderClear(chip8Renderer);
SDL_RenderCopy(chip8Renderer, chip8Texture, NULL, NULL);
SDL_RenderPresent(chip8Renderer);
}
void Display::destroyDisplay(void) {
SDL_DestroyWindow(chip8Window);
SDL_DestroyRenderer(chip8Renderer);
SDL_DestroyTexture(chip8Texture);
delete[] pixelBuffer;
SDL_Quit();
}
| 23.337662
| 85
| 0.723984
|
yann-boyer
|
f4d79e89943264d79c4041097bad11fe2e7f6c89
| 37,548
|
cpp
|
C++
|
3p/ClassLib/Windows/window.cpp
|
stbrenner/NiLogViewer
|
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
|
[
"MIT"
] | 2
|
2018-11-20T15:58:08.000Z
|
2021-12-15T14:51:10.000Z
|
3p/ClassLib/Windows/window.cpp
|
stbrenner/NiLogViewer
|
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
|
[
"MIT"
] | 1
|
2016-12-27T08:26:27.000Z
|
2016-12-27T08:26:27.000Z
|
3p/ClassLib/Windows/window.cpp
|
ymx/NiLogViewer
|
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
|
[
"MIT"
] | 1
|
2016-08-09T10:44:48.000Z
|
2016-08-09T10:44:48.000Z
|
//
// window.cpp
//
// (C) Copyright 2000 Jan van den Baard.
// All Rights Reserved.
//
#include "window.h"
#include "mdiwindow.h"
#include "../application.h"
#include "../gdi/gdiobject.h"
#include "../gdi/dc.h"
#include "../menus/menu.h"
#include "../menus/bitmapmenu.h"
#include "../tools/multimonitor.h"
#include "../tools/xpcolors.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Just in case...
#ifndef WM_QUERYUISTATE
#define WM_CHANGEUISTATE 0x0127
#define WM_UPDATEUISTATE 0x0128
#define WM_QUERYUISTATE 0x0129
#endif
// Lists of all window objects created.
ClsLinkedList<ClsWindow> temporary_window_list;
ClsLinkedList<ClsWindow> global_window_list;
typedef BOOL ( CALLBACK *ANIMATEWINDOW )( HWND, DWORD, DWORD );
typedef BOOL ( CALLBACK *SETLAYEREDWINDOWATTRIBUTES )( HWND, COLORREF, BYTE, DWORD );
// Statics.
HMENU ClsWindow::s_hMenu = NULL;
HWND ClsWindow::s_hMDIClient = NULL;
static ANIMATEWINDOW StaticAnimateWindow = NULL;
static SETLAYEREDWINDOWATTRIBUTES StaticSetLayeredWindowAttributes = NULL;
// Defined in "bitmapmenu.cpp".
extern ClsLinkedList<ClsMenu> global_menu_list;
// Finds a window object in the list by it's handle
// value.
ClsWindow *ClsFindObjectByHandle( ClsLinkedList<ClsWindow>& list, HWND hWnd )
{
_ASSERT_VALID( hWnd ); // This must be valid.
_ASSERT( IsWindow( hWnd )); // Only window handles.
// Iterate the nodes.
for ( ClsWindow *pWindow = list.GetFirst(); pWindow; pWindow = list.GetNext( pWindow ))
{
// Is the handle wrapped by this object
// the one we are looking for?
if ( pWindow->GetSafeHWND() == hWnd )
// Yes. Return a pointer to the object.
return pWindow;
}
// Object not in the list.
return NULL;
}
// Constructor. Setup data field(s).
ClsWindow::ClsWindow()
{
// Setup window type.
m_bIsDialog = FALSE;
m_bIsMDIFrame = FALSE;
m_bIsPopup = FALSE;
// Clear data.
m_hWnd = NULL;
m_lpfnOldWndProc = NULL;
m_bDestroyHandle = TRUE;
s_hMenu = NULL;
// Add this object to the global list.
global_window_list.AddHead( this );
}
// Destructor. Destroys the window
// unless it is detached.
ClsWindow::~ClsWindow()
{
// Destroy the window.
Destroy();
// Remove us from the global list if we where
// still linked into it.
ClsWindow *pWindow;
for ( pWindow = global_window_list.GetFirst(); pWindow; pWindow = global_window_list.GetNext( pWindow ))
{
// Is this us?
if ( pWindow == this )
{
// Yes. remove us from the list.
global_window_list.Remove( this );
return;
}
}
}
// Destroys the wrapped window if
// possible.
void ClsWindow::Destroy()
{
// Do we wrap a valid handle?
if ( GetSafeHWND())
{
// Destroy the window.
if ( m_bDestroyHandle )
// Destroy the handle.
::DestroyWindow( m_hWnd );
else
// Detach the handle to reset
// the original window procedure.
Detach();
}
}
// Detaches the window from the
// object.
HWND ClsWindow::Detach()
{
// Handle valid?
if ( GetSafeHWND())
{
// Did we subclass the window? If not we can't
// detach it. If we did the window would be left
// without a window procedure.
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
{
// Set back the original window procedure.
::SetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )m_lpfnOldWndProc );
// Get return code.
HWND hWnd = m_hWnd;
// Clear fields.
m_bIsDialog = FALSE;
m_hWnd = NULL;
m_lpfnOldWndProc = NULL;
// Return result.
return hWnd;
}
}
return NULL;
}
// Attach a window handle to this object. This will only
// work if this object does not already have a handle
// attached to it.
BOOL ClsWindow::Attach( HWND hWnd, BOOL bDestroy /* = FALSE */ )
{
_ASSERT_VALID( IsWindow( hWnd ) ); // Handle must be valid.
_ASSERT( GetSafeHWND() == NULL ); // Already has a handle.
// Is the handle already attached to
// another object? If so it may not
// be set to be destroyed by this object.
if ( bDestroy )
{
if ( ClsFindObjectByHandle( global_window_list, hWnd ) ||
ClsFindObjectByHandle( temporary_window_list, hWnd ))
{
_ASSERT( bDestroy == FALSE );
return FALSE;
}
}
// First we see if the handle is a normal window
// or a dialog.
TCHAR szClassName[ 10 ];
if ( ::GetClassName( hWnd, szClassName, 10 ))
{
// Is it a dialog?
m_bIsDialog = ( BOOL )( _tcscmp( _T( "#32770" ), szClassName ) == 0 );
// Save the handle.
m_hWnd = hWnd;
m_bDestroyHandle = bDestroy;
// Get the window procedure.
m_lpfnOldWndProc = ( WNDPROC )::GetWindowLongPtr( hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC );
// Is the window proc already our static
// window procedure?
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
{
// Call the PreSubclassWindow() override.
PreSubclassWindow();
// Subclass the original window
// procedure.
::SetWindowLongPtr( hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )ClsWindow::StaticWindowProc );
}
// Return success.
return TRUE;
}
// Failed.
m_lpfnOldWndProc = NULL;
m_hWnd = NULL;
return FALSE;
}
// Create the window.
BOOL ClsWindow::Create( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hwndParent, HMENU nIDorHMenu )
{
_ASSERT( m_hWnd == NULL ); // Must be zero!
// Do we already have a handle?
if ( GetSafeHWND() )
return FALSE;
// Setup the CREATESTRUCT.
CREATESTRUCT cs;
cs.dwExStyle = dwExStyle;
cs.lpszClass = lpszClassName;
cs.lpszName = lpszWindowName;
cs.style = dwStyle;
cs.x = x;
cs.y = y;
cs.cx = nWidth;
cs.cy = nHeight;
cs.hwndParent = hwndParent;
cs.hMenu = nIDorHMenu;
cs.lpCreateParams = 0L;
// Call the PreCreateWindow() function.
if ( PreCreateWindow( &cs ))
{
_ASSERT_VALID( cs.lpszClass ); // This must be known by now!
// Create the window.
m_hWnd = ::CreateWindowEx( cs.dwExStyle,
cs.lpszClass,
cs.lpszName,
cs.style,
cs.x,
cs.y,
cs.cx,
cs.cy,
cs.hwndParent,
cs.hMenu,
ClsGetInstanceHandle(),
( LPVOID )this );
// Subclass the window.
if ( m_hWnd )
{
// We destroy the handle.
m_bDestroyHandle = TRUE;
// Get the window procedure.
m_lpfnOldWndProc = ( WNDPROC )::GetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC );
// Is the window proc already our static
// window procedure?
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
{
// Call the PreSubclassWindow() override.
PreSubclassWindow();
// Subclass the original window
// procedure.
if ( ::SetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )ClsWindow::StaticWindowProc ))
// Return success.
return TRUE;
}
else
// Return success.
return TRUE;
}
// return success or failure.
return ( BOOL )( m_hWnd );
}
return FALSE;
}
// Create the window.
BOOL ClsWindow::Create( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const ClsRect& crBounds, HWND hwndParent, HMENU nIDorHMenu )
{
// Create the window.
return Create( dwExStyle, lpszClassName, lpszWindowName, dwStyle, crBounds.Left(), crBounds.Top(), crBounds.Width(), crBounds.Height(), hwndParent, nIDorHMenu );
}
// Modify the window style.
void ClsWindow::ModifyStyle( DWORD dwRemove, DWORD dwAdd, DWORD dwFlags /* = 0 */ )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// First we get the current window style.
DWORD dwStyle = ( DWORD )::GetWindowLongPtr( m_hWnd, GWL_STYLE );
// Change bits.
dwStyle &= ~dwRemove;
dwStyle |= dwAdd;
// Change the style.
::SetWindowLongPtr( m_hWnd, GWL_STYLE, ( LONG_PTR )( dwStyle | dwFlags ));
}
// Modify the extended window style.
void ClsWindow::ModifyExStyle( DWORD dwRemove, DWORD dwAdd, DWORD dwFlags /* = 0 */ )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// First we get the current window extended style.
DWORD dwExStyle = ( DWORD )::GetWindowLongPtr( m_hWnd, GWL_EXSTYLE );
// Change bits.
dwExStyle &= ~dwRemove;
dwExStyle |= dwAdd;
// Change the extended style.
::SetWindowLongPtr( m_hWnd, GWL_EXSTYLE, ( LONG_PTR )( dwExStyle | dwFlags ));
}
// Get the rectangle of a child window.
ClsRect ClsWindow::GetChildRect( UINT nID ) const
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
ClsRect crRect;
GetChildRect( crRect, nID );
return crRect;
}
// Get the rectangle of a child window.
void ClsWindow::GetChildRect( ClsRect& crRect, UINT nID ) const
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// Get the child window.
HWND hWndChild = ::GetDlgItem( m_hWnd, nID );
// OK?
if ( hWndChild )
{
// Get it's rectangle.
::GetWindowRect( hWndChild, crRect );
// Map to the window.
::MapWindowPoints( NULL, m_hWnd, ( LPPOINT )( LPRECT )crRect, 2 );
}
}
// Set the window text.
void ClsWindow::SetWindowText( LPCTSTR pszText )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// If the hi-order word of "pszText" is 0
// we load the string from the resources.
if ( pszText && HIWORD( pszText ) == 0 )
{
// Load the string.
ClsString str( pszText );
::SetWindowText( m_hWnd, str );
return;
}
// Set the text.
::SetWindowText( m_hWnd, pszText );
}
// Get the checked radion button.
int ClsWindow::GetCheckedRadioButton( int nIDFirstButton, int nIDLastButton )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// Get button checked states.
for ( int i = nIDFirstButton; i <= nIDLastButton; i++ )
{
// Is it checked?
if ( ::IsDlgButtonChecked( m_hWnd, i ))
return i;
}
return 0;
}
int ClsWindow::GetDlgItemText( int nID, LPTSTR lpStr, int nMaxCount ) const
{ _ASSERT_VALID( GetSafeHWND() );
ClsWindow *pWindow = GetDlgItem( nID );
if ( pWindow )
return pWindow->GetWindowText( lpStr, nMaxCount );
return 0;
}
int ClsWindow::GetDlgItemText( int nID, ClsString& rString ) const
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
ClsWindow *pWindow = GetDlgItem( nID );
if ( pWindow )
return pWindow->GetWindowText( rString );
return 0;
}
void ClsWindow::DeleteTempObjects()
{
ClsWindow *pWindow;
// Remove all objects and delete them.
while (( pWindow = temporary_window_list.RemoveHead()) != NULL )
delete pWindow;
}
// Called just before the window is subclassed.
void ClsWindow::PreSubclassWindow()
{
}
// Called just before the window is created.
BOOL ClsWindow::PreCreateWindow( LPCREATESTRUCT pCS )
{
// Use default class if none is given.
if ( pCS->lpszClass == NULL )
pCS->lpszClass = _T( "ClsWindowClass" );
// Continue creating the window.
return TRUE;
}
// Handle message traffic.
LRESULT ClsWindow::HandleMessageTraffic()
{
BOOL bTranslate = FALSE;
MSG msg;
// Enter the message loop.
while ( GetMessage( &msg, NULL, 0, 0 ) > 0 )
{
// Accelerator?
if ( msg.hwnd == NULL || ( ClsGetApp()->TranslateAccelerator( &msg )))
continue;
// Is there an MDI client? If so try to translate the
// accelerators.
if ( ClsWindow::s_hMDIClient && TranslateMDISysAccel( ClsWindow::s_hMDIClient, &msg ))
continue;
// Get the message window object. The message window may not
// be located in the global window list since it might be a
// child of the window located in the global window list.
//
// For example the messages from a edit control in a combobox
// control. In this case, when the message window is not found,
// we look up it's parent in the global window list.
ClsWindow *pWindow = ClsFindObjectByHandle( global_window_list, msg.hwnd );
if ( pWindow == NULL && IsChild( msg.hwnd )) pWindow = ClsFindObjectByHandle( global_window_list, ::GetParent( msg.hwnd ));
// Call the PreTranslateMessage() function to pre-process
// the message.
if ( pWindow )
{
bTranslate = pWindow->PreTranslateMessage( &msg );
}
else
{
// A dialog message for the active window?
bTranslate = ::IsDialogMessage( GetActiveWindow(), &msg );
if ( ! bTranslate )
{
// Is it a child window? If so we iterate the
// parent windows until we find one that
// translates the message or has no parent.
if ( IsChild( msg.hwnd ))
{
HWND hParent = ::GetParent( msg.hwnd );
ClsWindow *pTemp;
// Does the parent exist?
if ( hParent )
{
// Wrap the handle.
pTemp = ClsWindow::FromHandle( hParent );
// Do a translation.
if ( ! pTemp->PreTranslateMessage( &msg ))
{
// The message did not translate. Iterate until we
// find a parent which does.
while (( hParent = ::GetParent( hParent )) != NULL )
{
// Wrap the handle.
pTemp = ClsWindow::FromHandle( hParent );
// Does this one translate?
if ( pTemp->PreTranslateMessage( &msg ) == TRUE )
{
// Yes. Break up the loop.
bTranslate = TRUE;
break;
}
}
}
else
// Message was translated.
bTranslate = TRUE;
}
else
{
// Try it as a dialog message for the active window.
bTranslate = ::IsDialogMessage( ::GetActiveWindow(), &msg );
}
}
else
{
// Try it as a dialog message for the active window.
bTranslate = ::IsDialogMessage( ::GetActiveWindow(), &msg );
}
}
}
// Can we dispatch?
if ( ! bTranslate )
{
// Message was not handled. Dispatch it.
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
// Delete temporary GDI, Window and (Bitmap)Menu objects.
ClsGdiObject::DeleteTempObjects();
ClsMenu::DeleteTempObjects();
ClsBitmapMenu::DeleteTempObjects();
ClsWindow::DeleteTempObjects();
}
// Return the result.
return ( LRESULT )msg.wParam;
}
// Called just after the WM_NCDESTROY message
// was handled.
void ClsWindow::PostNcDestroy()
{
// Reset variables.
m_bIsDialog = FALSE;
m_hWnd = NULL;
m_lpfnOldWndProc = NULL;
}
// Returns FALSE by default.
BOOL ClsWindow::PreTranslateMessage( LPMSG pMsg )
{
// Are we a dialog? If so see if the message can be
// processed by IsDialogMessage.
if ( m_bIsDialog && IsDialogMessage( pMsg ))
return TRUE;
// Are we a child window? If so we see if our parent
// is a dialog and let it have a go at the message
// first.
ClsWindow *pParent = GetParent();
if ( pParent /*&& pParent->m_bIsDialog*/ && pParent->IsDialogMessage( pMsg ))
return TRUE;
// Message not processed.
return FALSE;
}
// WM_COMMAND message handler.
LRESULT ClsWindow::OnCommand( UINT nNotifyCode, UINT nCtrlID, HWND hWndCtrl )
{
// Not handled.
return -1;
}
// Reflected WM_COMMAND message handler.
LRESULT ClsWindow::OnReflectedCommand( UINT nNotifyCode, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// WM_NOTIFY message handler.
LRESULT ClsWindow::OnNotify( LPNMHDR pNMHDR )
{
// Not handled.
return -1;
}
// Reflected WM_NOTIFY message handler.
LRESULT ClsWindow::OnReflectedNotify( LPNMHDR pNMHDR, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// WM_PAINT message handler.
LRESULT ClsWindow::OnPaint( ClsDC *pDC )
{
// Not handled.
return -1;
}
// WM_ERASEBKGND message handler.
LRESULT ClsWindow::OnEraseBkgnd( ClsDC *pDC )
{
// Not handled.
return -1;
}
// WM_SIZE message handler.
LRESULT ClsWindow::OnSize( UINT nSizeType, int nWidth, int nHeight )
{
// Not handled.
return -1;
}
// WM_MOVE message handler.
LRESULT ClsWindow::OnMove( int xPos, int yPos )
{
// Not handled.
return -1;
}
// WM_DESTROY message handler.
LRESULT ClsWindow::OnDestroy()
{
// Not handled.
return -1;
}
// WM_CLOSE message handler.
LRESULT ClsWindow::OnClose()
{
// Not handled.
return -1;
}
// WM_MEASUREITEM message handler.
LRESULT ClsWindow::OnMeasureItem( UINT nID, LPMEASUREITEMSTRUCT pMis )
{
// Not handled.
return -1;
}
// WM_DRAWITEM message handler.
LRESULT ClsWindow::OnDrawItem( UINT nID, LPDRAWITEMSTRUCT pDis )
{
// Not handled.
return -1;
}
// Reflected WM_MEASUREITEM message handler.
LRESULT ClsWindow::OnReflectedMeasureItem( UINT nID, LPMEASUREITEMSTRUCT pMis, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// Reflected WM_DRAWITEM message handler.
LRESULT ClsWindow::OnReflectedDrawItem( UINT nID, LPDRAWITEMSTRUCT pDis, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// WM_CREATE message handler.
LRESULT ClsWindow::OnCreate( LPCREATESTRUCT pCS )
{
// Not handled. Note this is a special case. -1
// means failure with WM_CREATE messages.
return -2;
}
// Window procedure.
LRESULT ClsWindow::WindowProc( UINT uMsg, WPARAM wParam, LPARAM lParam )
{
LRESULT lResult = 0;
// Do we have an original window procedure to call?
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
// Call the original window procedure.
lResult = ::CallWindowProc( m_lpfnOldWndProc, GetSafeHWND(), uMsg, wParam, lParam );
else if ( m_bIsDialog == FALSE )
{
// Are we an MDI frame?
if ( m_bIsMDIFrame )
// Call the default procedure for MDI frames.
//
// The casting of the this pointer I do here is dangerous. If someone
// decides to create a "ClsWindow" derived class and set the "m_bIsMDIFrame"
// we are screwed. For now it works but I should consider another approach...
lResult = ::DefFrameProc( GetSafeHWND(), reinterpret_cast< ClsMDIMainWindow * >( this )->GetMDIClient()->GetSafeHWND(), uMsg, wParam, lParam );
else
// Call the default window procedure.
lResult = ::DefWindowProc( GetSafeHWND(), uMsg, wParam, lParam );
}
// Return the result.
return lResult;
}
// By default we use the current window size...
BOOL ClsWindow::OnGetMinSize( ClsSize& szMinSize )
{
ClsRect rc;
GetWindowRect( rc );
szMinSize = rc.Size();
return TRUE;
}
// Operator overload.
ClsWindow::operator HWND() const
{
return m_hWnd;
}
LRESULT CALLBACK ClsWindow::StaticWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
// We will need this.
ClsWindow *pWindow = NULL;
BOOL bFromTemp = FALSE;
// Do we need to attach the handle to it's
// object?
if ( uMsg == WM_NCCREATE )
{
// The object pointer of this window must be
// passed using the lParam field of the
// CREATESTRUCT structure.
pWindow = ( ClsWindow * )(( LPCREATESTRUCT )lParam )->lpCreateParams;
// Should be valid.
//_ASSERT_VALID( pWindow );
// Attach us to the object.
if ( pWindow ) pWindow->Attach( hWnd, TRUE );
}
else if ( uMsg == WM_INITDIALOG )
{
_ASSERT_VALID( lParam ); // Must be a valid pointer.
// First we check to see if the lParam parameter is
// an object from our global window list.
for ( pWindow = global_window_list.GetFirst(); pWindow != ( ClsWindow * )lParam && pWindow; pWindow = global_window_list.GetNext( pWindow ));
// If the object was not found in the list it must be
// a PROPSHEETPAGE pointer. In this case the object should
// be in the lParam field of this structure.
if ( pWindow == NULL )
pWindow = ( ClsWindow * )(( PROPSHEETPAGE * )lParam )->lParam;
// Should be valid.
_ASSERT_VALID( pWindow );
// Attach us to the object.
pWindow->Attach( hWnd, TRUE );
}
else
{
// When we reach this place the handle must be attached
// already.
pWindow = ClsFindObjectByHandle( global_window_list, hWnd );
if ( pWindow == NULL )
{
// We were not located in the globals list
// so we must be in the temporary list.
bFromTemp = TRUE;
pWindow = ClsFindObjectByHandle( temporary_window_list, hWnd );
}
}
// Do we have a valid object pointer?
if ( pWindow != NULL && pWindow->GetSafeHWND() )
{
// Preset message result.
LRESULT lResult = -1;
// Get message type.
switch ( uMsg )
{
case WM_UPDATEUISTATE:
case WM_SYSCOLORCHANGE:
// Update XP colorschemes.
XPColors.CreateColorTable();
// Pass on to the children.
EnumChildWindows( pWindow->GetSafeHWND(), DistributeMessage, WM_SYSCOLORCHANGE );
// Fall through when the message was WM_UPDATEUISTATE...
if ( uMsg == WM_SYSCOLORCHANGE )
break;
case WM_CHANGEUISTATE:
// Are we a child window?
if ( pWindow->GetStyle() & WS_CHILD )
// Repaint...
pWindow->Invalidate();
break;
case WM_CREATE:
// Call virtual message handler.
lResult = pWindow->OnCreate(( LPCREATESTRUCT )lParam );
break;
case WM_CLOSE:
// Call virtual message handler.
lResult = pWindow->OnClose();
break;
case WM_DESTROY:
{
// Does this window have a menu?
HMENU hMenu = pWindow->GetMenu();
if ( hMenu )
{
// See if it is wrapped by an object in the global
// menu list.
for ( ClsMenu *pMenu = global_menu_list.GetFirst(); pMenu; pMenu = global_menu_list.GetNext( pMenu ))
{
// Is this it?
if ( *pMenu == hMenu )
{
// We detach the menu from the window before the window
// destroys the menu handle. This is necessary because the
// destructor of "ClsBitmapMenu" derived classes need the
// handle valid to free used resources.
pWindow->SetMenu( NULL );
break;
}
}
}
// Call virtual message handler.
lResult = pWindow->OnDestroy();
break;
}
case WM_MOVE:
// Call virtual message handler.
lResult = pWindow->OnMove(( int )LOWORD( lParam ), ( int )HIWORD( lParam ));
break;
case WM_SIZE:
// Call virtual message handler.
lResult = pWindow->OnSize(( UINT )wParam, ( int )LOWORD( lParam ), ( int )HIWORD( lParam ));
break;
case WM_PAINT:
{
// Do we have a DC?
ClsDC *pDC = wParam ? ClsDC::FromHandle(( HDC )wParam ) : NULL;
// Call virtual message handler.
lResult = pWindow->OnPaint( pDC );
break;
}
case WM_ERASEBKGND:
{
// Wrap handle.
ClsDC *pDC = ClsDC::FromHandle(( HDC )wParam );
// Call virtual message handler.
lResult = pWindow->OnEraseBkgnd( pDC );
break;
}
case WM_INITMENU:
// Store the menu handle which just opened.
ClsWindow::s_hMenu = ( HMENU )wParam;
// OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedInitMenu() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedInitMenu( pWindow );
}
break;
case WM_INITMENUPOPUP:
// Menu handle OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedInitMenuPopup() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedInitMenuPopup( pWindow, ( HMENU )wParam, LOWORD( lParam ), HIWORD( lParam ));
}
break;
case WM_UNINITMENUPOPUP:
// Menu handle OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedUnInitMenuPopup() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedUnInitMenuPopup( pWindow, ( HMENU )wParam, lParam );
}
break;
case WM_EXITMENULOOP:
// Menu handle OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedInitMenuPopup() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedExitMenuLoop( pWindow, ( BOOL )wParam );
}
// Clear the menu handle.
ClsWindow::s_hMenu = NULL;
break;
case WM_MEASUREITEM:
// Control?
if ( wParam )
{
// Try to get the window object of the control.
ClsWindow *pChild = pWindow->FromHandle( pWindow->GetDlgItemHandle((( LPMEASUREITEMSTRUCT )lParam )->CtlID ));
// Found it?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the measure item message to the child
// window.
lResult = pChild->OnReflectedMeasureItem(( UINT )wParam, ( LPMEASUREITEMSTRUCT )lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
else
{
// Find the menu.
if ( ! ClsWindow::s_hMenu ) ClsWindow::s_hMenu = pWindow->GetMenu();
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Wrap the handle.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu )
{
// Call the overidable.
lResult = pMenu->OnReflectedMeasureItem(( LPMEASUREITEMSTRUCT ) lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
}
// Call virtual message handler.
lResult = pWindow->OnMeasureItem(( UINT )wParam, ( LPMEASUREITEMSTRUCT )lParam );
break;
case WM_DRAWITEM:
// Control?
if ( wParam )
{
// Try to get the window object of the control.
ClsWindow *pChild = pWindow->FromHandle( pWindow->GetDlgItemHandle((( LPDRAWITEMSTRUCT )lParam )->CtlID ));
// Found it?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the draw item message to the child
// window.
lResult = pChild->OnReflectedDrawItem(( UINT )wParam, ( LPDRAWITEMSTRUCT )lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
else
{
// Find the menu.
if ( ! ClsWindow::s_hMenu ) ClsWindow::s_hMenu = pWindow->GetMenu();
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Wrap the handle.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu )
{
// Call the overidable.
lResult = pMenu->OnReflectedDrawItem(( LPDRAWITEMSTRUCT )lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
}
// Call virtual message handler.
lResult = pWindow->OnDrawItem(( UINT )wParam, ( LPDRAWITEMSTRUCT )lParam );
break;
case WM_COMMAND:
{
// Message originates from a control?
if ( lParam )
{
// Try to get the window object of the control which
// sent the message.
ClsWindow *pChild = ClsFindObjectByHandle( global_window_list, ( HWND )lParam );
// Found it?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the command message to the child
// window.
lResult = pChild->OnReflectedCommand(( UINT )HIWORD( wParam ), bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
// Call virtual message handler.
lResult = pWindow->OnCommand(( UINT )HIWORD( wParam ), ( UINT )LOWORD( wParam ), ( HWND )lParam );
break;
}
case WM_NOTIFY:
LPNMHDR pNMHDR = ( LPNMHDR )lParam;
// Try to get the window object of the
// notification control.
ClsWindow *pChild = ClsFindObjectByHandle( global_window_list, pNMHDR->hwndFrom );
// Where we able to find the object in our
// global list?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the notification message to the
// child window.
lResult = pChild->OnReflectedNotify( pNMHDR, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Must we notify the parent?
if ( ! bNotifyParent )
break;
}
// Simply forward the message.
pWindow->OnNotify( pNMHDR );
break;
}
// Are we still alive?
//if ( ! bFromTemp )
// for ( ClsWindow *pTmp = global_window_list.GetFirst(); pTmp != pWindow && pTmp; pTmp = global_window_list.GetNext( pTmp ));
//else
// for ( ClsWindow *pTmp = temporary_window_list.GetFirst(); pTmp != pWindow && pTmp; pTmp = temporary_window_list.GetNext( pTmp ));
//
// We may not have been deleted by any of the virtual
// message handlers!
//_ASSERT( pTmp != NULL );
// If the message was not handled (lResult is -1) and the
// object window handle is still valid we call the virtual
// window procedure.
//
// Note: The WM_CREATE message is a special case which returns
// -2 when the message was not handled since -1 indicates that
// the window should not be created when -1 is returned.
if ((( lResult == -1 && uMsg != WM_CREATE ) || ( lResult == -2 && uMsg == WM_CREATE )) && pWindow->GetSafeHWND())
// Call the procedure.
lResult = pWindow->WindowProc( uMsg, wParam, lParam );
// Are we being destroyed?
if ( uMsg == WM_NCDESTROY )
{
// detach the handle from the object.
if ( pWindow->GetSafeHWND())
{
// Detach the handle.
pWindow->Detach();
// Just in case these are not cleared which will
// happen when the window has the ClsWindow::StaticWindowProc
// as the default window procedure.
pWindow->m_hWnd = NULL;
pWindow->m_lpfnOldWndProc = NULL;
}
// Call the PostNcDestroy() routine if the class pointer
// still exists in the global window list.
ClsWindow *pTmp;
for ( pTmp = global_window_list.GetFirst(); pTmp; pTmp = global_window_list.GetNext( pTmp ))
{
// Is this it?
if ( pTmp == pWindow )
{
// Call it.
pWindow->PostNcDestroy();
return lResult;
}
}
}
// return the result of the message handling.
return lResult;
}
// We did not find the handle in our global
// window list which means that it was not (yet)
// attached to a ClsWindow object.
//
// In this case we simply let windows handle
// the messages.
TCHAR szClassName[ 10 ];
// Get the class name of the window.
if ( ::GetClassName( hWnd, szClassName, 10 ))
{
// Is it a dialog box? If so we return 0 and do not
// call the default window procedure.
if ( _tcscmp( _T( "#32770" ), szClassName ) == 0 )
return 0;
}
// Return the result of the default window
// procedure.
return ::DefWindowProc( hWnd, uMsg, wParam, lParam );
}
// Helper which will try to locate the window object of the
// given handle. If it does not find it it will create an
// object for it and append it to the temporary object list.
ClsWindow *ClsWindow::FindWindow( HWND hWnd )
{
// Return NULL if the input is NULL.
if ( hWnd == NULL ) return NULL;
// First we try to locate the handle in the
// global window list.
ClsWindow *pWindow = ClsFindObjectByHandle( global_window_list, hWnd );
// Found it?
if ( pWindow == NULL )
{
// No. Try to locate it in our temporary object list.
pWindow = ClsFindObjectByHandle( temporary_window_list, hWnd );
if ( pWindow == NULL )
{
// Not found. Create a new object.
pWindow = new ClsWindow;
pWindow->Attach( hWnd );
// Remove it from the global list and
// move it into the temporary object list.
global_window_list.Remove( pWindow );
temporary_window_list.AddHead( pWindow );
}
}
// Return the object.
return pWindow;
}
// Close all windows marked as being a popup.
void ClsWindow::ClosePopups()
{
// Iterate the global window list.
ClsWindow *pWindow;
for ( pWindow = global_window_list.GetFirst(); pWindow; pWindow = global_window_list.GetNext( pWindow ))
{
// A popup?
if ( pWindow->m_bIsPopup )
{
// Get a pointer to the next in the list. Close the popup
// and set the pointer to the next.
ClsWindow *pNext = global_window_list.GetNext( pWindow );
pWindow->SendMessage( WM_CLOSE );
pWindow = pNext;
}
}
// Iterate the temporary window list.
for ( pWindow = temporary_window_list.GetFirst(); pWindow; pWindow = temporary_window_list.GetNext( pWindow ))
{
// A popup?
if ( pWindow->m_bIsPopup )
{
// Get a pointer to the next in the list. Close the popup
// and set the pointer to the next.
ClsWindow *pNext = temporary_window_list.GetNext( pWindow );
pWindow->SendMessage( WM_CLOSE );
pWindow = pNext;
}
}
}
// Center the window on another window or
// on the desktop.
BOOL ClsWindow::CenterWindow( ClsWindow *pOn )
{
_ASSERT_VALID( GetSafeHWND() );
// Obtain the child window
// screen bounds.
ClsRect rc, prc, screen;
GetWindowRect( rc );
// Get the rectangle of the display monitor which
// the window intersects the most.
ClsMultiMon mon;
int nMonitor;
mon.MonitorNumberFromWindow( GetSafeHWND(), MONITOR_DEFAULTTONEAREST, nMonitor );
mon.GetMonitorRect( nMonitor, prc, TRUE );
screen = prc;
// Do we have a valid parent
// handle?
if ( pOn )
// Obtain the parent window
// screen bounds.
pOn->GetWindowRect( prc );
// Compute offsets...
int x = prc.Left() + (( prc.Width() / 2 ) - ( rc.Width() / 2 ));
int y = prc.Top() + (( prc.Height() / 2 ) - ( rc.Height() / 2 ));
// Make sure the whole window remains visible on the screen.
if (( x + rc.Width()) > screen.Right()) x = screen.Right() - rc.Width();
if ( x < screen.Left()) x = screen.Left();
if (( y + rc.Height()) > screen.Bottom()) y = screen.Bottom() - rc.Height();
if ( y < screen.Top()) y = screen.Top();
// Move the window so that it is
// centered.
return SetWindowPos( NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );
}
// AnimateWindow() API.
BOOL ClsWindow::AnimateWindow( DWORD dwTime, DWORD dwFlags )
{
_ASSERT_VALID( GetSafeHWND()); // Must be valid.
// Just in case...
#ifndef AW_HIDE
#define AW_HIDE 0x00010000
#endif
// Function known?
if ( StaticAnimateWindow )
return ( *StaticAnimateWindow )( m_hWnd, dwTime, dwFlags );
// Get the procedure address.
StaticAnimateWindow = ( ANIMATEWINDOW )GetProcAddress( GetModuleHandle( _T( "user32.dll" )), "AnimateWindow" );
if ( StaticAnimateWindow )
return ( *StaticAnimateWindow )( m_hWnd, dwTime, dwFlags );
return FALSE;
}
// SetLayeredWindowAttributes() API.
BOOL ClsWindow::SetLayeredWindowAttributes( COLORREF crKey, BYTE bAlpha, DWORD dwFlags )
{
_ASSERT_VALID( GetSafeHWND()); // Must be valid.
// Function known?
if ( StaticSetLayeredWindowAttributes )
return ( *StaticSetLayeredWindowAttributes )( m_hWnd, crKey, bAlpha, dwFlags );
// Get the procedure address.
StaticSetLayeredWindowAttributes = ( SETLAYEREDWINDOWATTRIBUTES )GetProcAddress( GetModuleHandle( _T( "user32.dll" )), "SetLayeredWindowAttributes" );
if ( StaticSetLayeredWindowAttributes )
return ( *StaticSetLayeredWindowAttributes )( m_hWnd, crKey, bAlpha, dwFlags );
return FALSE;
}
// Get a pointer to the active menu object.
ClsMenu *ClsWindow::GetActiveMenu()
{
// Is there an active menu?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Look it up.
ClsMenu *pMenu;
for ( pMenu = global_menu_list.GetFirst(); pMenu; pMenu = global_menu_list.GetNext( pMenu ))
{
// Is this the one?
if (( HMENU )*pMenu == ClsWindow::s_hMenu )
return pMenu;
}
}
return NULL;
}
// Get state of the UI.
DWORD ClsWindow::GetUIState() const
{
_ASSERT_VALID( GetSafeHWND()); // Must be valid.
// Supported?
if ( ClsGetApp()->GetPlatformID() == VER_PLATFORM_WIN32_NT && ClsGetApp()->GetMajorVersion() >= 5 )
// Get the UI state.
return ( DWORD )::SendMessage( m_hWnd, WM_QUERYUISTATE, 0, 0 );
// No UI state.
return 0L;
}
// Functions which make use of the ClsDC class.
ClsDC *ClsWindow::BeginPaint( LPPAINTSTRUCT pPaintStruct )
{
_ASSERT_VALID( GetSafeHWND() );
_ASSERT_VALID( pPaintStruct );
return ClsDC::FromHandle( ::BeginPaint( m_hWnd, pPaintStruct ));
}
ClsDC *ClsWindow::GetDC()
{
_ASSERT_VALID( GetSafeHWND() );
return ClsDC::FromHandle( ::GetDC( m_hWnd ));
}
ClsDC *ClsWindow::GetDCEx( ClsRgn* prgnClip, DWORD flags )
{
_ASSERT_VALID( GetSafeHWND() );
return ClsDC::FromHandle( ::GetDCEx( m_hWnd, prgnClip ? ( HRGN )*prgnClip : NULL, flags ));
}
ClsDC *ClsWindow::GetWindowDC()
{
_ASSERT_VALID( GetSafeHWND() );
return ClsDC::FromHandle( ::GetWindowDC( m_hWnd ));
}
int ClsWindow::ReleaseDC( ClsDC *pDC )
{
_ASSERT_VALID( GetSafeHWND() );
return ::ReleaseDC( m_hWnd, *pDC );
}
| 26.800857
| 177
| 0.6562
|
stbrenner
|
f4d992fa6259231d30a542a191c9d94793d23fc2
| 3,110
|
cpp
|
C++
|
libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp
|
roymacdonald/ofxLineaDeTiempo
|
1a080c7d5533dc9b0e587bd1557506fe288f05e8
|
[
"MIT"
] | 31
|
2020-04-29T06:11:54.000Z
|
2021-11-10T19:14:09.000Z
|
libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp
|
roymacdonald/ofxLineaDeTiempo
|
1a080c7d5533dc9b0e587bd1557506fe288f05e8
|
[
"MIT"
] | 11
|
2020-07-27T17:12:05.000Z
|
2021-12-01T16:33:18.000Z
|
libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp
|
roymacdonald/ofxLineaDeTiempo
|
1a080c7d5533dc9b0e587bd1557506fe288f05e8
|
[
"MIT"
] | null | null | null |
//
// KeyframeTrackHeader.cpp
// ofxGuiWidgetDOMintegration
//
// Created by Roy Macdonald on 4/12/20.
//
#include "LineaDeTiempo/View/KeyframeTrackHeader.h"
#include "LineaDeTiempo/View/TrackGroupView.h"
#include "LineaDeTiempo/View/BaseTrackView.h"
namespace ofx {
namespace LineaDeTiempo {
template<typename ParamType>
KeyframeTrackHeader<ParamType>::KeyframeTrackHeader(ofParameter<ParamType> & param, const std::string& id, const ofRectangle& rect, BaseTrackView* track, TrackGroupView* group, bool belongsToPanel)
: TrackHeader(id, rect, track, group, belongsToPanel)
{
_gui = addChild<ofxGuiView<ParamType>>(param, group->getTracksHeaderWidth(), this);
_gui->setPosition(0, 0);//ConstVars::ViewTopHeaderHeight);
_ofxGuiHeightChangeListener = _gui->shapeChanged.newListener(this, &KeyframeTrackHeader::_ofxGuiHeightChange);
_colorListener = track->colorChangeEvent.newListener(this, &KeyframeTrackHeader::_colorChanged);
}
template<typename ParamType>
float KeyframeTrackHeader<ParamType>::_getMinHeight()
{
return _gui->getShape().getMaxY();
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::_onShapeChange(const DOM::ShapeChangeEventArgs& e)
{
if(e.widthChanged())
{
_gui->setWidth(getWidth());
}
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::_ofxGuiHeightChange(DOM::ShapeChangeEventArgs& args)
{
if(args.changedVertically())
{
if(getHeight() < args.shape.getMaxY())
{
setHeight(args.shape.getMaxY());
}
}
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::onDraw() const
{
// the intention of this override is to avoid the drawing of the TrackHeader class
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::_colorChanged(ofColor& color)
{
if(_gui && _gui->getOfxGui())
{
_gui->getOfxGui()->setHeaderBackgroundColor(color);
_gui->getOfxGui()->setBackgroundColor(color);
}
}
template class KeyframeTrackHeader<ofRectangle>;
template class KeyframeTrackHeader<ofColor>;
template class KeyframeTrackHeader<ofShortColor>;
template class KeyframeTrackHeader<ofFloatColor>;
template class KeyframeTrackHeader<glm::vec2>;
template class KeyframeTrackHeader<glm::vec3>;
template class KeyframeTrackHeader<glm::vec4>;
//template class KeyframeTrackHeader<glm::quat>;
//template class KeyframeTrackHeader<glm::mat4>;
template class KeyframeTrackHeader<bool>;
template class KeyframeTrackHeader<void>;
template class KeyframeTrackHeader<int8_t>;
template class KeyframeTrackHeader<uint8_t>;
template class KeyframeTrackHeader<int16_t>;
template class KeyframeTrackHeader<uint16_t>;
template class KeyframeTrackHeader<int32_t>;
template class KeyframeTrackHeader<uint32_t>;
template class KeyframeTrackHeader<int64_t>;
template class KeyframeTrackHeader<uint64_t>;
template class KeyframeTrackHeader<float>;
template class KeyframeTrackHeader<double>;
#ifndef TARGET_LINUX
template class KeyframeTrackHeader<typename std::conditional<std::is_same<uint32_t, size_t>::value || std::is_same<uint64_t, size_t>::value, bool, size_t>::type>;
#endif
} } // ofx::LineaDeTiempo
| 26.581197
| 198
| 0.791318
|
roymacdonald
|
f4dbb4983a66a6d8cdf4192b8d85e3ba544a2928
| 104,662
|
cpp
|
C++
|
sxaccelerate/src/math/SxBlasLib.cpp
|
ashtonmv/sphinx_vdw
|
5896fee0d92c06e883b72725cb859d732b8b801f
|
[
"Apache-2.0"
] | 1
|
2020-02-29T03:26:32.000Z
|
2020-02-29T03:26:32.000Z
|
sxaccelerate/src/math/SxBlasLib.cpp
|
ashtonmv/sphinx_vdw
|
5896fee0d92c06e883b72725cb859d732b8b801f
|
[
"Apache-2.0"
] | null | null | null |
sxaccelerate/src/math/SxBlasLib.cpp
|
ashtonmv/sphinx_vdw
|
5896fee0d92c06e883b72725cb859d732b8b801f
|
[
"Apache-2.0"
] | null | null | null |
// ---------------------------------------------------------------------------
//
// The general purpose cross platform C/C++ framework
//
// S x A c c e l e r a t e
//
// Home: https://www.sxlib.de
// License: Apache 2
// Authors: see src/AUTHORS
//
// ---------------------------------------------------------------------------
// ref1 - Comp. Phys. Comm (128), 1-45 (2000)
//#include <stdio.h>
//#include <string.h>
//#include <stdlib.h>
//#include <iostream>
#include <math.h>
#include <SxBlasLib.h>
#include <SxError.h>
#ifdef USE_OPENMP
#include <omp.h>
#endif
//#include <SxRandom.h>
// --- BLAS, LAPACK
#if defined(USE_VECLIB)
//# include <veclib.h> // --- don't use HP header files!
//# include <lapack.h> // more details in SxMLIB.h
# include <SxMLIB.h>
#elif defined (ESSE_ESSL)
// --- before including ESSL we have to do a messy definition
// otherwise it doesn't compile. i don't know a better way.
// see also: SxFFT.h
# define _ESV_COMPLEX_
# include <complex>
# include <essl.h>
#elif defined (USE_INTEL_MKL)
// mkl uses 'long long', which is not ISO C++. Disable errors here.
//#pragma GCC diagnostic push
//#pragma GCC diagnostic warning "-Wlong-long"
extern "C" {
# include <mkl.h>
}
//#pragma GCC diagnostic pop
#elif defined (USE_ACML)
extern "C" {
# include <acml.h>
}
#elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
# define blasint int
extern "C" {
# include <f2c.h>
# include <cblas.h>
# include <clapack.h>
}
#elif defined (USE_ATLAS)
# if defined (USE_ACCELERATE_FRAMEWORK)
# include <Accelerate/Accelerate.h>
typedef __CLPK_integer integer;
typedef __CLPK_logical logical;
typedef __CLPK_real real;
typedef __CLPK_doublereal doublereal;
typedef __CLPK_ftnlen ftnlen;
typedef __CLPK_complex complex;
typedef __CLPK_doublecomplex doublecomplex;
# else
extern "C" {
# include <f2c.h>
# include <cblas.h>
# include <clapack.h>
}
# endif /* USE_ACCELERATE_FRAMEWORK */
#else
# error "No numeric library specified"
// make sure that we do not drown in error messages
#define SX_IGNORE_THE_REST_OF_THE_FILE
#endif
#ifndef SX_IGNORE_THE_REST_OF_THE_FILE
//------------------------------------------------------------------------------
// BLAS/LAPACK error handling
//------------------------------------------------------------------------------
#if defined (USE_VECLIB)
// error handling not yet supported
#elif defined (USE_ESSL)
// error handling not yet supported
#elif defined (USE_INTEL_MKL)
// error handling not yet supported
#elif defined (USE_ACML)
// error handling not yet supported
#elif defined (USE_GOTO)
// error handling not yet supported
#else
# include <stdarg.h>
#ifdef MACOSX
# if ( DIST_VERSION_L >= 1070L )
extern "C" void cblas_xerbla (int p, char *rout, char *form, ...)
# else
extern "C" void cblas_xerbla (int p, const char *rout, const char *form, ...)
# endif /* DIST_VERSION_L */
#else
extern "C" void cblas_xerbla (int p, const char *rout, const char *form, ...)
#endif /* MACOSX */
{
//sxprintf ("\nA BLAS/LAPACK error has occured!\n");
std::cout << "\nA BLAS/LAPACK error has occured!\n";
// --- original code from ATLAS/interfaces/blas/C/src/cblas_xerbla.c
va_list argptr;
va_start(argptr, form);
# ifdef GCCWIN
//if (p) sxprintf("Parameter %d to routine %s was incorrect\n", p, rout);
if (p) std::cout << "Parameter " << p << " to routine "
<< rout << " was incorrect\n";
vprintf(form, argptr);
# else
if (p)
fprintf(stderr, "Parameter %d to routine %s was incorrect\n",
p, rout);
vfprintf(stderr, form, argptr);
# endif /* CYGWIN */
va_end(argptr);
// --- end of original ATLAS code
SX_EXIT;
}
#endif /* USE_VECLIB */
//------------------------------------------------------------------------------
// norm of vectors
//------------------------------------------------------------------------------
float norm2 (const float *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return snrm2 (&n, (float *)vec, &incx);
# elif defined (USE_ESSL)
return snrm2 (n, vec, incx);
# elif defined (USE_INTEL_MKL)
return snrm2 (&n, const_cast<float *>(vec), &incx);
# elif defined (USE_ACML)
return snrm2 (n, const_cast<float *>(vec), incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_snrm2 (n, const_cast<float *>(vec), incx);
# else
return cblas_snrm2 (n, vec, incx);
# endif
}
double norm2 (const double *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return dnrm2 (&n, (double *)vec, &incx);
# elif defined (USE_ESSL)
return dnrm2 (n, vec, incx);
# elif defined (USE_INTEL_MKL)
return dnrm2 (&n, const_cast<double *>(vec), &incx);
# elif defined (USE_ACML)
return dnrm2 (n, const_cast<double *>(vec), incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_dnrm2 (n, const_cast<double*>(vec), incx);
# else
return cblas_dnrm2 (n, vec, incx);
# endif
}
float norm2 (const SxComplex8 *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return scnrm2 (&n, (complex8_t *)vec, &incx);
# elif defined (USE_ESSL)
return scnrm2 (n, (const complex<float> *)vec, incx);
# elif defined (USE_INTEL_MKL)
return scnrm2 (&n, (MKL_Complex8 *)const_cast<SxComplex8 *>(vec), &incx);
# elif defined (USE_ACML)
return scnrm2 (n, (complex *)const_cast<SxComplex8 *>(vec), incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_scnrm2 (n, (float*)vec, incx);
# else
return cblas_scnrm2 (n, vec, incx);
# endif
}
double norm2 (const SxComplex16 *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return dznrm2 (&n, (complex16_t *)vec, &incx);
# elif defined (USE_ESSL)
return dznrm2 (n, (const complex<double> *)vec, incx);
# elif defined (USE_INTEL_MKL)
return dznrm2 (&n, (MKL_Complex16 *)const_cast<SxComplex16*>(vec), &incx);
# elif defined (USE_ACML)
return dznrm2 (n, (doublecomplex *)const_cast<SxComplex16 *>(vec),
incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_dznrm2 (n, (double*)vec, incx);
# else
return cblas_dznrm2 (n, vec, incx);
# endif
}
//------------------------------------------------------------------------------
// scale vectors
//------------------------------------------------------------------------------
void scale (float *vec, const float alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
sscal (&n, (float *)&alpha, (float *)vec, &incx);
# elif defined (USE_ESSL)
sscal (n, alpha, vec, incx);
# elif defined (USE_INTEL_MKL)
sscal (&n, const_cast<float *>(&alpha), (float *)vec, &incx);
# elif defined (USE_ACML)
sscal (n, alpha, vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_sscal (n, alpha, vec, incx);
# else
cblas_sscal (n, alpha, vec, incx);
# endif
}
void scale (double *vec, const double alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
dscal (&n, (double *)&alpha, (double *)vec, &incx);
# elif defined (USE_ESSL)
dscal (n, alpha, vec, incx);
# elif defined (USE_INTEL_MKL)
dscal (&n, const_cast<double *>(&alpha), (double *)vec, &incx);
# elif defined (USE_ACML)
dscal (n, alpha, vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_dscal (n, alpha, vec, incx);
# else
cblas_dscal (n, alpha, vec, incx);
# endif
}
void scale (SxComplex8 *vec, const SxComplex8 &alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
cscal (&n, (complex8_t *)&alpha, (complex8_t *)vec, &incx);
# elif defined (USE_ESSL)
const complex<float> alphaTmp (alpha.re, alpha.im);
cscal (n, alphaTmp, (complex<float> *)vec, incx);
# elif defined (USE_INTEL_MKL)
cscal (&n, (MKL_Complex8 *)const_cast<SxComplex8*>(&alpha),
(MKL_Complex8 *)vec, &incx);
# elif defined (USE_ACML)
cscal (n, (complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_cscal (n, (float*)&alpha, (float*)vec, incx);
# else
cblas_cscal (n, &alpha, vec, incx);
# endif
}
void scale (SxComplex16 *vec, const SxComplex16 &alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
zscal (&n, (complex16_t *)&alpha, (complex16_t *)vec, &incx);
# elif defined (USE_ESSL)
const complex<double> alphaTmp (alpha.re, alpha.im);
zscal (n, alphaTmp, (complex<double> *)vec, incx);
# elif defined (USE_INTEL_MKL)
zscal (&n, (MKL_Complex16 *)const_cast<SxComplex16*>(&alpha),
(MKL_Complex16 *)vec, &incx);
# elif defined (USE_ACML)
zscal (n, (doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_zscal (n, (double*)&alpha, (double*)vec, incx);
# else
cblas_zscal (n, &alpha, vec, incx);
# endif
}
//------------------------------------------------------------------------------
// Y += a*X
//------------------------------------------------------------------------------
void axpy (float *yOut, const float &alpha, const float *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
saxpy (&n, (float *)&alpha,
(float *)xIn, &incx, (float *)yOut, &incx);
# elif defined (USE_ESSL)
saxpy (n, a,
(float *)xIn, incx, (float *)yOut, incx);
# elif defined (USE_INTEL_MKL)
saxpy (&n, const_cast<float *>(&alpha),
const_cast<float *>(xIn), &incx, yOut, &incx);
# elif defined (USE_ACML)
saxpy (n, alpha, (float *)const_cast<float *>(xIn),
incx, (float *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_saxpy (n, alpha, const_cast<float*>(xIn), incx, yOut, incx);
# else
cblas_saxpy (n, alpha, xIn, incx, yOut, incx);
# endif
}
void axpy (double *yOut, const double &alpha, const double *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
daxpy (&n, (double *)&alpha,
(double *)xIn, &incx, (double *)yOut, &incx);
# elif defined (USE_ESSL)
daxpy (n, a,
(double *)xIn, incx, (double *)yOut, incx);
# elif defined (USE_INTEL_MKL)
daxpy (&n, const_cast<double *>(&alpha),
const_cast<double *>(xIn), &incx, (double *)yOut, &incx);
# elif defined (USE_ACML)
daxpy (n, alpha, (double *)const_cast<double *>(xIn),
incx, (double *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_daxpy (n, alpha, const_cast<double*>(xIn), incx, yOut, incx);
# else
cblas_daxpy (n, alpha, xIn, incx, yOut, incx);
# endif
}
void axpy (SxComplex8 *yOut,
const SxComplex8 &alpha, const SxComplex8 *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
caxpy (&n, (complex8_t *)&alpha,
(complex8_t *)xIn, &incx, (complex8_t *)yOut, &incx);
# elif defined (USE_ESSL)
const complex<double> alphaTmp (alpha.re, alpha.im);
caxpy (n, alphaTmp,
(complex<float> *)xIn, incx, (complex<float> *)yOut, incx);
# elif defined (USE_INTEL_MKL)
caxpy (&n, (MKL_Complex8 *)const_cast<SxComplex8 *>(&alpha),
(MKL_Complex8 *)const_cast<SxComplex8 *>(xIn), &incx,
(MKL_Complex8 *)yOut, &incx);
# elif defined (USE_ACML)
caxpy (n, (complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)const_cast<SxComplex8 *>(xIn), incx,
(complex *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_caxpy (n, (float*)&alpha, (float*)xIn, incx, (float*)yOut, incx);
# else
cblas_caxpy (n, &alpha, xIn, incx, yOut, incx);
# endif
}
void axpy (SxComplex16 *yOut,
const SxComplex16 &alpha, const SxComplex16 *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
zaxpy (&n, (complex16_t *)&alpha,
(complex16_t *)xIn, &incx, (complex16_t *)yOut, &incx);
# elif defined (USE_ESSL)
const complex<double> alphaTmp (alpha.re, alpha.im);
zaxpy (n, alphaTmp,
(complex<double> *)xIn, incx, (complex<double> *)yOut, incx);
# elif defined (USE_INTEL_MKL)
zaxpy (&n, (MKL_Complex16 *)const_cast<SxComplex16 *>(&alpha),
(MKL_Complex16 *)const_cast<SxComplex16 *>(xIn), &incx,
(MKL_Complex16 *)yOut, &incx);
# elif defined (USE_ACML)
zaxpy (n, (doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)const_cast<SxComplex16 *>(xIn),
incx, (doublecomplex *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_zaxpy (n, (double*)&alpha, (double*)xIn, incx, (double*)yOut, incx);
# else
cblas_zaxpy (n, &alpha, xIn, incx, yOut, incx);
# endif
}
//------------------------------------------------------------------------------
// scalar product
//------------------------------------------------------------------------------
float scalarProduct (const float *aVec, const float *bVec, int n)
{
const float *aPtr = aVec;
const float *bPtr = bVec;
float res = 0.;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += *aPtr * *bPtr;
return res;
}
double scalarProduct (const double *aVec, const double *bVec, int n)
{
const double *aPtr = aVec;
const double *bPtr = bVec;
double res = 0;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += *aPtr * *bPtr;
return res;
}
SxComplex8 scalarProduct (const SxComplex8 *aVec, const SxComplex8 *bVec, int n)
{
const SxComplex8 *aPtr = aVec;
const SxComplex8 *bPtr = bVec;
SxComplex8 res = (SxComplex8)0.;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += aPtr->conj() * *bPtr;
return res;
}
SxComplex16 scalarProduct (const SxComplex16 *aVec, const SxComplex16 *bVec, int n)
{
const SxComplex16 *aPtr = aVec;
const SxComplex16 *bPtr = bVec;
SxComplex16 res = (SxComplex8)0.;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += aPtr->conj() * *bPtr;
return res;
}
//------------------------------------------------------------------------------
// general matrix-matrix multiplication
//------------------------------------------------------------------------------
void matmult (float *resMat, const float *aMat, const float *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
float alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
char noTrans = 'N';
sgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
&alpha, (float *)aMat, &aMatRows,
(float *)bMat, &aMatCols, &beta, (float *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
sgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
sgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols,
&alpha, const_cast<float *>(aMat), &aMatRows,
const_cast<float *>(bMat), &aMatCols, &beta, resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
sgemm (noTrans, noTrans, aMatRows, bMatCols, aMatCols,
alpha, const_cast<float *>(aMat), aMatRows,
const_cast<float *>(bMat), aMatCols, beta, resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_sgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, const_cast<float*>(aMat), aMatRows,
const_cast<float*>(bMat), aMatCols, beta, resMat,
aMatRows);
# else
cblas_sgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# endif
}
void matmult (double *resMat, const double *aMat, const double *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
double alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
char noTrans = 'N';
dgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
&alpha, (double *)aMat, &aMatRows,
(double *)bMat, &aMatCols, &beta, (double *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
dgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
dgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
&alpha, const_cast<double *>(aMat), &aMatRows,
const_cast<double *>(bMat), &aMatCols, &beta, resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
dgemm (noTrans, noTrans,
aMatRows, bMatCols, aMatCols,
alpha, const_cast<double *>(aMat), aMatRows,
const_cast<double *>(bMat), aMatCols, beta, resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_dgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, const_cast<double*>(aMat), aMatRows,
const_cast<double*>(bMat), aMatCols, beta, resMat, aMatRows);
# else
cblas_dgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# endif
}
void matmult (SxComplex8 *resMat,
const SxComplex8 *aMat, const SxComplex8 *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
SxComplex8 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
char noTrans = 'N';
cgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
(complex8_t *)&alpha, (complex8_t *)aMat, &aMatRows,
(complex8_t *)bMat, &aMatCols, (complex8_t *)&beta,
(complex8_t *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
complex<float> alphaT (alpha.re, alpha.im);
complex<float> betaT (beta.re, beta.im);
cgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alphaT, (complex<float> *)aMat, aMatRows,
(complex<float> *)bMat, aMatCols, betaT,
(complex<float> *)resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
cgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols,
(MKL_Complex8 *)&alpha,
(MKL_Complex8 *)const_cast<SxComplex8 *>(aMat), &aMatRows,
(MKL_Complex8 *)const_cast<SxComplex8 *>(bMat), &aMatCols,
(MKL_Complex8 *)&beta,
(MKL_Complex8 *)resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
cgemm (noTrans, noTrans,
aMatRows, bMatCols, aMatCols,
(complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)const_cast<SxComplex8 *>(aMat), aMatRows,
(complex *)const_cast<SxComplex8 *>(bMat), aMatCols,
(complex *)const_cast<SxComplex8 *>(&beta),
(complex *)resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_cgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
(float*)&alpha, (float*)aMat, aMatRows,
(float*)bMat, aMatCols, (float*)&beta,
(float*)resMat, aMatRows);
# else
cblas_cgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
&alpha, aMat, aMatRows,
bMat, aMatCols, &beta, resMat, aMatRows);
# endif
}
void matmult (SxComplex16 *resMat,
const SxComplex16 *aMat, const SxComplex16 *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
SxComplex16 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
char noTrans = 'N';
zgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
(complex16_t *)&alpha, (complex16_t *)aMat, &aMatRows,
(complex16_t *)bMat, &aMatCols, (complex16_t *)&beta,
(complex16_t *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
complex<double> alphaT (alpha.re, alpha.im);
complex<double> betaT (beta.re, beta.im);
zgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alphaT, (complex<double> *)aMat, aMatRows,
(complex<double> *)bMat, aMatCols, betaT,
(complex<double> *)resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
zgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols,
(MKL_Complex16 *)&alpha,
(MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows,
(MKL_Complex16 *)const_cast<SxComplex16 *>(bMat), &aMatCols,
(MKL_Complex16 *)&beta, (MKL_Complex16 *)resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
zgemm (noTrans, noTrans,
aMatRows, bMatCols, aMatCols,
(doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)const_cast<SxComplex16 *>(aMat), aMatRows,
(doublecomplex *)const_cast<SxComplex16 *>(bMat), aMatCols,
(doublecomplex *)const_cast<SxComplex16 *>(&beta),
(doublecomplex *)resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasNoTrans, aMatRows, aMatCols,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, 1, (double*)&beta, (double*)resMat, 1);
} else if (aMatRows == 1) {
cblas_zgemv (CblasColMajor, CblasTrans, aMatCols, bMatCols,
(double*)&alpha, (double*)bMat, aMatCols,
(double*)aMat, 1, (double*)&beta, (double*)resMat, 1);
} else {
cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, aMatCols, (double*)&beta, (double*)resMat,
aMatRows);
}
# else
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasNoTrans, aMatRows, aMatCols,
&alpha, aMat, aMatRows,
bMat, 1, &beta, resMat, 1);
} else if (aMatRows == 1) {
cblas_zgemv (CblasColMajor, CblasTrans, aMatCols, bMatCols,
&alpha, bMat, aMatCols,
aMat, 1, &beta, resMat, 1);
} else {
#if defined(USE_OPENMP) && defined(USE_ATLAS)
if (aMatRows > 1024) {
# pragma omp parallel
{
int nThreads = omp_get_num_threads ();
int nb = aMatRows / nThreads;
// distribute remaining elements over all threads
if (nb * nThreads < aMatRows) nb++;
int offset = omp_get_thread_num () * nb;
// reduce nb for last thread
if (offset + nb > aMatRows) nb = aMatRows - offset;
cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
nb, bMatCols, aMatCols,
&alpha, aMat + offset, aMatRows,
bMat, aMatCols, &beta, resMat + offset, aMatRows);
}
} else // no openMP parallelism ...
#endif
cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
&alpha, aMat, aMatRows,
bMat, aMatCols, &beta, resMat, aMatRows);
}
# endif
}
//------------------------------------------------------------------------------
// overlap matrices
//------------------------------------------------------------------------------
void matovlp (float *resMat,
const float *aMat, const float *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
float alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
sgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, (float *)aMat, &aMatRows,
(float *)bMat, &bMatRows, &beta,
(float *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
sgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
// SX_EXIT; // not tested
// change by khr
char noTrans = 'N', conjTrans = 'C';
sgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, const_cast<float *>(aMat), &aMatRows,
const_cast<float *>(bMat), &bMatRows, &beta, resMat, &aMatCols);
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
sgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<float *>(aMat), aMatRows,
const_cast<float *>(bMat), bMatRows,
beta, resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, const_cast<float*>(aMat), aMatRows,
const_cast<float*>(bMat), 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, const_cast<float*>(bMat), bMatRows,
const_cast<float*>(aMat), 1, beta, resMat, 1);
} else {
cblas_sgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<float *>(aMat), aMatRows,
const_cast<float*>(bMat), bMatRows, beta, resMat, aMatCols);
}
# else
if (bMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, aMat, aMatRows,
bMat, 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, bMat, bMatRows,
aMat, 1, beta, resMat, 1);
} else {
cblas_sgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
}
# endif
}
void matovlp (double *resMat,
const double *aMat, const double *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
double alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
dgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, (double *)aMat, &aMatRows,
(double *)bMat, &bMatRows, &beta,
(double *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
dgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
// SX_EXIT; // not tested
// change by khr
char noTrans = 'N', conjTrans = 'C';
dgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, const_cast<double *>(aMat), &aMatRows,
const_cast<double *>(bMat), &bMatRows, &beta, resMat, &aMatCols);
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
dgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<double *>(aMat), aMatRows,
const_cast<double *>(bMat), bMatRows,
beta, resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, const_cast<double*>(aMat), aMatRows,
const_cast<double*>(bMat), 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, const_cast<double*>(bMat), bMatRows,
const_cast<double*>(aMat), 1, beta, resMat, 1);
} else {
cblas_dgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<double*>(aMat), aMatRows,
const_cast<double*>(bMat), bMatRows, beta, resMat, aMatCols);
}
# else
if (bMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, aMat, aMatRows,
bMat, 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, bMat, bMatRows,
aMat, 1, beta, resMat, 1);
} else {
cblas_dgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
}
# endif
}
void matovlp (SxComplex8 *resMat,
const SxComplex8 *aMat, const SxComplex8 *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
SxComplex8 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
cgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
(complex8_t *)&alpha, (complex8_t *)aMat, &aMatRows,
(complex8_t *)bMat, &bMatRows, (complex8_t *)&beta,
(complex8_t *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
complex<float> alphaT (alpha.re, alpha.im);
complex<float> betaT (beta.re, beta.im);
cgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alphaT, (complex<float> *)aMat, aMatRows,
(complex<float> *)bMat, bMatRows, betaT,
(complex<float> *)resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N', conjTrans = 'C';
cgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize,
(MKL_Complex8 *)&alpha,
(MKL_Complex8 *)const_cast<SxComplex8 *>(aMat), &aMatRows,
(MKL_Complex8 *)const_cast<SxComplex8 *>(bMat), &bMatRows,
(MKL_Complex8 *)&beta, (MKL_Complex8 *)resMat, &aMatCols);
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
cgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
(complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)const_cast<SxComplex8 *>(aMat), aMatRows,
(complex *)const_cast<SxComplex8 *>(bMat), bMatRows,
(complex *)const_cast<SxComplex8 *>(&beta),
(complex *)resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
(float*)&alpha, (float*)aMat, aMatRows,
(float*)bMat, 1, (float*)&beta, (float*)resMat, 1);
} else if (aMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
(float*)&alpha, (float*)bMat, bMatRows,
(float*)aMat, 1, (float*)&beta, (float*)resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
cblas_cgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
(float*)&alpha, (float*)aMat, aMatRows,
(float*)bMat, bMatRows, (float*)&beta, (float*)resMat,
aMatCols);
}
# else
if (bMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
&alpha, aMat, aMatRows,
bMat, 1, &beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
&alpha, bMat, bMatRows,
aMat, 1, &beta, resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
cblas_cgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
&alpha, aMat, aMatRows,
bMat, bMatRows, &beta, resMat, aMatCols);
}
# endif
}
/*
#include <SxTimer.h>
enum BlasLibTimer { Matovlp };
REGISTER_TIMERS (BlasLibTimer)
{
regTimer (Matovlp, "matovlp");
}
*/
void matovlp (SxComplex16 *resMat,
const SxComplex16 *aMat, const SxComplex16 *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
SxComplex16 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
zgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
(complex16_t *)&alpha, (complex16_t *)aMat, &aMatRows,
(complex16_t *)bMat, &bMatRows, (complex16_t *)&beta,
(complex16_t *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
complex<double> alphaT (alpha.re, alpha.im);
complex<double> betaT (beta.re, beta.im);
zgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alphaT, (complex<double> *)aMat, aMatRows,
(complex<double> *)bMat, bMatRows, betaT,
(complex<double> *)resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N', conjTrans = 'C';
if (aMat == bMat && aMatRows == bMatRows && aMatCols == bMatCols) {
// special case: A.overlap (A) => use Hermitean routine ...
char uplo = 'U';
zherk (&uplo, &conjTrans, &aMatCols, &sumSize,
&alpha.re,
(MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows,
&beta.re, (MKL_Complex16 *)resMat, &aMatCols);
// ... and copy upper half to lower half
for (int i = 0; i < aMatCols; i++)
for (int j = 0; j < i; j++)
resMat[i + aMatCols * j] = resMat[j + aMatCols * i].conj ();
} else {
zgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize,
(MKL_Complex16 *)&alpha,
(MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows,
(MKL_Complex16 *)const_cast<SxComplex16 *>(bMat), &bMatRows,
(MKL_Complex16 *)&beta, (MKL_Complex16 *)resMat, &aMatCols);
}
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
zgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
(doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)const_cast<SxComplex16 *>(aMat), aMatRows,
(doublecomplex *)const_cast<SxComplex16 *>(bMat), bMatRows,
(doublecomplex *)const_cast<SxComplex16 *>(&beta),
(doublecomplex *)resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, 1, (double*)&beta, (double*)resMat, 1);
} else if (aMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
(double*)&alpha, (double*)bMat, bMatRows,
(double*)aMat, 1, (double*)&beta, (double*)resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, bMatRows, (double*)&beta,
(double*)resMat, aMatCols);
}
# else
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
&alpha, aMat, aMatRows,
bMat, 1, &beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
&alpha, bMat, bMatRows,
aMat, 1, &beta, resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
#ifndef USE_OPENMP
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
&alpha, aMat, aMatRows,
bMat, bMatRows, &beta, resMat, aMatCols);
#else
//CLOCK (Matovlp);
int nb = 128;
int np = sumSize / nb;
// --- compute contribution from rest elements
if (sumSize > nb * np) {
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize - nb * np,
&alpha, aMat + nb * np, aMatRows,
bMat + nb * np, bMatRows, &beta, resMat, aMatCols);
} else {
for (int i = 0; i < aMatCols * bMatCols; ++i)
resMat[i].re = resMat[i].im = 0.;
}
# pragma omp parallel
{
SxComplex16 *part = NULL;
// --- compute partial results (in parallel)
# pragma omp for
for (int ip = 0; ip < np; ip++) {
if (!part) {
part = new SxComplex16[aMatCols * bMatCols];
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, nb,
&alpha, aMat + ip * nb, aMatRows,
bMat + ip * nb, bMatRows, &beta, part, aMatCols);
} else {
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, nb,
&alpha, aMat + ip * nb, aMatRows,
bMat + ip * nb, bMatRows, &alpha, part, aMatCols);
}
}
// --- sum partial results
if (part) {
# pragma omp critical
cblas_zaxpy (aMatCols * bMatCols, &alpha, part, 1, resMat, 1);
delete [] part;
}
}
# endif
}
# endif
}
//------------------------------------------------------------------------------
// Matrix decompositions
//------------------------------------------------------------------------------
void cholesky (float *resMat, enum UPLO uplo, float * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
spotrf (&uploChar, &n, (float *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
spotrf (&uploChar, n, resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
spotrf (&uploChar, &n, resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
spotrf (uploChar, n, resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
spotrf_ (&uploChar, &rank, (real *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void cholesky (double *resMat, enum UPLO uplo, double * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
dpotrf (&uploChar, &n, (double *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
dpotrf (&uploChar, n, resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
dpotrf (&uploChar, &n, resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
dpotrf (uploChar, n, resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
dpotrf_ (&uploChar, &rank, (doublereal *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void cholesky (SxComplex8 *resMat, enum UPLO uplo,
SxComplex8 * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
cpotrf (&uploChar, &n, (complex8_t *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
cpotrf (&uploChar, n, (complex<float> *)resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
cpotrf (&uploChar, &n, (MKL_Complex8 *)resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
cpotrf (uploChar, n, (complex *)resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
cpotrf_ (&uploChar, &rank, (complex *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void cholesky (SxComplex16 *resMat, enum UPLO uplo,
SxComplex16 * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
zpotrf (&uploChar, &n, (complex16_t *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
zpotrf (&uploChar, n, (complex<double> *)resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
zpotrf(&uploChar, &n, (MKL_Complex16 *)resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
zpotrf(uploChar, n, (doublecomplex *)resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
zpotrf_ (&uploChar, &rank, (doublecomplex *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void singularValueDecomp (float *mat, int nRows, int nCols,
float *vals,
float *left,
float *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
int ldvt = zeroSpace ? nCols : minMN;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// workspace query:
int *iwork = new int[8 * minMN];
int err = 0;
int lwork = -1;
float optwork;
sgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (int)optwork;
float* work = new float[lwork];
// --- actual compute
sgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer *iwork = new integer[8 * minMN];
integer lwork = -1;
integer err = 0;
// workspace query:
float optwork;
integer nr = nRows, nc = nCols, ldvt_ = ldvt;
sgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork;
float* work = new float[lwork];
// --- actual compute
sgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
delete[] iwork;
}
void singularValueDecomp (double *mat, int nRows, int nCols,
double *vals,
double *left,
double *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
int ldvt = zeroSpace ? nCols : minMN;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// workspace query:
int err = 0;
int *iwork = new int[8 * minMN];
int lwork = -1;
double optwork;
dgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = int(lround(optwork));
double* work = new double[lwork];
// --- actual compute
dgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer err = 0;
integer lwork = -1;
integer *iwork = new integer[8 * minMN];
// workspace query:
double optwork;
integer nr = nRows, nc = nCols, ldvt_ = ldvt;
dgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork;
double* work = new double[lwork];
// --- actual compute
dgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
delete[] iwork;
}
void singularValueDecomp (SxComplex8 *mat, int nRows, int nCols,
float *vals,
SxComplex8 *left,
SxComplex8 *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
int ldvt = zeroSpace ? nCols : minMN;
int lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
int err = 0;
int lwork = -1;
float *rwork = new float[lrwork];
int *iwork = new int[8 * minMN];
// workspace query:
MKL_Complex8 optwork;
cgesdd(&jobz, &nRows, &nCols, (MKL_Complex8*)mat, &nRows,
vals, (MKL_Complex8*)left, &nRows, (MKL_Complex8*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = int(lround(optwork.real));
MKL_Complex8* work = new MKL_Complex8[lwork];
// --- actual compute
cgesdd(&jobz, &nRows, &nCols, (MKL_Complex8*)mat, &nRows,
vals, (MKL_Complex8*)left, &nRows, (MKL_Complex8*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer ldvt = zeroSpace ? nCols : minMN;
integer lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
integer err = 0;
integer lwork = -1;
float *rwork = new float[lrwork];
integer *iwork = new integer[8 * minMN];
// workspace query:
integer nr = nRows, nc = nCols;
complex optwork;
SX_EXIT;
/* missing prototype
cgesdd_(&jobz, &nr, &nc, (complex *)mat, &nr,
vals, (complex*)left, &nr, (complex*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
*/
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork.r;
complex* work = new complex[lwork];
// --- actual compute
SX_EXIT;
/* missing prototype
cgesdd_(&jobz, &nr, &nc, (complex *)mat, &nr,
vals, (complex*)left, &nr, (complex*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
*/
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
}
void singularValueDecomp (SxComplex16 *mat, int nRows, int nCols,
double *vals,
SxComplex16 *left,
SxComplex16 *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
int ldvt = zeroSpace ? nCols : minMN;
int lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
int err = 0;
int lwork = -1;
double *rwork = new double[lrwork];
int *iwork = new int[8 * minMN];
// workspace query:
MKL_Complex16 optwork;
zgesdd(&jobz, &nRows, &nCols, (MKL_Complex16*)mat, &nRows,
vals, (MKL_Complex16*)left, &nRows, (MKL_Complex16*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = int(lround(optwork.real));
MKL_Complex16* work = new MKL_Complex16[lwork];
// --- actual compute
zgesdd(&jobz, &nRows, &nCols, (MKL_Complex16*)mat, &nRows,
vals, (MKL_Complex16*)left, &nRows, (MKL_Complex16*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer ldvt = zeroSpace ? nCols : minMN;
integer lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
integer err = 0;
integer lwork = -1;
double *rwork = new double[lrwork];
integer *iwork = new integer[8 * minMN];
// workspace query:
doublecomplex optwork;
integer nr = nRows, nc = nCols;
SX_EXIT;
/* missing prototype:
zgesdd_(&jobz, &nr, &nc, (doublecomplex *)mat, &nr,
vals, (doublecomplex*)left, &nr, (doublecomplex*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
*/
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork.r;
doublecomplex* work = new doublecomplex[lwork];
// --- actual compute
/* missing prototype:
zgesdd_(&jobz, &nr, &nc, (doublecomplex *)mat, &nr,
vals, (doublecomplex*)left, &nr, (doublecomplex*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
*/
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
}
//------------------------------------------------------------------------------
// Matrix inversion
//------------------------------------------------------------------------------
void matInverse (float *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (&nRows, &nCols, (float *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (nRows, nCols, mat, r, pivots, err);
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (&nRows, &nCols, mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (nRows, nCols, mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
sgetrf_ (&r, &c, (real *)mat, &r, pivots, &err);
# endif
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in SGETRF: " << err <<std::endl;
delete [] pivots;
SX_EXIT;
}
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
float *work = new float [lWork];
sgetri (&r, (float *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
float *work = new float [lWork];
sgetri (r, mat, r, pivots, work, lWork, err);
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
float *work = new float [lWork];
sgetri (&r, mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
float *work = NULL; // ACML doesn't use work
sgetri (r, mat, r, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
real *work = new real [lWork];
sgetri_ (&r, (real *)mat, &r, pivots, work, &lWork, &err);
# endif
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in SGETRI: " << err <<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
}
void matInverse (double *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (&nRows, &nCols, (double *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (nRows, nCols, mat, r, pivots, err);
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (&nRows, &nCols, mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (nRows, nCols, mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
dgetrf_ (&r, &c, (doublereal *)mat, &r, pivots, &err);
# endif
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in DGETRF: " << err <<std::endl;
delete [] pivots;
SX_EXIT;
}
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
double *work = new double [lWork];
dgetri (&nRows, (double *)mat, &nRows, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
double *work = new double [lWork];
dgetri (nRows, mat, nRows, pivots, work, lWork, err);
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
double *work = new double [lWork];
dgetri (&nRows, mat, &nRows, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
double *work = NULL; // ACML doesn't use work
dgetri (nRows, mat, nRows, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
doublereal *work = new doublereal [lWork];
dgetri_ (&r, (doublereal *)mat, &r, pivots, work, &lWork, &err);
# endif
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in DGETRI: " << err <<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
}
void matInverse (SxComplex8 *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
cgetrf (&r, &c, (complex8_t *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r, c, err=0;
// map complex inversion to real inversion
// +----+----+ +-----+-----+
// +----+ | Re |-Im | | re1 | im1 |
// |cmlx| => +----+----+ = +-----+-----+
// +----+ | Im | Re | | im2 | re2 |
// +----+----+ +-----+-----+
SxComplex8 *matPtr = mat;
float *realMat = new float [ (2*nRows)*(2*nCols) ];
float *re1Ptr = realMat;
float *im1Ptr = &realMat[nCols];
float *im2Ptr = &realMat[2*nRows*nCols];
float *re2Ptr = &realMat[2*nRows*nCols + nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, re2Ptr+=nCols,
im1Ptr+=nCols, im2Ptr+=nCols)
{
for (c=0; c<nCols; c++, matPtr++) {
*re1Ptr++ = *re2Ptr++ = matPtr->re;
*im1Ptr++ = -matPtr->im;
*im2Ptr++ = matPtr->im;
}
}
// --- compute inverse of real helper matrix
matInverse (realMat, 2*nRows, 2*nCols);
// construct complex result
// +----+----+ +-----+-----+
// | Re | * | | re1 | * | +----+
// +----+----+ = +-----+-----+ => |cmlx|
// | Im | * | | im2 | * | +----+
// +----+----+ +-----+-----+
matPtr = mat;
re1Ptr = realMat;
im2Ptr = &realMat[2*nRows*nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, im2Ptr+=nCols) {
for (c=0; c<nCols; c++, matPtr++) {
matPtr->re = *re1Ptr++;
matPtr->im = *im2Ptr++;
}
}
delete [] realMat;
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
cgetrf (&r, &c, (MKL_Complex8 *)mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
cgetrf (r, c, (complex *)mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
cgetrf_ (&r, &c, (complex *)mat, &r, pivots, &err);
# endif
# ifndef USE_ESSL
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in CGETRF: "<<err<<std::endl;
delete [] pivots;
SX_EXIT;
}
# endif
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
complex8_t *work = new complex8_t [lWork];
cgetri (&r, (complex8_t *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
// empty
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
MKL_Complex8 *work = new MKL_Complex8 [lWork];
cgetri (&r, (MKL_Complex8 *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
complex *work = NULL; // ACML doesn't use work
cgetri (r, (complex *)mat, r, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
complex *work = new complex [lWork];
cgetri_ (&r, (complex *)mat, &r, pivots, work, &lWork, &err);
# endif
# ifndef USE_ESSL
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in CGETRI: "<<err<<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
# endif
}
void matInverse (SxComplex16 *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
zgetrf (&r, &c, (complex16_t *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r, c, err=0;
// map complex inversion to real inversion
// +----+----+ +-----+-----+
// +----+ | Re |-Im | | re1 | im1 |
// |cmlx| => +----+----+ = +-----+-----+
// +----+ | Im | Re | | im2 | re2 |
// +----+----+ +-----+-----+
SxComplex16 *matPtr = mat;
double *realMat = new double [ (2*nRows)*(2*nCols) ];
double *re1Ptr = realMat;
double *im1Ptr = &realMat[nCols];
double *im2Ptr = &realMat[2*nRows*nCols];
double *re2Ptr = &realMat[2*nRows*nCols + nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, re2Ptr+=nCols,
im1Ptr+=nCols, im2Ptr+=nCols)
{
for (c=0; c<nCols; c++, matPtr++) {
*re1Ptr++ = *re2Ptr++ = matPtr->re;
*im1Ptr++ = -matPtr->im;
*im2Ptr++ = matPtr->im;
}
}
// --- compute inverse of real helper matrix
matInverse (realMat, 2*nRows, 2*nCols);
// construct complex result
// +----+----+ +-----+-----+
// | Re | * | | re1 | * | +----+
// +----+----+ = +-----+-----+ => |cmlx|
// | Im | * | | im2 | * | +----+
// +----+----+ +-----+-----+
matPtr = mat;
re1Ptr = realMat;
im2Ptr = &realMat[2*nRows*nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, im2Ptr+=nCols) {
for (c=0; c<nCols; c++, matPtr++) {
matPtr->re = *re1Ptr++;
matPtr->im = *im2Ptr++;
}
}
delete [] realMat;
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
zgetrf (&r, &c, (MKL_Complex16 *)mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
zgetrf (r, c, (doublecomplex *)mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
zgetrf_ (&r, &c, (doublecomplex *)mat, &r, pivots, &err);
# endif
# ifndef USE_ESSL
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in ZGETRF: "<<err<<std::endl;
delete [] pivots;
SX_EXIT;
}
# endif
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
complex16_t *work = new complex16_t [lWork];
zgetri (&r, (complex16_t *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
// empty
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
MKL_Complex16 *work = new MKL_Complex16 [lWork];
zgetri (&r, (MKL_Complex16 *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
doublecomplex *work = NULL; // ACML doesn't use work
zgetri (r, (doublecomplex *)mat, r, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
doublecomplex *work = new doublecomplex [lWork];
zgetri_ (&r, (doublecomplex *)mat, &r, pivots, work, &lWork, &err);
# endif
# ifndef USE_ESSL
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in ZGETRI: "<<err<<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
# endif
}
void matInverseTri (float * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/)
{
SX_EXIT; // not yet implemented
}
void matInverseTri (double *mat, int nRows, enum UPLO uplo)
{
char uploChar = (uplo == UpperRight ? 'U' : 'L');
// --- (1) Factorization: A = U*D*U^t
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined ( USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// int err = 0;
// SX_EXIT; // not yet implemented
// change by khr
int r = nRows, err = 0;
int *pivots = new int[r];
dsptrf (&uploChar, &r, mat, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, err = 0;
int *pivots = new int[r];
dsptrf (uploChar, r, mat, pivots, &err);
# else
integer r = (integer)nRows, err = 0;
integer *pivots = new integer[r];
dsptrf_ (&uploChar, &r, (doublereal *)mat, pivots, &err);
# endif
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverseTri: Error in DSPTRF: "
<< err << std::endl;
SX_EXIT;
}
// --- (2) Inverse of A
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// double *work = NULL, *pivots=NULL;
// SX_EXIT; // not yet implemented
// change by khr
double *work = new double [r];
dsptri (&uploChar, &r, mat, pivots, work, &err);
# elif defined (USE_ACML)
double *work = NULL; // ACML doesn't use work
dsptri (uploChar, r, mat, pivots, &err);
# else
doublereal *work = new doublereal [r];
dsptri_ (&uploChar, &r, (doublereal *)mat, pivots, work, &err);
# endif
# ifndef USE_ESSL
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverseTri: Error in DSPTRI: "
<< err << std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
# endif
}
void matInverseTri (SxComplex8 * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/)
{
SX_EXIT; // not yet implemented
}
void matInverseTri (SxComplex16 * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/)
{
SX_EXIT; // not yet implemented
}
//------------------------------------------------------------------------------
// Linear equation solver (least square based)
//------------------------------------------------------------------------------
void solveLinEq (float *mat, int nRows, int nCols, float *b, int bCols)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
int iopt = 2; //compute singulare Values, V and U^TB
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
char transa = 'N';
int naux = 0; //ESSL choose size of work array dynamically
float *aux = NULL; //workarray is ignored
int info;
float *s = new float [n];
float *x = new float [n*nrhs];
float tau = 1e-10; // error tolerance for zero
sgesvf(iopt,mat,lda,b,ldb,nrhs,s,m,n,aux,naux);
sgesvs (mat,n,b,n,nrhs,s,x,n,m,n,tau);
// results are now in x; copy to b
for(int i = 0; i < n*nrhs; i++) {
b[i] = x[i];
}
delete [] s; delete [] x;
//TODO TEST
SX_EXIT;
# elif defined (USE_INTEL_MKL)
// for ilaenv
MKL_INT iSpec = 9;
char *name = const_cast<char*>("SGELSD");
char *opts = const_cast<char*>(" ");
MKL_INT n1 = 0;
MKL_INT n2 = 0;
MKL_INT n3 = 0;
MKL_INT n4 = 0;
// for dgelsd
MKL_INT m = nRows;
MKL_INT n = nCols;
MKL_INT minmn = n < m ? n : m;
MKL_INT nrhs = bCols;
MKL_INT lda = m;
MKL_INT ldb = m;
float *s = new float [minmn];
float rcond = -1.;
MKL_INT rank;
MKL_INT SMLSIZ = ilaenv(&iSpec,name,opts,&n1,&n2,&n3,&n4);
MKL_INT logVal = MKL_INT(log( 1.0*n/(SMLSIZ+1))/log(2.0)) + 1;
MKL_INT NLVL = 0 < logVal ? logVal : 0;
MKL_INT lwork = -1;
float autolwork;
MKL_INT liwork = 3 * minmn * NLVL + 11 * minmn;
MKL_INT *iwork = new MKL_INT [liwork];
MKL_INT info;
// determine optimal lwork
// dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
sgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = MKL_INT(autolwork+0.5);
float *work = new float [lwork];
sgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
//TODO TEST
SX_EXIT;
# elif defined (USE_ACML)
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
int minmn = n < m ? n : m;
float *s = new float [minmn];
float rcond = -1.;
int rank;
int info;
sgelsd (m,n,nrhs,mat,lda,b,ldb,s,rcond,&rank,&info);
delete [] s;
//TODO TEST
SX_EXIT;
# else
// for ilaenv
integer iSpec = 9;
char *name = const_cast<char*>("SGELSD");
char *opts = const_cast<char*>(" ");
integer n1 = 0;
integer n2 = 0;
integer n3 = 0;
integer n4 = 0;
ftnlen lname = 6;
ftnlen lopts = 1;
// for sgelsd
integer m = nRows;
integer n = nCols;
integer minmn = n < m ? n : m;
integer nrhs = bCols;
integer lda = m;
integer ldb = m;
float *s = new float [minmn];
float rcond = -1.;
integer rank;
#ifdef MACOSX
# if ( DIST_VERSION_L >= 1070L )
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4);
# else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
# endif /* DIST_VERSION_L */
#else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
#endif /* MACOSX */
integer logVal = integer(log( double(n)/double(SMLSIZ+1))/log(2.0)) + 1;
integer NLVL = 0 < logVal ? logVal : 0;
integer lwork = -1;
float autolwork;
integer liwork = 3 * minmn * NLVL + 11 * minmn;
integer *iwork = new integer [liwork];
integer info;
// determine optimal lwork
sgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = integer(autolwork+0.5);
float *work = new float [lwork];
sgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
# endif
}
void solveLinEq (double *mat, int nRows, int nCols, double *b, int bCols)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
int iopt = 2; //compute singulare Values, V and U^TB
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
char transa = 'N';
int naux = 0; //ESSL choose size of work array dynamically
double *aux = NULL; //workarray is ignored
int info;
double *s = new double [n];
double *x = new double [n*nrhs];
double tau = 1e-10; // error tolerance for zero
dgesvf(iopt,mat,lda,b,ldb,nrhs,s,m,n,aux,naux);
dgesvs (mat,n,b,n,nrhs,s,x,n,m,n,tau);
// results are now in x; copy to b
for(int i = 0; i < n*nrhs; i++) {
b[i] = x[i];
}
delete [] s; delete [] x;
//TODO TEST
SX_EXIT;
# elif defined (USE_INTEL_MKL)
// for ilaenv
MKL_INT iSpec = 9;
char *name = const_cast<char*>("DGELSD");
char *opts = const_cast<char*>(" ");
MKL_INT n1 = 0;
MKL_INT n2 = 0;
MKL_INT n3 = 0;
MKL_INT n4 = 0;
// for dgelsd
MKL_INT m = nRows;
MKL_INT n = nCols;
MKL_INT minmn = n < m ? n : m;
MKL_INT nrhs = bCols;
MKL_INT lda = m;
MKL_INT ldb = m;
double *s = new double [minmn];
double rcond = -1.;
MKL_INT rank;
MKL_INT SMLSIZ = ilaenv(&iSpec,name,opts,&n1,&n2,&n3,&n4);
MKL_INT logVal = MKL_INT(log( 1.0*n/(SMLSIZ+1))/log(2.0)) + 1;
MKL_INT NLVL = 0 < logVal ? logVal : 0;
MKL_INT lwork = -1;
double autolwork;
MKL_INT liwork = 3 * minmn * NLVL + 11 * minmn;
MKL_INT *iwork = new MKL_INT [liwork];
MKL_INT info;
// determine optimal lwork
dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = MKL_INT(autolwork+0.5);
double *work = new double [lwork];
dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
# elif defined (USE_ACML)
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
int minmn = n < m ? n : m;
double *s = new double [minmn];
double rcond = -1.;
int rank;
int info;
dgelsd (m,n,nrhs,mat,lda,b,ldb,s,rcond,&rank,&info);
delete [] s;
//TODO TEST
SX_EXIT;
# else
// for ilaenv
integer iSpec = 9;
char *name = const_cast<char*>("DGELSD");
char *opts = const_cast<char*>(" ");
integer n1 = 0;
integer n2 = 0;
integer n3 = 0;
integer n4 = 0;
ftnlen lname = 6;
ftnlen lopts = 1;
// for dgelsd
integer m = nRows;
integer n = nCols;
integer minmn = n < m ? n : m;
integer nrhs = bCols;
integer lda = m;
integer ldb = m;
double *s = new double [minmn];
double rcond = -1.;
integer rank;
#ifdef MACOSX
# if ( DIST_VERSION_L >= 1070L )
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4);
# else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
# endif /* DIST_VERSION_L */
#else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
#endif /* MACOSX */
integer logVal = integer(log( double(n)/double(SMLSIZ+1))/log(2.0)) + 1;
integer NLVL = 0 < logVal ? logVal : 0;
integer lwork = -1;
double autolwork;
integer liwork = 3 * minmn * NLVL + 11 * minmn;
integer *iwork = new integer [liwork];
integer info;
// determine optimal lwork
dgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = integer(autolwork+0.5);
double *work = new double [lwork];
dgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
# endif
}
void solveLinEq (SxComplex8 * /*mat*/, int /*nRows*/, int /*nCols*/,
SxComplex8 * /*b*/, int /*bCols*/)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
//TODO
SX_EXIT;
# elif defined (USE_INTEL_MKL)
//TODO
SX_EXIT;
# elif defined (USE_ACML)
//TODO
SX_EXIT;
# endif
}
void solveLinEq (SxComplex16 * /*mat*/, int /*nRows*/, int /*nCols*/,
SxComplex16 * /*b*/, int /*bCols*/)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
//TODO
SX_EXIT;
# elif defined (USE_INTEL_MKL)
//TODO
SX_EXIT;
# elif defined (USE_ACML)
//TODO
SX_EXIT;
# else
//TODO
SX_EXIT;
# endif
}
//------------------------------------------------------------------------------
// Eigensolver
//------------------------------------------------------------------------------
int matEigensolver (SxComplex8 *eigVals, float *eigVecs,
float *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 4*n : size;
integer workDim = lWork;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
float *work = new float [workDim];
float *epsRe = new float [n], *epsIm = new float [n];
float *eigVecLeft = new float [ldVecLeft];
sgeev (&jobvl, &jobvr,
&rank, (float *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (float *)eigVecs, &rank, work, &lWork, &info, 0, 0);
# elif defined (USE_ESSL)
complex<float> *vecs = new complex<float> [rank*rank];
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
sgeev (iOpt, inMat, rank,
(complex<float> *)eigVals, vecs, rank,
NULL, rank, NULL, 0);
complex<float> *srcPtr = vecs;
float *dstPtr = eigVecs;
int i, len = n*n;
for (i=0; i < len; i++, srcPtr++) {
*dstPtr++ = real(*srcPtr);
}
// --- normalize eigenvectors
float c;
for (i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
delete [] vecs;
return 0;
# elif defined (USE_INTEL_MKL)
float *work = new float [workDim];
float *epsRe = new float [n], *epsIm = new float [n];
float *eigVecLeft = new float [ldVecLeft];
sgeev (&jobvl, &jobvr,
&rank, inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, eigVecs, &rank, work, &lWork, &info);
# elif defined (USE_ACML)
float *work = NULL; // ACML doesn't use work
float *epsRe = new float [n], *epsIm = new float [n];
float *eigVecLeft = new float [ldVecLeft];
sgeev (jobvl, jobvr,
rank, inMat, rank, epsRe, epsIm, eigVecLeft,
ldVecLeft, eigVecs, rank, &info);
# else
real *work = new real [workDim];
real *epsRe = new real[n], *epsIm = new real[n];
real *eigVecLeft = new real [ldVecLeft];
sgeev_ (&jobvl, &jobvr,
&rank, (real *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (real *)eigVecs, &rank, work, &lWork, &info);
# endif
# ifndef USE_ESSL
float *ptr=(float *)eigVals;
float *rePtr=(float *)epsRe, *imPtr=(float *)epsIm;
for (int i=0; i < n; i++) {
*ptr++ = *rePtr++; // eigVals[i].re = epsRe[i];
*ptr++ = *imPtr++; // eigVals[i].im = epsIm[i];
}
delete [] eigVecLeft; delete [] epsIm; delete [] epsRe; delete [] work;
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in SGEEV: " << info << std::endl;
SX_EXIT;
}
return (cmd == OptSize) ? (int)work[0] : 0;
# endif
}
int matEigensolver (SxComplex16 *eigVals, double *eigVecs,
double *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 4*n : size;
integer workDim = lWork;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
double *work = new double [workDim];
double *epsRe = new double[n], *epsIm = new double[n];
double *eigVecLeft = new double [ldVecLeft];
dgeev (&jobvl, &jobvr,
&rank, (double *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (double *)eigVecs, &rank, work, &lWork, &info, 0, 0);
# elif defined (USE_ESSL)
complex<double> *vecs = new complex<double> [rank*rank];
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
dgeev (iOpt, inMat, rank,
(complex<double> *)eigVals, vecs, rank,
NULL, rank, NULL, 0);
complex<double> *srcPtr = vecs;
double *dstPtr = eigVecs;
int i, len = n*n;
for (i=0; i < len; i++, srcPtr++) {
*dstPtr++ = real(*srcPtr);
}
// --- normalize eigenvectors
double c;
for (i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
delete [] vecs;
return 0;
# elif defined (USE_INTEL_MKL)
double *work = new double [workDim];
double *epsRe = new double [n], *epsIm = new double [n];
double *eigVecLeft = new double [ldVecLeft];
dgeev (&jobvl, &jobvr,
&rank, inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, eigVecs, &rank, work, &lWork, &info);
# elif defined (USE_ACML)
double *work = NULL; // ACML doesn't use work
double *epsRe = new double [n], *epsIm = new double [n];
double *eigVecLeft = new double [ldVecLeft];
dgeev (jobvl, jobvr,
rank, inMat, rank, epsRe, epsIm, eigVecLeft,
ldVecLeft, eigVecs, rank, &info);
# else
doublereal *work = new doublereal [workDim];
doublereal *epsRe = new doublereal[n], *epsIm = new doublereal[n];
doublereal *eigVecLeft = new doublereal [ldVecLeft];
dgeev_ (&jobvl, &jobvr,
&rank, (doublereal *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (doublereal *)eigVecs, &rank, work, &lWork, &info);
# endif
# ifndef USE_ESSL
double *ptr=(double *)eigVals;
double *rePtr=(double *)epsRe, *imPtr=(double *)epsIm;
for (int i=0; i < n; i++) {
*ptr++ = *rePtr++; // eigVals[i].re = epsRe[i];
*ptr++ = *imPtr++; // eigVals[i].im = epsIm[i];
}
delete [] eigVecLeft; delete [] epsIm; delete [] epsRe; delete [] work;
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in DGEEV: " << info << std::endl;
SX_EXIT;
}
return (cmd == OptSize) ? (int)work[0] : 0;
# endif
}
int matEigensolver (SxComplex8 *eigVals, SxComplex8 *eigVecs,
SxComplex8 *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 2*n : size;
integer workDim = lWork;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
complex8_t *eigVecLeft = new complex8_t [ldVecLeft];
complex8_t *work = new complex8_t [workDim];
float *rWork = new float [workDim];
cgeev (&jobvl, &jobvr,
&rank, (complex8_t *)inMat, &rank,
(complex8_t *)eigVals, eigVecLeft,
&ldVecLeft, (complex8_t *)eigVecs, &rank, work, &lWork,
rWork, &info, 0, 0);
if (cmd == OptSize) lWork = (int)work[0].re;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# elif defined (USE_ESSL)
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
cgeev (iOpt, (complex<float> *)inMat, rank,
(complex<float> *)eigVals, (complex<float> *)eigVecs, rank,
NULL, rank, NULL, 0);
// --- normalize eigenvectors
double c;
for (int i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
# elif defined (USE_INTEL_MKL)
MKL_Complex8 *eigVecLeft = new MKL_Complex8 [ldVecLeft];
MKL_Complex8 *work = new MKL_Complex8 [workDim];
float *rWork = new float [workDim];
cgeev (&jobvl, &jobvr,
&rank, (MKL_Complex8 *)inMat, &rank,
(MKL_Complex8 *)eigVals, eigVecLeft,
&ldVecLeft, (MKL_Complex8 *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].real;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# elif defined (USE_ACML)
complex *eigVecLeft = new complex [ldVecLeft];
cgeev (jobvl, jobvr,
rank, (complex *)inMat, rank,
(complex *)eigVals, eigVecLeft,
ldVecLeft, (complex *)eigVecs, rank, &info);
delete eigVecLeft;
# else
complex *eigVecLeft = new complex [ldVecLeft];
complex *work = new complex [workDim];
real *rWork = new real [workDim];
cgeev_ (&jobvl, &jobvr,
&rank, (complex *)inMat, &rank,
(complex *)eigVals, eigVecLeft,
&ldVecLeft, (complex *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].r;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# endif
# ifndef USE_ESSL
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in CGEEV: " << info << std::endl;
SX_EXIT;
}
# endif
# if defined (USE_VECLIB)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ESSL)
return 0;
# elif defined (USE_INTEL_MKL)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ACML)
return 0;
# else
return (cmd == OptSize) ? (int)lWork : 0;
# endif
}
int matEigensolver (SxComplex16 *eigVals, SxComplex16 *eigVecs,
SxComplex16 *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 2*n : size;
integer workDim = !size ? 2*n : size;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
complex16_t *eigVecLeft = new complex16_t [ldVecLeft];
complex16_t *work = new complex16_t [workDim];
double *rWork = new double [workDim];
zgeev (&jobvl, &jobvr,
&rank, (complex16_t *)inMat, &rank,
(complex16_t *)eigVals, eigVecLeft,
&ldVecLeft, (complex16_t *)eigVecs, &rank, work, &lWork,
rWork, &info, 0, 0);
if (cmd == OptSize) lWork = (int)work[0].re;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# elif defined (USE_ESSL)
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
zgeev (iOpt, (complex<double> *)inMat, rank,
(complex<double> *)eigVals, (complex<double> *)eigVecs, rank,
NULL, rank, NULL, 0);
// --- normalize eigenvectors
double c;
for (int i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
# elif defined (USE_INTEL_MKL)
MKL_Complex16 *eigVecLeft = new MKL_Complex16 [ldVecLeft];
MKL_Complex16 *work = new MKL_Complex16 [workDim];
double *rWork = new double [workDim];
zgeev (&jobvl, &jobvr,
&rank, (MKL_Complex16 *)inMat, &rank,
(MKL_Complex16 *)eigVals, eigVecLeft,
&ldVecLeft, (MKL_Complex16 *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].real;
delete [] rWork;
delete [] work;
delete [] eigVecLeft;
# elif defined (USE_ACML)
doublecomplex *eigVecLeft = new doublecomplex [ldVecLeft];
zgeev (jobvl, jobvr,
rank, (doublecomplex *)inMat, rank,
(doublecomplex *)eigVals, eigVecLeft,
ldVecLeft, (doublecomplex *)eigVecs, rank, &info);
delete [] eigVecLeft;
# else
doublecomplex *eigVecLeft = new doublecomplex [ldVecLeft];
doublecomplex *work = new doublecomplex [workDim];
doublereal *rWork = new doublereal [workDim];
zgeev_ (&jobvl, &jobvr,
&rank, (doublecomplex *)inMat, &rank,
(doublecomplex *)eigVals, eigVecLeft,
&ldVecLeft, (doublecomplex *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].r;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# endif
# ifndef USE_ESSL
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in DGEEV: " << info << std::endl;
SX_EXIT;
}
# endif
# if defined (USE_VECLIB)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ESSL)
return 0;
# elif defined (USE_INTEL_MKL)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ACML)
return 0;
# else
return (cmd == OptSize) ? (int)lWork : 0;
# endif
}
//------------------------------------------------------------------------------
// Eigensolver - tridiagonal matrices
//------------------------------------------------------------------------------
void matEigensolverTri (float *eigVals, float *eigVecs,
float *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
float *work = new float [workDim];
sspev (&jobz, &uploChar,
&rank, (float *)inMat, (float *)eigVals,
(float *)eigVecs, &ldEigVecs,
work, &info, 0, 0);
delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
sspev (iOpt, inMat, eigVals,
eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
float *work = new float [workDim];
sspev (&jobz, &uploChar,
&rank, (float *)inMat, (float *)eigVals,
(float *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
sspev (jobz, uploChar,
rank, inMat, eigVals,
eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 3*n;
real *work = new real [workDim];
sspev_ (&jobz, &uploChar,
&rank, (real *)inMat, (real *)eigVals,
(real *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in SSPEV: " << info << std::endl;
SX_EXIT;
}
}
void matEigensolverTri (double *eigVals, double *eigVecs,
double *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
double *work = new double [workDim];
dspev (&jobz, &uploChar,
&rank, (double *)inMat, (double *)eigVals,
(double *)eigVecs, &ldEigVecs,
work, &info, 0, 0);
delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
dspev (iOpt, inMat, eigVals,
eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
double *work = new double [workDim];
dspev (&jobz, &uploChar,
&rank, (double *)inMat, (double *)eigVals,
(double *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
dspev (jobz, uploChar,
rank, inMat, eigVals,
eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 3*n;
doublereal *work = new doublereal [workDim];
dspev_ (&jobz, &uploChar,
&rank, (doublereal *)inMat, (doublereal *)eigVals,
(doublereal *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in DSPEV: " << info << std::endl;
SX_EXIT;
}
}
void matEigensolverTri (float *eigVals, SxComplex8 *eigVecs,
SxComplex8 *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
complex8_t *work = new complex8_t [workDim];
float *rWork = new float [rWorkDim];
chpev (&jobz, &uploChar,
&rank, (complex8_t *)inMat, (float *)eigVals,
(complex8_t *)eigVecs, &ldEigVecs,
work, rWork, &info, 0, 0);
delete [] rWork; delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
chpev (iOpt, (complex<float> *)inMat, eigVals,
(complex<float> *)eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
MKL_Complex8 *work = new MKL_Complex8 [workDim];
float *rWork = new float [rWorkDim];
chpev (&jobz, &uploChar,
&rank, (MKL_Complex8 *)inMat, (float *)eigVals,
(MKL_Complex8 *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
chpev (jobz, uploChar,
rank, (complex *)inMat, (float *)eigVals,
(complex *)eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 2*n-1;
integer rWorkDim = 3*n-2;
complex *work = new complex [workDim];
real *rWork = new real [rWorkDim];
chpev_ (&jobz, &uploChar,
&rank, (complex *)inMat, (real *)eigVals,
(complex *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in CHPEV: " << info << std::endl;
SX_EXIT;
}
}
void matEigensolverTri (double *eigVals, SxComplex16 *eigVecs,
SxComplex16 *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
complex16_t *work = new complex16_t [workDim];
double *rWork = new double[rWorkDim];
zhpev (&jobz, &uploChar,
&rank, (complex16_t *)inMat, (double *)eigVals,
(complex16_t *)eigVecs, &ldEigVecs,
work, rWork, &info, 0, 0);
delete [] rWork; delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
zhpev (iOpt, (complex<double> *)inMat, eigVals,
(complex<double> *)eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
MKL_Complex16 *work = new MKL_Complex16 [workDim];
double *rWork = new double[rWorkDim];
zhpev (&jobz, &uploChar,
&rank, (MKL_Complex16 *)inMat, (double *)eigVals,
(MKL_Complex16 *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
zhpev (jobz, uploChar,
rank, (doublecomplex *)inMat, (double *)eigVals,
(doublecomplex *)eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 2*n-1;
integer rWorkDim = 3*n-2;
doublecomplex *work = new doublecomplex [workDim];
doublereal *rWork = new doublereal [rWorkDim];
zhpev_ (&jobz, &uploChar,
&rank, (doublecomplex *)inMat, (doublereal *)eigVals,
(doublecomplex *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in ZHPEV: " << info << std::endl;
SX_EXIT;
}
}
// -------------------------- SX_IGNORE_THE_REST_OF_THE_FILE
# endif
// --------------------------
| 36.127718
| 90
| 0.524202
|
ashtonmv
|
f4e35f80c0c5af0818c4a4e061d12b0d1d2fb196
| 890
|
tpp
|
C++
|
lib/include/ellcpp/oracles/sdp_oracle.tpp
|
luk036/ellcpp
|
3415e7ffb70b63edb9ce4d6c2b9fee92898538bc
|
[
"MIT"
] | 2
|
2020-07-26T04:58:11.000Z
|
2021-01-26T06:29:59.000Z
|
lib/include/ellcpp/oracles/sdp_oracle.tpp
|
luk036/ellcpp
|
3415e7ffb70b63edb9ce4d6c2b9fee92898538bc
|
[
"MIT"
] | null | null | null |
lib/include/ellcpp/oracles/sdp_oracle.tpp
|
luk036/ellcpp
|
3415e7ffb70b63edb9ce4d6c2b9fee92898538bc
|
[
"MIT"
] | 2
|
2018-06-03T08:20:20.000Z
|
2019-06-30T10:41:49.000Z
|
// -*- coding: utf-8 -*-
#pragma once
#include "lmi_oracle.hpp"
namespace bnu = boost::numeric::ublas;
class sdp_oracle
{
using Mat = bnu::symmetric_matrix<double, bnu::upper>;
using Vec = bnu::vector<double>;
using Arr = bnu::vector<Mat>;
public:
sdp_oracle(const Vec& c, const Arr& F)
: _c {c}
, _lmi {lmi_oracle(F)}
{
}
auto operator()(const Vec& x, double& t) const
{
auto [g, fj] = _lmi.chk_spd(x);
if (fj > 0)
{
return std::make_tuple(g, fj, false);
}
auto f0 = bnu::inner_prod(_c, x);
fj = f0 - t;
g = _c;
if (fj > 0)
{
return std::make_tuple(g, fj, false);
}
t = f0;
return std::make_tuple(g, 0., true);
}
private:
const Vec& _c;
lmi_oracle _lmi;
};
| 20.697674
| 59
| 0.477528
|
luk036
|
f4e85aaa6bbe122fff1af5ec5d461311f2ed6228
| 10,000
|
hpp
|
C++
|
metricknn/metricknn_lib/src/metricknn/metricknn_cpp/mknn_predefined_distance.hpp
|
juanbarrios/multimedia_tools
|
91fe64779168c3dd3ad4e51e089df9ccad5f176b
|
[
"BSD-2-Clause"
] | 6
|
2015-09-08T00:14:59.000Z
|
2018-09-11T09:46:40.000Z
|
metricknn/metricknn_lib/src/metricknn/metricknn_cpp/mknn_predefined_distance.hpp
|
juanbarrios/multimedia_tools
|
91fe64779168c3dd3ad4e51e089df9ccad5f176b
|
[
"BSD-2-Clause"
] | null | null | null |
metricknn/metricknn_lib/src/metricknn/metricknn_cpp/mknn_predefined_distance.hpp
|
juanbarrios/multimedia_tools
|
91fe64779168c3dd3ad4e51e089df9ccad5f176b
|
[
"BSD-2-Clause"
] | 1
|
2020-11-13T15:55:30.000Z
|
2020-11-13T15:55:30.000Z
|
/*
* Copyright (C) 2012-2015, Juan Manuel Barrios <http://juan.cl/>
* All rights reserved.
*
* This file is part of MetricKnn. http://metricknn.org/
* MetricKnn is made available under the terms of the BSD 2-Clause License.
*/
#ifndef MKNN_PREDEFINED_DISTANCE_HPP_
#define MKNN_PREDEFINED_DISTANCE_HPP_
#include "../metricknn_cpp.hpp"
namespace mknn {
/**
* MetricKnn provides a set of pre-defined distances.
*
* The generic way for instantiating a predefined distance is to use the method
* Distance::newPredefined, which requires the ID and parameters of the distance.
*
* The complete list of predefined distances can be listed by calling
* Distance::helpListDistances. The parameters supported by each distance
* can be listed by calling PredefDistance::helpPrintDistance.
*
* This class contains some functions to ease the instantiation of some predefined distances.
*
*/
class PredefDistance {
public:
/**
* @name Help functions
* @{
*/
/**
* Lists to standard output all pre-defined distances.
*/
static void helpListDistances();
/**
* Prints to standard output the help for a distance.
*
* @param id_dist the unique identifier of a pre-defined distance.
*/
static void helpPrintDistance(std::string id_dist);
/**
* Tests whether the given string references a valid pre-defined distance.
*
* @param id_dist the unique identifier of a pre-defined distance.
* @return true whether @p id_dist corresponds to a pre-defined distance, and false otherwise.
*/
static bool testDistanceId(std::string id_dist);
/**
* @}
*/
/**
* Creates an object for Manhattan or Taxi-cab distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{L1}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sum_{i=1}^{n} |x_i - y_i|
* \f]
*
* This distance satisfies the metric properties, therefore it can be used by Metric Indexes to obtain exact nearest neighbors.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams L1();
/**
* Creates an object for Euclidean distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{L2}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sqrt{ \sum_{i=1}^{n} (x_i - y_i)^2 }
* \f]
*
* This distance satisfies the metric properties, therefore it can be used by Metric Indexes to obtain exact nearest neighbors.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams L2();
/**
* Creates an object for L-max distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Lmax}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \max_{i \in \{1,...,n\}} |x_i - y_i|
* \f]
*
* This distance satisfies the metric properties, therefore it can be used by Metric Indexes to obtain exact nearest neighbors.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Lmax();
/**
* Creates an object for Minkowski distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Lp}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \left( {\sum_{i=1}^n |x_i-y_i|^p } \right)^{\frac{1}{p}}
* \f]
*
* @note This distance satisfies the metric properties only when \f$ p \geq 1 \f$.
* When \f$ 0 < p < 1 \f$ the Metric Indexes may not obtain exact nearest neighbors.
*
* @param order the order \f$ p \f$ of the distance \f$ p > 0 \f$.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Lp(double order);
/**
* Creates an object for Hamming distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Hamming}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sum_{i=1}^n \bar{p}_i
* \f]
*
* where \f$ \bar{p}_i= \left\{ \begin{array}{ll} 0 & x_i = y_i\\ 1 & x_i \neq y_i\\ \end{array} \right. \f$ .
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Hamming();
/**
* Creates an object for Chi2 distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \chi^2(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sum_{i=1}^n \frac{ (x_i - \bar{m}_i )^2 }{ \bar{m}_i }
* \f]
*
* where \f$ \bar{m}_i=\frac{x_i+y_i}{2} \f$ .
*
* @note This distance does not satisfy the metric properties.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Chi2();
/**
* Creates an object for Hellinger distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Hellinger}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sqrt { \frac { \sum_{i=1}^n ( \sqrt{x_i} - \sqrt{y_i} )^2} { 2 } }
* \f]
*
* @note This distance does not satisfy the metric properties.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Hellinger();
/**
* Creates an object for Cosine Similarity.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{cos}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \frac { \sum_{i=1}^n x_i \cdot y_i } {\sqrt{ \sum_{i=1}^{n} {x_i}^2 } \cdot \sqrt{ \sum_{i=1}^{n} {y_i}^2 } }
* \f]
*
* @note This is a similarity function, therefore a search for the Farthest Neighbors is needed. See #CosineDistance
* for a distance version.
*
* @param normalize_vectors Computes the euclidean norm for each vector. If this is set to false, it assumes the vectors are already normalized
* thus the value \f$ \sqrt{ \sum_{i=1}^{n} {x_i}^2 } \cdot \sqrt{ \sum_{i=1}^{n} {y_i}^2 } \f$ is equal to 1.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams CosineSimilarity(bool normalize_vectors);
/**
* Creates an object for Cosine Distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{CosineDistance}(\vec{x},\vec{y}) = \sqrt{ 2 ( 1 - \cos(\vec{x},\vec{y})) }
* \f]
*
* where \f$ \cos(\vec{x},\vec{y}) \f$ is the cosine similarity between vectors \f$ \vec{x} \f$ and \f$ \vec{y} \f$ as defined in #CosineSimilarity.
*
* The nearest neighbors obtained by this distance are identical to the farthest neighbor obtained by cosine similarity (if vectors
* are normalized). Therefore, this distance can be used accelerate the search using cosine similarity.
*
* @param normalize_vectors The cosine similarity must normalize vectors to euclidean norm 1 prior to each computation.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams CosineDistance(bool normalize_vectors);
/**
* Creates an object for Earth Mover's Distance.
*
* This function uses OpenCV's implementation, see http://docs.opencv.org/modules/imgproc/doc/histograms.html#emd .
*
* @note Depending on the cost_matrix this distance may or may not satisfy the metric properties. If the values in cost_matrix
* where computed by a metric distance, then the EMD will also be a metric distance.
*
* @param matrix_rows
* @param matrix_cols
* @param cost_matrix an array of length <tt>matrix_rows * matrix_cols</tt> with the
* cost for each pair of dimensions.
* @param normalize_vectors normalizes (sum 1) both vectors before computing the distance.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams EMD(long long matrix_rows, long long matrix_cols,
double *cost_matrix, bool normalize_vectors);
/**
* Creates an object for Dynamic Partial Function distance. See definition http://dx.doi.org/10.1109/ICIP.2002.1040021 .
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{DPF}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \left( {\sum_{i \in \Delta_m} |x_i-y_i|^p } \right)^{\frac{1}{p}}
* \f]
*
* where \f$ \Delta_m \f$ is the subset of the \f$ m \f$ smallest values of \f$ |x_i-y_i| \f$.
*
* @param order the order \f$ p \f$ of the distance \f$ p > 0 \f$.
* @param num_dims_discard fixed number of dimensions to discard <tt>0 @< num_dims_discard @< num_dimensions</tt>.
* @param pct_discard fixed number of dimensions to discard computed as a fraction of @p num_dimensions <tt>0 @< pct_discard @< 1</tt>.
* <tt>num_dims_discard = round(pct_discard * num_dimensions)</tt>
* @param threshold_discard discard all dimensions which difference is higher than @p threshold_discard.
* It produces a variable number of dimensions to discard.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams DPF(double order, long long num_dims_discard,
double pct_discard, double threshold_discard);
/**
* Defines a multi-distance, which is a weighted combination of distances.
*
* @warning Under construction.
*
* @param subdistances the distances to combine
* @param free_subdistances_on_release to release the subdistances together with this distance
* @param normalization_values the value to divide each distance.
* @param ponderation_values the value to weight each distance.
* @param with_auto_config run algorithms to automatically locate normalization or ponderation values.
* @param auto_config_dataset the data to be used by the algorithms.
* @param auto_normalize_alpha the value to be used by the alpha-normalization.
* @param auto_ponderation_maxrho run the automatic ponderation according to max rho criterium.
* @param auto_ponderation_maxtau run the automatic ponderation according to max tau criterium.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams MultiDistance(
const std::vector<Distance> &subdistances,
bool free_subdistances_on_release,
const std::vector<double> &normalization_values,
const std::vector<double> &ponderation_values,
bool with_auto_config, Dataset &auto_config_dataset,
double auto_normalize_alpha, bool auto_ponderation_maxrho,
bool auto_ponderation_maxtau);
};
}
#endif
| 37.593985
| 162
| 0.6887
|
juanbarrios
|
f4e96d63ad6cb13ab1d635f38a2c82281158d907
| 4,545
|
cpp
|
C++
|
Engine/__Deprecated/ImGui/ImUtil.cpp
|
zolo-mario/ZeloEngine
|
e595467dd057157c47cc8fa91399b0c7137dae63
|
[
"MIT"
] | 98
|
2019-09-13T16:00:57.000Z
|
2022-03-25T05:15:36.000Z
|
Engine/__Deprecated/ImGui/ImUtil.cpp
|
zolo-mario/ZeloEngine
|
e595467dd057157c47cc8fa91399b0c7137dae63
|
[
"MIT"
] | 269
|
2019-08-22T01:47:09.000Z
|
2021-12-01T14:47:47.000Z
|
Engine/__Deprecated/ImGui/ImUtil.cpp
|
zolo-mario/ZeloEngine
|
e595467dd057157c47cc8fa91399b0c7137dae63
|
[
"MIT"
] | 5
|
2021-05-07T11:11:40.000Z
|
2022-03-29T08:38:33.000Z
|
// ImUtil.cpp
// created on 2021/5/28
// author @zoloypzuo
#include "ZeloPreCompiledHeader.h"
#include "ImUtil.h"
#include "ImGuiInternal.h"
int ImStricmp(const char *str1, const char *str2) {
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) {
str1++;
str2++;
}
return d;
}
const char *ImStristr(const char *haystack, const char *needle, const char *needle_end) {
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = toupper(*needle);
while (*haystack) {
if (toupper(*haystack) == un0) {
const char *b = needle + 1;
for (const char *a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
ImU32 crc32(const void *data, size_t data_size, ImU32 seed) {
static ImU32 crc32_lut[256] = {0};
if (!crc32_lut[1]) {
const ImU32 polynomial = 0xEDB88320;
for (ImU32 i = 0; i < 256; i++) {
ImU32 crc = i;
for (ImU32 j = 0; j < 8; j++)
crc = (crc >> 1) ^ (-int(crc & 1) & polynomial);
crc32_lut[i] = crc;
}
}
ImU32 crc = ~seed;
const unsigned char *current = (const unsigned char *) data;
while (data_size--)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
return ~crc;
}
size_t ImFormatString(char *buf, size_t buf_size, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
int w = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
buf[buf_size - 1] = 0;
if (w == -1) w = buf_size;
return w;
}
size_t ImFormatStringV(char *buf, size_t buf_size, const char *fmt, va_list args) {
int w = vsnprintf(buf, buf_size, fmt, args);
buf[buf_size - 1] = 0;
if (w == -1) w = buf_size;
return w;
}
ImU32 ImConvertColorFloat4ToU32(const ImVec4 &in) {
ImU32 out = ((ImU32) (ImSaturate(in.x) * 255.f));
out |= ((ImU32) (ImSaturate(in.y) * 255.f) << 8);
out |= ((ImU32) (ImSaturate(in.z) * 255.f) << 16);
out |= ((ImU32) (ImSaturate(in.w) * 255.f) << 24);
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImConvertColorRGBtoHSV(float r, float g, float b, float &out_h, float &out_s, float &out_v) {
float K = 0.f;
if (g < b) {
const float tmp = g;
g = b;
b = tmp;
K = -1.f;
}
if (r < g) {
const float tmp = r;
r = g;
g = tmp;
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = abs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImConvertColorHSVtoRGB(float h, float s, float v, float &out_r, float &out_g, float &out_b) {
if (s == 0.0f) {
// gray
out_r = out_g = out_b = v;
return;
}
h = fmodf(h, 1.0f) / (60.0f / 360.0f);
int i = (int) h;
float f = h - (float) i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i) {
case 0:
out_r = v;
out_g = t;
out_b = p;
break;
case 1:
out_r = q;
out_g = v;
out_b = p;
break;
case 2:
out_r = p;
out_g = v;
out_b = t;
break;
case 3:
out_r = p;
out_g = q;
out_b = v;
break;
case 4:
out_r = t;
out_g = p;
out_b = v;
break;
case 5:
default:
out_r = v;
out_g = p;
out_b = q;
break;
}
}
//-----------------------------------------------------------------------------
ImGuiOncePerFrame::ImGuiOncePerFrame() : LastFrame(-1) {}
bool ImGuiOncePerFrame::TryIsNewFrame() const {
const int current_frame = ImGui::GetFrameCount();
if (LastFrame == current_frame) return false;
LastFrame = current_frame;
return true;
}
ImGuiOncePerFrame::operator bool() const { return TryIsNewFrame(); }
| 27.545455
| 102
| 0.492629
|
zolo-mario
|
f4edd60f9853e6fd95b8846f13265c60b1d426d9
| 3,854
|
cpp
|
C++
|
manycal/nodes/camera_throttler.cpp
|
Humhu/argus
|
8b112382038c6df1ecf15d9c872b6cc9b471cd22
|
[
"AFL-3.0"
] | 6
|
2017-08-02T20:32:52.000Z
|
2021-06-15T09:33:33.000Z
|
manycal/nodes/camera_throttler.cpp
|
Humhu/argus
|
8b112382038c6df1ecf15d9c872b6cc9b471cd22
|
[
"AFL-3.0"
] | 1
|
2018-03-12T22:57:59.000Z
|
2018-03-13T02:52:36.000Z
|
manycal/nodes/camera_throttler.cpp
|
Humhu/argus
|
8b112382038c6df1ecf15d9c872b6cc9b471cd22
|
[
"AFL-3.0"
] | 4
|
2017-03-25T08:36:17.000Z
|
2019-04-23T00:28:16.000Z
|
#include <ros/ros.h>
#include <deque>
#include <boost/foreach.hpp>
#include "image_transport/image_transport.h"
#include "cv_bridge/cv_bridge.h"
#include "argus_utils/synchronization/MessageThrottler.hpp"
#include "manycal/SetThrottleWeight.h"
#include "argus_utils/utils/ParamUtils.h"
using namespace argus;
class CameraThrottler
{
public:
CameraThrottler( ros::NodeHandle& nh, ros::NodeHandle& ph )
: publicPort( nh )
{
// TODO Parameters for _throttle?
unsigned int buffLen;
GetParamRequired( ph, "buffer_length", buffLen );
double r;
GetParamRequired( ph, "max_rate", r );
_throttle.SetBufferLength( buffLen );
_throttle.SetTargetRate( r );
GetParamRequired( ph, "update_rate", r );
_updateTimer = nh.createTimer( ros::Duration( 1.0/r ), &CameraThrottler::TimerCallback, this );
YAML::Node sources;
GetParamRequired( ph, "sources", sources );
YAML::Node::const_iterator iter;
for( iter = sources.begin(); iter != sources.end(); ++iter )
{
const std::string& name = iter->first.as<std::string>();
const YAML::Node& info = iter->second;
std::string input_topic, output_topic;
GetParamRequired( info, "input", input_topic );
GetParamRequired( info, "output", output_topic );
ROS_INFO_STREAM( "Registering source " << name << " with input " << input_topic <<
" and output " << output_topic );
_throttle.RegisterSource( name );
_throttle.SetSourceWeight( name, 1.0 );
_subscribers.emplace_back(
publicPort.subscribeCamera(input_topic, 10,
boost::bind(&CameraThrottler::CameraCallback, this, name, _1, _2)) );
_publishers[name] = publicPort.advertiseCamera(output_topic, 10);
}
_throttleServer = ph.advertiseService( "set_throttle", &CameraThrottler::SetThrottleCallback,
this );
}
private:
ros::Timer _updateTimer;
ros::ServiceServer _throttleServer;
image_transport::ImageTransport publicPort;
std::deque<image_transport::CameraSubscriber> _subscribers;
std::map<std::string, image_transport::CameraPublisher> _publishers;
typedef std::pair<sensor_msgs::Image::ConstPtr, sensor_msgs::CameraInfo::ConstPtr> CameraData;
typedef MessageThrottler<CameraData> DataThrottler;
DataThrottler _throttle;
bool SetThrottleCallback( manycal::SetThrottleWeight::Request& req,
manycal::SetThrottleWeight::Response& res )
{
try
{
_throttle.SetSourceWeight( req.name, req.weight );
return true;
}
catch ( const std::invalid_argument& e )
{
return false;
}
}
void TimerCallback( const ros::TimerEvent& event )
{
DataThrottler::KeyedData out;
if( _throttle.GetOutput( event.current_real.toSec(), out ) )
{
_publishers[out.first].publish( out.second.first, out.second.second );
}
}
void CameraCallback( const std::string& name,
const sensor_msgs::Image::ConstPtr& image,
const sensor_msgs::CameraInfo::ConstPtr& info )
{
_throttle.BufferData( name, CameraData( image, info ) );
}
};
int main( int argc, char** argv )
{
ros::init( argc, argv, "camera_throttler" );
ros::NodeHandle nh;
ros::NodeHandle ph( "~" );
unsigned int numThreads;
GetParam<unsigned int>( ph, "num_threads", numThreads, 1 );
CameraThrottler throttler( nh, ph );
// ros::spin();
ros::AsyncSpinner spinner( numThreads );
spinner.start();
ros::waitForShutdown();
return 0;
}
| 31.080645
| 103
| 0.614427
|
Humhu
|
f4f13b044f9221528c862b19ad1af4e8935cc5f8
| 77
|
hh
|
C++
|
build/X86/mem/protocol/VIPERCoalescer.hh
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | 5
|
2019-12-12T16:26:09.000Z
|
2022-03-17T03:23:33.000Z
|
build/X86/mem/protocol/VIPERCoalescer.hh
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | null | null | null |
build/X86/mem/protocol/VIPERCoalescer.hh
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | null | null | null |
#include "/home/zhoushuxin/gem5/build/X86/mem/ruby/system/VIPERCoalescer.hh"
| 38.5
| 76
| 0.805195
|
zhoushuxin
|
f4f1ddcc73b72ad1189d7145666bdabb400f88e4
| 239
|
cpp
|
C++
|
src/question_1/question1.cpp
|
juliaholland/acc-cosc-1337-midterm-juliaholland
|
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
|
[
"MIT"
] | null | null | null |
src/question_1/question1.cpp
|
juliaholland/acc-cosc-1337-midterm-juliaholland
|
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
|
[
"MIT"
] | null | null | null |
src/question_1/question1.cpp
|
juliaholland/acc-cosc-1337-midterm-juliaholland
|
a6d09518393fd8ee9e88c1a4ae3d468e2bd291c3
|
[
"MIT"
] | null | null | null |
#include "question1.h"
bool test_config()
{
return true;
}
double get_kinetic_energy(double mass, double velocity)
{
double kineticEnergy;
kineticEnergy = 0.5 * mass * velocity * velocity;
return kineticEnergy;
}
| 14.058824
| 55
| 0.682008
|
juliaholland
|
f4f2a7201d0e73ca372a5a429bfe6ca7b51eb2fd
| 40,892
|
cpp
|
C++
|
src/vedit.cpp
|
linails/vnote
|
97810731db97292f474951c3450aac150acef0bc
|
[
"MIT"
] | 1
|
2019-07-27T10:46:41.000Z
|
2019-07-27T10:46:41.000Z
|
src/vedit.cpp
|
linails/vnote
|
97810731db97292f474951c3450aac150acef0bc
|
[
"MIT"
] | 1
|
2022-01-22T13:10:44.000Z
|
2022-01-22T13:10:44.000Z
|
src/vedit.cpp
|
linails/vnote
|
97810731db97292f474951c3450aac150acef0bc
|
[
"MIT"
] | 1
|
2021-06-17T02:43:27.000Z
|
2021-06-17T02:43:27.000Z
|
#include <QtWidgets>
#include <QVector>
#include <QDebug>
#include "vedit.h"
#include "vnote.h"
#include "vconfigmanager.h"
#include "vtableofcontent.h"
#include "utils/vutils.h"
#include "utils/veditutils.h"
#include "utils/vmetawordmanager.h"
#include "veditoperations.h"
#include "vedittab.h"
#include "dialog/vinsertlinkdialog.h"
#include "utils/viconutils.h"
extern VConfigManager *g_config;
extern VNote *g_vnote;
extern VMetaWordManager *g_mwMgr;
VEdit::VEdit(VFile *p_file, QWidget *p_parent)
: QTextEdit(p_parent), m_file(p_file),
m_editOps(NULL), m_enableInputMethod(true)
{
const int labelTimerInterval = 500;
const int extraSelectionHighlightTimer = 500;
const int labelSize = 64;
m_selectedWordColor = QColor(g_config->getEditorSelectedWordBg());
m_searchedWordColor = QColor(g_config->getEditorSearchedWordBg());
m_searchedWordCursorColor = QColor(g_config->getEditorSearchedWordCursorBg());
m_incrementalSearchedWordColor = QColor(g_config->getEditorIncrementalSearchedWordBg());
m_trailingSpaceColor = QColor(g_config->getEditorTrailingSpaceBg());
QPixmap wrapPixmap(":/resources/icons/search_wrap.svg");
m_wrapLabel = new QLabel(this);
m_wrapLabel->setPixmap(wrapPixmap.scaled(labelSize, labelSize));
m_wrapLabel->hide();
m_labelTimer = new QTimer(this);
m_labelTimer->setSingleShot(true);
m_labelTimer->setInterval(labelTimerInterval);
connect(m_labelTimer, &QTimer::timeout,
this, &VEdit::labelTimerTimeout);
m_highlightTimer = new QTimer(this);
m_highlightTimer->setSingleShot(true);
m_highlightTimer->setInterval(extraSelectionHighlightTimer);
connect(m_highlightTimer, &QTimer::timeout,
this, &VEdit::doHighlightExtraSelections);
m_extraSelections.resize((int)SelectionId::MaxSelection);
updateFontAndPalette();
m_config.init(QFontMetrics(font()), false);
updateConfig();
connect(this, &VEdit::cursorPositionChanged,
this, &VEdit::handleCursorPositionChanged);
connect(this, &VEdit::selectionChanged,
this, &VEdit::highlightSelectedWord);
m_lineNumberArea = new LineNumberArea(this);
connect(document(), &QTextDocument::blockCountChanged,
this, &VEdit::updateLineNumberAreaMargin);
connect(this, &QTextEdit::textChanged,
this, &VEdit::updateLineNumberArea);
connect(verticalScrollBar(), &QScrollBar::valueChanged,
this, &VEdit::updateLineNumberArea);
updateLineNumberAreaMargin();
connect(document(), &QTextDocument::contentsChange,
this, &VEdit::updateBlockLineDistanceHeight);
}
VEdit::~VEdit()
{
}
void VEdit::updateConfig()
{
m_config.update(QFontMetrics(font()));
if (m_config.m_tabStopWidth > 0) {
setTabStopWidth(m_config.m_tabStopWidth);
}
emit configUpdated();
}
void VEdit::beginEdit()
{
updateFontAndPalette();
updateConfig();
setReadOnlyAndHighlight(false);
setModified(false);
}
void VEdit::endEdit()
{
setReadOnlyAndHighlight(true);
}
void VEdit::saveFile()
{
Q_ASSERT(m_file->isModifiable());
if (!document()->isModified()) {
return;
}
m_file->setContent(toHtml());
setModified(false);
}
void VEdit::reloadFile()
{
setHtml(m_file->getContent());
setModified(false);
}
bool VEdit::scrollToBlock(int p_blockNumber)
{
QTextBlock block = document()->findBlockByNumber(p_blockNumber);
if (block.isValid()) {
VEditUtils::scrollBlockInPage(this, block.blockNumber(), 0);
moveCursor(QTextCursor::EndOfBlock);
return true;
}
return false;
}
bool VEdit::isModified() const
{
return document()->isModified();
}
void VEdit::setModified(bool p_modified)
{
document()->setModified(p_modified);
}
void VEdit::insertImage()
{
if (m_editOps) {
m_editOps->insertImage();
}
}
void VEdit::insertLink()
{
if (!m_editOps) {
return;
}
QString text;
QString linkText, linkUrl;
QTextCursor cursor = textCursor();
if (cursor.hasSelection()) {
text = VEditUtils::selectedText(cursor).trimmed();
// Only pure space is accepted.
QRegExp reg("[\\S ]*");
if (reg.exactMatch(text)) {
QUrl url = QUrl::fromUserInput(text,
m_file->fetchBasePath());
QRegExp urlReg("[\\.\\\\/]");
if (url.isValid()
&& text.contains(urlReg)) {
// Url.
linkUrl = text;
} else {
// Text.
linkText = text;
}
}
}
VInsertLinkDialog dialog(tr("Insert Link"),
"",
"",
linkText,
linkUrl,
false,
this);
if (dialog.exec() == QDialog::Accepted) {
linkText = dialog.getLinkText();
linkUrl = dialog.getLinkUrl();
Q_ASSERT(!linkText.isEmpty() && !linkUrl.isEmpty());
m_editOps->insertLink(linkText, linkUrl);
}
}
bool VEdit::peekText(const QString &p_text, uint p_options, bool p_forward)
{
if (p_text.isEmpty()) {
makeBlockVisible(document()->findBlock(textCursor().selectionStart()));
highlightIncrementalSearchedWord(QTextCursor());
return false;
}
bool wrapped = false;
QTextCursor retCursor;
bool found = findTextHelper(p_text, p_options, p_forward,
p_forward ? textCursor().position() + 1
: textCursor().position(),
wrapped, retCursor);
if (found) {
makeBlockVisible(document()->findBlock(retCursor.selectionStart()));
highlightIncrementalSearchedWord(retCursor);
}
return found;
}
// Use QTextEdit::find() instead of QTextDocument::find() because the later has
// bugs in searching backward.
bool VEdit::findTextHelper(const QString &p_text, uint p_options,
bool p_forward, int p_start,
bool &p_wrapped, QTextCursor &p_cursor)
{
p_wrapped = false;
bool found = false;
// Options
QTextDocument::FindFlags findFlags;
bool caseSensitive = false;
if (p_options & FindOption::CaseSensitive) {
findFlags |= QTextDocument::FindCaseSensitively;
caseSensitive = true;
}
if (p_options & FindOption::WholeWordOnly) {
findFlags |= QTextDocument::FindWholeWords;
}
if (!p_forward) {
findFlags |= QTextDocument::FindBackward;
}
// Use regular expression
bool useRegExp = false;
QRegExp exp;
if (p_options & FindOption::RegularExpression) {
useRegExp = true;
exp = QRegExp(p_text,
caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
}
// Store current state of the cursor.
QTextCursor cursor = textCursor();
if (cursor.position() != p_start) {
if (p_start < 0) {
p_start = 0;
} else if (p_start > document()->characterCount()) {
p_start = document()->characterCount();
}
QTextCursor startCursor = cursor;
startCursor.setPosition(p_start);
setTextCursor(startCursor);
}
while (!found) {
if (useRegExp) {
found = find(exp, findFlags);
} else {
found = find(p_text, findFlags);
}
if (p_wrapped) {
break;
}
if (!found) {
// Wrap to the other end of the document to search again.
p_wrapped = true;
QTextCursor wrapCursor = textCursor();
if (p_forward) {
wrapCursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
} else {
wrapCursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
}
setTextCursor(wrapCursor);
}
}
if (found) {
p_cursor = textCursor();
}
// Restore the original cursor.
setTextCursor(cursor);
return found;
}
QList<QTextCursor> VEdit::findTextAll(const QString &p_text, uint p_options)
{
QList<QTextCursor> results;
if (p_text.isEmpty()) {
return results;
}
// Options
QTextDocument::FindFlags findFlags;
bool caseSensitive = false;
if (p_options & FindOption::CaseSensitive) {
findFlags |= QTextDocument::FindCaseSensitively;
caseSensitive = true;
}
if (p_options & FindOption::WholeWordOnly) {
findFlags |= QTextDocument::FindWholeWords;
}
// Use regular expression
bool useRegExp = false;
QRegExp exp;
if (p_options & FindOption::RegularExpression) {
useRegExp = true;
exp = QRegExp(p_text,
caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
}
int startPos = 0;
QTextCursor cursor;
QTextDocument *doc = document();
while (true) {
if (useRegExp) {
cursor = doc->find(exp, startPos, findFlags);
} else {
cursor = doc->find(p_text, startPos, findFlags);
}
if (cursor.isNull()) {
break;
} else {
results.append(cursor);
startPos = cursor.selectionEnd();
}
}
return results;
}
bool VEdit::findText(const QString &p_text, uint p_options, bool p_forward,
QTextCursor *p_cursor, QTextCursor::MoveMode p_moveMode)
{
clearIncrementalSearchedWordHighlight();
if (p_text.isEmpty()) {
clearSearchedWordHighlight();
return false;
}
QTextCursor cursor = textCursor();
bool wrapped = false;
QTextCursor retCursor;
int matches = 0;
int start = p_forward ? cursor.position() + 1 : cursor.position();
if (p_cursor) {
start = p_forward ? p_cursor->position() + 1 : p_cursor->position();
}
bool found = findTextHelper(p_text, p_options, p_forward, start,
wrapped, retCursor);
if (found) {
Q_ASSERT(!retCursor.isNull());
if (wrapped) {
showWrapLabel();
}
if (p_cursor) {
p_cursor->setPosition(retCursor.selectionStart(), p_moveMode);
} else {
cursor.setPosition(retCursor.selectionStart(), p_moveMode);
setTextCursor(cursor);
}
highlightSearchedWord(p_text, p_options);
highlightSearchedWordUnderCursor(retCursor);
matches = m_extraSelections[(int)SelectionId::SearchedKeyword].size();
} else {
clearSearchedWordHighlight();
}
if (matches == 0) {
statusMessage(tr("Found no match"));
} else {
statusMessage(tr("Found %1 %2").arg(matches)
.arg(matches > 1 ? tr("matches") : tr("match")));
}
return found;
}
void VEdit::replaceText(const QString &p_text, uint p_options,
const QString &p_replaceText, bool p_findNext)
{
QTextCursor cursor = textCursor();
bool wrapped = false;
QTextCursor retCursor;
bool found = findTextHelper(p_text, p_options, true,
cursor.position(), wrapped, retCursor);
if (found) {
if (retCursor.selectionStart() == cursor.position()) {
// Matched.
retCursor.beginEditBlock();
retCursor.insertText(p_replaceText);
retCursor.endEditBlock();
setTextCursor(retCursor);
}
if (p_findNext) {
findText(p_text, p_options, true);
}
}
}
void VEdit::replaceTextAll(const QString &p_text, uint p_options,
const QString &p_replaceText)
{
// Replace from the start to the end and restore the cursor.
QTextCursor cursor = textCursor();
int nrReplaces = 0;
QTextCursor tmpCursor = cursor;
tmpCursor.setPosition(0);
setTextCursor(tmpCursor);
int start = tmpCursor.position();
while (true) {
bool wrapped = false;
QTextCursor retCursor;
bool found = findTextHelper(p_text, p_options, true,
start, wrapped, retCursor);
if (!found) {
break;
} else {
if (wrapped) {
// Wrap back.
break;
}
nrReplaces++;
retCursor.beginEditBlock();
retCursor.insertText(p_replaceText);
retCursor.endEditBlock();
setTextCursor(retCursor);
start = retCursor.position();
}
}
// Restore cursor position.
cursor.clearSelection();
setTextCursor(cursor);
qDebug() << "replace all" << nrReplaces << "occurences";
emit statusMessage(tr("Replace %1 %2").arg(nrReplaces)
.arg(nrReplaces > 1 ? tr("occurences")
: tr("occurence")));
}
void VEdit::showWrapLabel()
{
int labelW = m_wrapLabel->width();
int labelH = m_wrapLabel->height();
int x = (width() - labelW) / 2;
int y = (height() - labelH) / 2;
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
m_wrapLabel->move(x, y);
m_wrapLabel->show();
m_labelTimer->stop();
m_labelTimer->start();
}
void VEdit::labelTimerTimeout()
{
m_wrapLabel->hide();
}
void VEdit::updateFontAndPalette()
{
setFont(g_config->getBaseEditFont());
setPalette(g_config->getBaseEditPalette());
}
void VEdit::highlightExtraSelections(bool p_now)
{
m_highlightTimer->stop();
if (p_now) {
doHighlightExtraSelections();
} else {
m_highlightTimer->start();
}
}
void VEdit::doHighlightExtraSelections()
{
int nrExtra = m_extraSelections.size();
Q_ASSERT(nrExtra == (int)SelectionId::MaxSelection);
QList<QTextEdit::ExtraSelection> extraSelects;
for (int i = 0; i < nrExtra; ++i) {
extraSelects.append(m_extraSelections[i]);
}
setExtraSelections(extraSelects);
}
void VEdit::highlightCurrentLine()
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::CurrentLine];
if (g_config->getHighlightCursorLine() && !isReadOnly()) {
// Need to highlight current line.
selects.clear();
// A long block maybe splited into multiple visual lines.
QTextEdit::ExtraSelection select;
select.format.setBackground(m_config.m_cursorLineBg);
select.format.setProperty(QTextFormat::FullWidthSelection, true);
QTextCursor cursor = textCursor();
if (m_config.m_highlightWholeBlock) {
cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor, 1);
QTextBlock block = cursor.block();
int blockEnd = block.position() + block.length();
int pos = -1;
while (cursor.position() < blockEnd && pos != cursor.position()) {
QTextEdit::ExtraSelection newSelect = select;
newSelect.cursor = cursor;
selects.append(newSelect);
pos = cursor.position();
cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, 1);
}
} else {
cursor.clearSelection();
select.cursor = cursor;
selects.append(select);
}
} else {
// Need to clear current line highlight.
if (selects.isEmpty()) {
return;
}
selects.clear();
}
highlightExtraSelections(true);
}
void VEdit::highlightSelectedWord()
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SelectedWord];
if (!g_config->getHighlightSelectedWord()) {
if (!selects.isEmpty()) {
selects.clear();
highlightExtraSelections(true);
}
return;
}
QString text = textCursor().selectedText().trimmed();
if (text.isEmpty() || wordInSearchedSelection(text)) {
selects.clear();
highlightExtraSelections(true);
return;
}
QTextCharFormat format;
format.setBackground(m_selectedWordColor);
highlightTextAll(text, FindOption::CaseSensitive, SelectionId::SelectedWord,
format);
}
// Do not highlight trailing spaces with current cursor right behind.
static void trailingSpaceFilter(VEdit *p_editor, QList<QTextEdit::ExtraSelection> &p_result)
{
QTextCursor cursor = p_editor->textCursor();
if (!cursor.atBlockEnd()) {
return;
}
int cursorPos = cursor.position();
for (auto it = p_result.begin(); it != p_result.end(); ++it) {
if (it->cursor.selectionEnd() == cursorPos) {
p_result.erase(it);
// There will be only one.
return;
}
}
}
void VEdit::highlightTrailingSpace()
{
if (!g_config->getEnableTrailingSpaceHighlight()) {
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::TrailingSpace];
if (!selects.isEmpty()) {
selects.clear();
highlightExtraSelections(true);
}
return;
}
QTextCharFormat format;
format.setBackground(m_trailingSpaceColor);
QString text("\\s+$");
highlightTextAll(text, FindOption::RegularExpression,
SelectionId::TrailingSpace, format,
trailingSpaceFilter);
}
bool VEdit::wordInSearchedSelection(const QString &p_text)
{
QString text = p_text.trimmed();
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword];
for (int i = 0; i < selects.size(); ++i) {
QString searchedWord = selects[i].cursor.selectedText();
if (text == searchedWord.trimmed()) {
return true;
}
}
return false;
}
void VEdit::highlightTextAll(const QString &p_text, uint p_options,
SelectionId p_id, QTextCharFormat p_format,
void (*p_filter)(VEdit *, QList<QTextEdit::ExtraSelection> &))
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)p_id];
if (!p_text.isEmpty()) {
selects.clear();
QList<QTextCursor> occurs = findTextAll(p_text, p_options);
for (int i = 0; i < occurs.size(); ++i) {
QTextEdit::ExtraSelection select;
select.format = p_format;
select.cursor = occurs[i];
selects.append(select);
}
} else {
if (selects.isEmpty()) {
return;
}
selects.clear();
}
if (p_filter) {
p_filter(this, selects);
}
highlightExtraSelections();
}
void VEdit::highlightSearchedWord(const QString &p_text, uint p_options)
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword];
if (!g_config->getHighlightSearchedWord() || p_text.isEmpty()) {
if (!selects.isEmpty()) {
selects.clear();
highlightExtraSelections(true);
}
return;
}
QTextCharFormat format;
format.setBackground(m_searchedWordColor);
highlightTextAll(p_text, p_options, SelectionId::SearchedKeyword, format);
}
void VEdit::highlightSearchedWordUnderCursor(const QTextCursor &p_cursor)
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor];
if (!p_cursor.hasSelection()) {
if (!selects.isEmpty()) {
selects.clear();
highlightExtraSelections(true);
}
return;
}
selects.clear();
QTextEdit::ExtraSelection select;
select.format.setBackground(m_searchedWordCursorColor);
select.cursor = p_cursor;
selects.append(select);
highlightExtraSelections(true);
}
void VEdit::highlightIncrementalSearchedWord(const QTextCursor &p_cursor)
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword];
if (!g_config->getHighlightSearchedWord() || !p_cursor.hasSelection()) {
if (!selects.isEmpty()) {
selects.clear();
highlightExtraSelections(true);
}
return;
}
selects.clear();
QTextEdit::ExtraSelection select;
select.format.setBackground(m_incrementalSearchedWordColor);
select.cursor = p_cursor;
selects.append(select);
highlightExtraSelections(true);
}
void VEdit::clearSearchedWordHighlight()
{
clearIncrementalSearchedWordHighlight(false);
clearSearchedWordUnderCursorHighlight(false);
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeyword];
if (selects.isEmpty()) {
return;
}
selects.clear();
highlightExtraSelections(true);
}
void VEdit::clearSearchedWordUnderCursorHighlight(bool p_now)
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::SearchedKeywordUnderCursor];
if (selects.isEmpty()) {
return;
}
selects.clear();
highlightExtraSelections(p_now);
}
void VEdit::clearIncrementalSearchedWordHighlight(bool p_now)
{
QList<QTextEdit::ExtraSelection> &selects = m_extraSelections[(int)SelectionId::IncrementalSearchedKeyword];
if (selects.isEmpty()) {
return;
}
selects.clear();
highlightExtraSelections(p_now);
}
void VEdit::contextMenuEvent(QContextMenuEvent *p_event)
{
QMenu *menu = createStandardContextMenu();
menu->setToolTipsVisible(true);
const QList<QAction *> actions = menu->actions();
if (!textCursor().hasSelection()) {
VEditTab *editTab = dynamic_cast<VEditTab *>(parent());
V_ASSERT(editTab);
if (editTab->isEditMode()) {
QAction *saveExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/save_exit.svg"),
tr("&Save Changes And Read"), this);
saveExitAct->setToolTip(tr("Save changes and exit edit mode"));
connect(saveExitAct, &QAction::triggered,
this, &VEdit::handleSaveExitAct);
QAction *discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"),
tr("&Discard Changes And Read"), this);
discardExitAct->setToolTip(tr("Discard changes and exit edit mode"));
connect(discardExitAct, &QAction::triggered,
this, &VEdit::handleDiscardExitAct);
menu->insertAction(actions.isEmpty() ? NULL : actions[0], discardExitAct);
menu->insertAction(discardExitAct, saveExitAct);
if (!actions.isEmpty()) {
menu->insertSeparator(actions[0]);
}
} else if (m_file->isModifiable()) {
// HTML.
QAction *editAct= new QAction(VIconUtils::menuIcon(":/resources/icons/edit_note.svg"),
tr("&Edit"), this);
editAct->setToolTip(tr("Edit current note"));
connect(editAct, &QAction::triggered,
this, &VEdit::handleEditAct);
menu->insertAction(actions.isEmpty() ? NULL : actions[0], editAct);
// actions does not contain editAction.
if (!actions.isEmpty()) {
menu->insertSeparator(actions[0]);
}
}
}
alterContextMenu(menu, actions);
menu->exec(p_event->globalPos());
delete menu;
}
void VEdit::handleSaveExitAct()
{
emit saveAndRead();
}
void VEdit::handleDiscardExitAct()
{
emit discardAndRead();
}
void VEdit::handleEditAct()
{
emit editNote();
}
VFile *VEdit::getFile() const
{
return m_file;
}
void VEdit::handleCursorPositionChanged()
{
static QTextCursor lastCursor;
QTextCursor cursor = textCursor();
if (lastCursor.isNull() || cursor.blockNumber() != lastCursor.blockNumber()) {
highlightCurrentLine();
highlightTrailingSpace();
} else {
// Judge whether we have trailing space at current line.
QString text = cursor.block().text();
if (text.rbegin()->isSpace()) {
highlightTrailingSpace();
}
// Handle word-wrap in one block.
// Highlight current line if in different visual line.
if ((lastCursor.positionInBlock() - lastCursor.columnNumber()) !=
(cursor.positionInBlock() - cursor.columnNumber())) {
highlightCurrentLine();
}
}
lastCursor = cursor;
}
VEditConfig &VEdit::getConfig()
{
return m_config;
}
void VEdit::mousePressEvent(QMouseEvent *p_event)
{
if (p_event->button() == Qt::LeftButton
&& p_event->modifiers() == Qt::ControlModifier
&& !textCursor().hasSelection()) {
m_oriMouseX = p_event->x();
m_oriMouseY = p_event->y();
m_readyToScroll = true;
m_mouseMoveScrolled = false;
p_event->accept();
return;
}
m_readyToScroll = false;
m_mouseMoveScrolled = false;
QTextEdit::mousePressEvent(p_event);
emit selectionChangedByMouse(textCursor().hasSelection());
}
void VEdit::mouseReleaseEvent(QMouseEvent *p_event)
{
if (m_mouseMoveScrolled || m_readyToScroll) {
viewport()->setCursor(Qt::IBeamCursor);
m_readyToScroll = false;
m_mouseMoveScrolled = false;
p_event->accept();
return;
}
m_readyToScroll = false;
m_mouseMoveScrolled = false;
QTextEdit::mouseReleaseEvent(p_event);
}
void VEdit::mouseMoveEvent(QMouseEvent *p_event)
{
const int threshold = 5;
if (m_readyToScroll) {
int deltaX = p_event->x() - m_oriMouseX;
int deltaY = p_event->y() - m_oriMouseY;
if (qAbs(deltaX) >= threshold || qAbs(deltaY) >= threshold) {
m_oriMouseX = p_event->x();
m_oriMouseY = p_event->y();
if (!m_mouseMoveScrolled) {
m_mouseMoveScrolled = true;
viewport()->setCursor(Qt::SizeAllCursor);
}
QScrollBar *verBar = verticalScrollBar();
QScrollBar *horBar = horizontalScrollBar();
if (verBar->isVisible()) {
verBar->setValue(verBar->value() - deltaY);
}
if (horBar->isVisible()) {
horBar->setValue(horBar->value() - deltaX);
}
}
p_event->accept();
return;
}
QTextEdit::mouseMoveEvent(p_event);
emit selectionChangedByMouse(textCursor().hasSelection());
}
void VEdit::requestUpdateVimStatus()
{
if (m_editOps) {
m_editOps->requestUpdateVimStatus();
} else {
emit vimStatusUpdated(NULL);
}
}
bool VEdit::jumpTitle(bool p_forward, int p_relativeLevel, int p_repeat)
{
Q_UNUSED(p_forward);
Q_UNUSED(p_relativeLevel);
Q_UNUSED(p_repeat);
return false;
}
QVariant VEdit::inputMethodQuery(Qt::InputMethodQuery p_query) const
{
if (p_query == Qt::ImEnabled) {
return m_enableInputMethod;
}
return QTextEdit::inputMethodQuery(p_query);
}
void VEdit::setInputMethodEnabled(bool p_enabled)
{
if (m_enableInputMethod != p_enabled) {
m_enableInputMethod = p_enabled;
QInputMethod *im = QGuiApplication::inputMethod();
im->reset();
// Ask input method to query current state, which will call inputMethodQuery().
im->update(Qt::ImEnabled);
}
}
void VEdit::decorateText(TextDecoration p_decoration)
{
if (m_editOps) {
m_editOps->decorateText(p_decoration);
}
}
void VEdit::updateLineNumberAreaMargin()
{
int width = 0;
if (g_config->getEditorLineNumber()) {
width = m_lineNumberArea->calculateWidth();
}
setViewportMargins(width, 0, 0, 0);
}
void VEdit::updateLineNumberArea()
{
if (g_config->getEditorLineNumber()) {
if (!m_lineNumberArea->isVisible()) {
updateLineNumberAreaMargin();
m_lineNumberArea->show();
}
m_lineNumberArea->update();
} else if (m_lineNumberArea->isVisible()) {
updateLineNumberAreaMargin();
m_lineNumberArea->hide();
}
}
void VEdit::resizeEvent(QResizeEvent *p_event)
{
QTextEdit::resizeEvent(p_event);
if (g_config->getEditorLineNumber()) {
QRect rect = contentsRect();
m_lineNumberArea->setGeometry(QRect(rect.left(),
rect.top(),
m_lineNumberArea->calculateWidth(),
rect.height()));
}
}
void VEdit::lineNumberAreaPaintEvent(QPaintEvent *p_event)
{
int lineNumberType = g_config->getEditorLineNumber();
if (!lineNumberType) {
updateLineNumberAreaMargin();
m_lineNumberArea->hide();
return;
}
QPainter painter(m_lineNumberArea);
painter.fillRect(p_event->rect(), g_config->getEditorLineNumberBg());
QAbstractTextDocumentLayout *layout = document()->documentLayout();
QTextBlock block = firstVisibleBlock();
if (!block.isValid()) {
return;
}
int blockNumber = block.blockNumber();
int offsetY = contentOffsetY();
QRectF rect = layout->blockBoundingRect(block);
int top = offsetY + (int)rect.y();
int bottom = top + (int)rect.height();
int eventTop = p_event->rect().top();
int eventBtm = p_event->rect().bottom();
const int digitHeight = m_lineNumberArea->getDigitHeight();
const int curBlockNumber = textCursor().block().blockNumber();
const QString &fg = g_config->getEditorLineNumberFg();
const int lineDistanceHeight = m_config.m_lineDistanceHeight;
painter.setPen(fg);
// Display line number only in code block.
if (lineNumberType == 3) {
if (m_file->getDocType() != DocType::Markdown) {
return;
}
int number = 0;
while (block.isValid() && top <= eventBtm) {
int blockState = block.userState();
switch (blockState) {
case HighlightBlockState::CodeBlockStart:
Q_ASSERT(number == 0);
number = 1;
break;
case HighlightBlockState::CodeBlockEnd:
number = 0;
break;
case HighlightBlockState::CodeBlock:
if (number == 0) {
// Need to find current line number in code block.
QTextBlock startBlock = block.previous();
while (startBlock.isValid()) {
if (startBlock.userState() == HighlightBlockState::CodeBlockStart) {
number = block.blockNumber() - startBlock.blockNumber();
break;
}
startBlock = startBlock.previous();
}
}
break;
default:
break;
}
if (blockState == HighlightBlockState::CodeBlock) {
if (block.isVisible() && bottom >= eventTop) {
QString numberStr = QString::number(number);
painter.drawText(0,
top + 2,
m_lineNumberArea->width(),
digitHeight,
Qt::AlignRight,
numberStr);
}
++number;
}
block = block.next();
top = bottom;
bottom = top + (int)layout->blockBoundingRect(block).height() + lineDistanceHeight;
}
return;
}
// Handle lineNumberType 1 and 2.
Q_ASSERT(lineNumberType == 1 || lineNumberType == 2);
while (block.isValid() && top <= eventBtm) {
if (block.isVisible() && bottom >= eventTop) {
bool currentLine = false;
int number = blockNumber + 1;
if (lineNumberType == 2) {
number = blockNumber - curBlockNumber;
if (number == 0) {
currentLine = true;
number = blockNumber + 1;
} else if (number < 0) {
number = -number;
}
} else if (blockNumber == curBlockNumber) {
currentLine = true;
}
QString numberStr = QString::number(number);
if (currentLine) {
QFont font = painter.font();
font.setBold(true);
painter.setFont(font);
}
painter.drawText(0,
top + 2,
m_lineNumberArea->width(),
digitHeight,
Qt::AlignRight,
numberStr);
if (currentLine) {
QFont font = painter.font();
font.setBold(false);
painter.setFont(font);
}
}
block = block.next();
top = bottom;
bottom = top + (int)layout->blockBoundingRect(block).height() + lineDistanceHeight;
++blockNumber;
}
}
int VEdit::contentOffsetY()
{
int offsety = 0;
QScrollBar *sb = verticalScrollBar();
offsety = sb->value();
return -offsety;
}
QTextBlock VEdit::firstVisibleBlock()
{
QTextDocument *doc = document();
QAbstractTextDocumentLayout *layout = doc->documentLayout();
int offsetY = contentOffsetY();
// Binary search.
int idx = -1;
int start = 0, end = doc->blockCount() - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
QTextBlock block = doc->findBlockByNumber(mid);
if (!block.isValid()) {
break;
}
int y = offsetY + (int)layout->blockBoundingRect(block).y();
if (y == 0) {
return block;
} else if (y < 0) {
start = mid + 1;
} else {
if (idx == -1 || mid < idx) {
idx = mid;
}
end = mid - 1;
}
}
if (idx != -1) {
return doc->findBlockByNumber(idx);
}
// Linear search.
qDebug() << "fall back to linear search for first visible block";
QTextBlock block = doc->begin();
while (block.isValid()) {
int y = offsetY + (int)layout->blockBoundingRect(block).y();
if (y >= 0) {
return block;
}
block = block.next();
}
return QTextBlock();
}
int LineNumberArea::calculateWidth() const
{
int bc = m_document->blockCount();
if (m_blockCount == bc) {
return m_width;
}
const_cast<LineNumberArea *>(this)->m_blockCount = bc;
int digits = 1;
int max = qMax(1, m_blockCount);
while (max >= 10) {
max /= 10;
++digits;
}
int width = m_digitWidth * digits;
const_cast<LineNumberArea *>(this)->m_width = width;
return m_width;
}
void VEdit::makeBlockVisible(const QTextBlock &p_block)
{
if (!p_block.isValid() || !p_block.isVisible()) {
return;
}
QScrollBar *vbar = verticalScrollBar();
if (!vbar || !vbar->isVisible()) {
// No vertical scrollbar. No need to scroll.
return;
}
QAbstractTextDocumentLayout *layout = document()->documentLayout();
int height = rect().height();
QScrollBar *hbar = horizontalScrollBar();
if (hbar && hbar->isVisible()) {
height -= hbar->height();
}
bool moved = false;
QRectF rect = layout->blockBoundingRect(p_block);
int y = contentOffsetY() + (int)rect.y();
int rectHeight = (int)rect.height();
// Handle the case rectHeight >= height.
if (rectHeight >= height) {
if (y <= 0) {
if (y + rectHeight < height) {
// Need to scroll up.
while (y + rectHeight < height && vbar->value() > vbar->minimum()) {
moved = true;
vbar->setValue(vbar->value() - vbar->singleStep());
rect = layout->blockBoundingRect(p_block);
rectHeight = (int)rect.height();
y = contentOffsetY() + (int)rect.y();
}
}
} else {
// Need to scroll down.
while (y > 0 && vbar->value() < vbar->maximum()) {
moved = true;
vbar->setValue(vbar->value() + vbar->singleStep());
rect = layout->blockBoundingRect(p_block);
rectHeight = (int)rect.height();
y = contentOffsetY() + (int)rect.y();
}
}
if (moved) {
qDebug() << "scroll to make huge block visible";
}
return;
}
while (y < 0 && vbar->value() > vbar->minimum()) {
moved = true;
vbar->setValue(vbar->value() - vbar->singleStep());
rect = layout->blockBoundingRect(p_block);
rectHeight = (int)rect.height();
y = contentOffsetY() + (int)rect.y();
}
if (moved) {
qDebug() << "scroll page down to make block visible";
return;
}
while (y + rectHeight > height && vbar->value() < vbar->maximum()) {
moved = true;
vbar->setValue(vbar->value() + vbar->singleStep());
rect = layout->blockBoundingRect(p_block);
rectHeight = (int)rect.height();
y = contentOffsetY() + (int)rect.y();
}
if (moved) {
qDebug() << "scroll page up to make block visible";
}
}
bool VEdit::isBlockVisible(const QTextBlock &p_block)
{
if (!p_block.isValid() || !p_block.isVisible()) {
return false;
}
QScrollBar *vbar = verticalScrollBar();
if (!vbar || !vbar->isVisible()) {
// No vertical scrollbar.
return true;
}
QAbstractTextDocumentLayout *layout = document()->documentLayout();
int height = rect().height();
QScrollBar *hbar = horizontalScrollBar();
if (hbar && hbar->isVisible()) {
height -= hbar->height();
}
QRectF rect = layout->blockBoundingRect(p_block);
int y = contentOffsetY() + (int)rect.y();
int rectHeight = (int)rect.height();
return (y >= 0 && y < height) || (y < 0 && y + rectHeight > 0);
}
void VEdit::alterContextMenu(QMenu *p_menu, const QList<QAction *> &p_actions)
{
Q_UNUSED(p_menu);
Q_UNUSED(p_actions);
}
void VEdit::updateBlockLineDistanceHeight(int p_pos,
int p_charsRemoved,
int p_charsAdded)
{
if ((p_charsRemoved == 0 && p_charsAdded == 0)
|| m_config.m_lineDistanceHeight <= 0) {
return;
}
QTextDocument *doc = document();
QTextBlock block = doc->findBlock(p_pos);
QTextBlock lastBlock = doc->findBlock(p_pos + p_charsRemoved + p_charsAdded);
QTextCursor cursor(block);
bool changed = false;
while (block.isValid()) {
cursor.setPosition(block.position());
QTextBlockFormat fmt = cursor.blockFormat();
if (fmt.lineHeightType() != QTextBlockFormat::LineDistanceHeight
|| fmt.lineHeight() != m_config.m_lineDistanceHeight) {
fmt.setLineHeight(m_config.m_lineDistanceHeight,
QTextBlockFormat::LineDistanceHeight);
if (!changed) {
changed = true;
cursor.joinPreviousEditBlock();
}
cursor.mergeBlockFormat(fmt);
qDebug() << "merge block format line distance" << block.blockNumber();
}
if (block == lastBlock) {
break;
}
block = block.next();
}
if (changed) {
cursor.endEditBlock();
}
}
void VEdit::evaluateMagicWords()
{
QString text;
QTextCursor cursor = textCursor();
if (!cursor.hasSelection()) {
// Get the WORD in current cursor.
int start, end;
VEditUtils::findCurrentWORD(cursor, start, end);
if (start == end) {
return;
} else {
cursor.setPosition(start);
cursor.setPosition(end, QTextCursor::KeepAnchor);
}
}
text = VEditUtils::selectedText(cursor);
Q_ASSERT(!text.isEmpty());
QString evaText = g_mwMgr->evaluate(text);
if (text != evaText) {
qDebug() << "evaluateMagicWords" << text << evaText;
cursor.insertText(evaText);
if (m_editOps) {
m_editOps->setVimMode(VimMode::Insert);
}
setTextCursor(cursor);
}
}
void VEdit::setReadOnlyAndHighlight(bool p_readonly)
{
setReadOnly(p_readonly);
highlightCurrentLine();
}
| 28.615815
| 112
| 0.58092
|
linails
|
f4f2b945b1685e17693494aed5602c18ef01f341
| 5,812
|
cxx
|
C++
|
Modules/Filtering/FFT/test/itkForwardInverseFFTImageFilterTest.cxx
|
floryst/ITK
|
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
|
[
"Apache-2.0"
] | 1
|
2020-10-09T18:12:53.000Z
|
2020-10-09T18:12:53.000Z
|
Modules/Filtering/FFT/test/itkForwardInverseFFTImageFilterTest.cxx
|
floryst/ITK
|
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
|
[
"Apache-2.0"
] | 1
|
2018-10-18T18:49:19.000Z
|
2018-10-18T18:49:19.000Z
|
Modules/Filtering/FFT/test/itkForwardInverseFFTImageFilterTest.cxx
|
floryst/ITK
|
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
|
[
"Apache-2.0"
] | 1
|
2020-10-13T07:24:57.000Z
|
2020-10-13T07:24:57.000Z
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkVnlForwardFFTImageFilter.h"
#include "itkVnlInverseFFTImageFilter.h"
#include "itkVnlRealToHalfHermitianForwardFFTImageFilter.h"
#include "itkVnlHalfHermitianToRealInverseFFTImageFilter.h"
#if defined(ITK_USE_FFTWF) || defined(ITK_USE_FFTWD)
#include "itkFFTWForwardFFTImageFilter.h"
#include "itkFFTWInverseFFTImageFilter.h"
#include "itkFFTWRealToHalfHermitianForwardFFTImageFilter.h"
#include "itkFFTWHalfHermitianToRealInverseFFTImageFilter.h"
#endif
#include "itkForwardInverseFFTTest.h"
int itkForwardInverseFFTImageFilterTest(int argc, char* argv[])
{
if ( argc < 2 )
{
std::cout << "Usage: " << argv[0] << " <input file> " << std::endl;
return EXIT_FAILURE;
}
constexpr unsigned int Dimension = 2;
using FloatType = float;
using DoubleType = double;
using FloatImageType = itk::Image< FloatType, Dimension >;
using DoubleImageType = itk::Image< DoubleType, Dimension >;
bool success = true;
using FloatVnlFullFFTType = itk::VnlForwardFFTImageFilter<FloatImageType>;
using FloatVnlFullIFFTType = itk::VnlInverseFFTImageFilter<FloatVnlFullFFTType::OutputImageType>;
if ( !ForwardInverseFullFFTTest< FloatVnlFullFFTType, FloatVnlFullIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for FloatVnlFullFFTType" << std::endl;
}
else
{
std::cout << "Test passed for FloatVnlFullFFTType" << std::endl;
}
using DoubleVnlFullFFTType = itk::VnlForwardFFTImageFilter<DoubleImageType>;
using DoubleVnlFullIFFTType = itk::VnlInverseFFTImageFilter<DoubleVnlFullFFTType::OutputImageType>;
if ( !ForwardInverseFullFFTTest< DoubleVnlFullFFTType, DoubleVnlFullIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for DoubleVnlFullFFTType" << std::endl;
}
else
{
std::cout << "Test passed for DoubleVnlFullFFTType" << std::endl;
}
#if defined(ITK_USE_FFTWF)
using FloatFFTWFullFFTType = itk::FFTWForwardFFTImageFilter<FloatImageType>;
using FloatFFTWFullIFFTType = itk::FFTWInverseFFTImageFilter<FloatFFTWFullFFTType::OutputImageType>;
if ( !ForwardInverseFullFFTTest< FloatFFTWFullFFTType, FloatFFTWFullIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for FloatFFTWFullFFTType" << std::endl;
}
else
{
std::cout << "Test passed for FloatFFTWFullFFTType" << std::endl;
}
#endif
#if defined(ITK_USE_FFTWD)
using DoubleFFTWFullFFTType = itk::FFTWForwardFFTImageFilter<DoubleImageType>;
using DoubleFFTWFullIFFTType = itk::FFTWInverseFFTImageFilter<DoubleFFTWFullFFTType::OutputImageType>;
if ( !ForwardInverseFullFFTTest< DoubleFFTWFullFFTType, DoubleFFTWFullIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for DoubleFFTWFullFFTType" << std::endl;
}
else
{
std::cout << "Test passed for DoubleFFTWFullFFTType" << std::endl;
}
#endif
using FloatVnlHalfFFTType = itk::VnlRealToHalfHermitianForwardFFTImageFilter<FloatImageType>;
using FloatVnlHalfIFFTType = itk::VnlHalfHermitianToRealInverseFFTImageFilter<FloatVnlHalfFFTType::OutputImageType>;
if ( !ForwardInverseHalfFFTTest< FloatVnlHalfFFTType, FloatVnlHalfIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for FloatVnlHalfFFTType" << std::endl;
}
else
{
std::cout << "Test passed for FloatVnlHalfFFTType" << std::endl;
}
using DoubleVnlHalfFFTType = itk::VnlRealToHalfHermitianForwardFFTImageFilter<DoubleImageType>;
using DoubleVnlHalfIFFTType = itk::VnlHalfHermitianToRealInverseFFTImageFilter<DoubleVnlHalfFFTType::OutputImageType>;
if ( !ForwardInverseHalfFFTTest< DoubleVnlHalfFFTType, DoubleVnlHalfIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for DoubleVnlHalfFFTType" << std::endl;
}
else
{
std::cout << "Test passed for DoubleVnlHalfFFTType" << std::endl;
}
#if defined(ITK_USE_FFTWF)
using FloatFFTWHalfFFTType = itk::FFTWRealToHalfHermitianForwardFFTImageFilter<FloatImageType>;
using FloatFFTWHalfIFFTType = itk::FFTWHalfHermitianToRealInverseFFTImageFilter<FloatFFTWHalfFFTType::OutputImageType>;
if ( !ForwardInverseHalfFFTTest< FloatFFTWHalfFFTType, FloatFFTWHalfIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for FloatFFTWHalfFFTType" << std::endl;
}
else
{
std::cout << "Test passed for FloatFFTWHalfFFTType" << std::endl;
}
#endif
#if defined(ITK_USE_FFTWD)
using DoubleFFTWHalfFFTType = itk::FFTWRealToHalfHermitianForwardFFTImageFilter<DoubleImageType>;
using DoubleFFTWHalfIFFTType = itk::FFTWHalfHermitianToRealInverseFFTImageFilter<DoubleFFTWHalfFFTType::OutputImageType>;
if ( !ForwardInverseHalfFFTTest< DoubleFFTWHalfFFTType, DoubleFFTWHalfIFFTType >( argv[1] ) )
{
success = false;
std::cerr << "Test failed for DoubleFFTWHalfFFTType" << std::endl;
}
else
{
std::cout << "Test passed for DoubleFFTWHalfFFTType" << std::endl;
}
#endif
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 37.25641
| 123
| 0.720062
|
floryst
|
f4f8b3ded57685503b36f0e9542b3f5210036b25
| 34,267
|
cpp
|
C++
|
multimedia/dshow/filters/inftee/inftee.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
multimedia/dshow/filters/inftee/inftee.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
multimedia/dshow/filters/inftee/inftee.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//==========================================================================;
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//
// Copyright (c) 1992 - 1998 Microsoft Corporation. All Rights Reserved.
//
//--------------------------------------------------------------------------;
#include <streams.h>
#include <initguid.h>
#include <inftee.h>
#include <tchar.h>
#include <stdio.h>
//
//
// What this sample illustrates
//
// A pass through filter splits a data stream into many output channels
//
// Summary
//
// This is a sample ActiveMovie pass through filter. We have a single input
// pin and can have many output pins. We start with one output pin and each
// time we connect an output pin we spawn another, although we could keep
// doing this ad infinitum we have a top level maximum of INFTEE_MAX_PINS.
// Any data samples our input pin receives will be sent down each output
// pin in turn. Each output pin has a separate thread if necessary (see
// the output queue class in the SDK) to avoid delivery blocking our thread
//
// Demonstration instructions
//
// Start GRAPHEDT available in the ActiveMovie SDK tools. Drag and drop any
// MPEG, AVI or MOV file into the tool and it will be rendered. Then go to
// the filters in the graph and find the filter (box) titled "Video Renderer"
// Then click on the box and hit DELETE. After that go to the Graph menu and
// select "Insert Filters", from the dialog box find and select the "Infinite
// Tee Filter" and then dismiss the dialog. Back in the graph layout find the
// output pin of the filter that was connected to the input of the video
// renderer you just deleted, right click and select "Render". You should
// see it being connected to the input pin of the filter you just inserted
//
// The infinite tee filter will have one output pin connected and will have
// spawned another, right click on this and select Render. A new renderer
// will pop up fo the stream. Do this once or twice more and then click on
// the Pause and Run on the GRAPHEDT frame and you will see the video...
// .. many times over in different windows
//
// Files
//
// inftee.cpp Main implementation of the infinite tee
// inftee.def What APIs the DLL will import and export
// inftee.h Class definition of the infinite tee
// inftee.rc Not much, just our version information
// inftee.reg What goes in the registry to make us work
// makefile How to build it...
//
//
// Base classes used
//
// CBaseInputPin Basic IMemInputPin based input pin
// CBaseOutputPin Used for basic connection stuff
// CBaseFilter Well we need a filter don't we
// CCritSec Controls access to output pin list
// COutputQueue Delivers data on a separate thread
//
//
#define INFTEE_MAX_PINS 1000
// Using this pointer in constructor
#pragma warning(disable:4355)
// Setup data
const AMOVIESETUP_MEDIATYPE sudPinTypes =
{
&MEDIATYPE_NULL, // Major CLSID
&MEDIASUBTYPE_NULL // Minor type
};
const AMOVIESETUP_PIN psudPins[] =
{
{ L"Input", // Pin's string name
FALSE, // Is it rendered
FALSE, // Is it an output
FALSE, // Allowed none
FALSE, // Allowed many
&CLSID_NULL, // Connects to filter
L"Output", // Connects to pin
1, // Number of types
&sudPinTypes }, // Pin information
{ L"Output", // Pin's string name
FALSE, // Is it rendered
TRUE, // Is it an output
FALSE, // Allowed none
FALSE, // Allowed many
&CLSID_NULL, // Connects to filter
L"Input", // Connects to pin
1, // Number of types
&sudPinTypes } // Pin information
};
const AMOVIESETUP_FILTER sudInfTee =
{
&CLSID_InfTee, // CLSID of filter
L"Infinite Pin Tee Filter", // Filter's name
MERIT_DO_NOT_USE, // Filter merit
2, // Number of pins
psudPins // Pin information
};
#ifdef FILTER_DLL
CFactoryTemplate g_Templates [1] = {
{ L"Infinite Pin Tee"
, &CLSID_InfTee
, CTee::CreateInstance
, NULL
, &sudInfTee }
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);
//
// DllRegisterServer
//
STDAPI DllRegisterServer()
{
return AMovieDllRegisterServer2( TRUE );
}
//
// DllUnregisterServer
//
STDAPI
DllUnregisterServer()
{
return AMovieDllRegisterServer2( FALSE );
}
#endif
//
// CreateInstance
//
// Creator function for the class ID
//
CUnknown * WINAPI CTee::CreateInstance(LPUNKNOWN pUnk, HRESULT *phr)
{
return new CTee(NAME("Infinite Tee Filter"), pUnk, phr);
}
//
// Constructor
//
CTee::CTee(TCHAR *pName, LPUNKNOWN pUnk, HRESULT *phr) :
m_OutputPinsList(NAME("Tee Output Pins list")),
m_lCanSeek(TRUE),
m_pAllocator(NULL),
m_NumOutputPins(0),
m_NextOutputPinNumber(0),
m_Input(NAME("Input Pin"), this, phr, L"Input"),
CBaseFilter(NAME("Tee filter"), pUnk, this, CLSID_InfTee)
{
ASSERT(phr);
// Create a single output pin at this time
InitOutputPinsList();
CTeeOutputPin *pOutputPin = CreateNextOutputPin(this);
if (pOutputPin != NULL )
{
m_NumOutputPins++;
m_OutputPinsList.AddTail(pOutputPin);
}
}
//
// Destructor
//
CTee::~CTee()
{
InitOutputPinsList();
}
//
// GetPinCount
//
int CTee::GetPinCount()
{
return (1 + m_NumOutputPins);
}
//
// GetPin
//
CBasePin *CTee::GetPin(int n)
{
if (n < 0)
return NULL ;
// Pin zero is the one and only input pin
if (n == 0)
return &m_Input;
// return the output pin at position(n - 1) (zero based)
return GetPinNFromList(n - 1);
}
//
// InitOutputPinsList
//
void CTee::InitOutputPinsList()
{
POSITION pos = m_OutputPinsList.GetHeadPosition();
while(pos)
{
CTeeOutputPin *pOutputPin = m_OutputPinsList.GetNext(pos);
ASSERT(pOutputPin->m_pOutputQueue == NULL);
pOutputPin->Release();
}
m_NumOutputPins = 0;
m_OutputPinsList.RemoveAll();
} // InitOutputPinsList
//
// CreateNextOutputPin
//
CTeeOutputPin *CTee::CreateNextOutputPin(CTee *pTee)
{
WCHAR szbuf[20]; // Temporary scratch buffer
m_NextOutputPinNumber++; // Next number to use for pin
HRESULT hr = NOERROR;
wsprintfW(szbuf, L"Output%d", m_NextOutputPinNumber);
CTeeOutputPin *pPin = new CTeeOutputPin(NAME("Tee Output"), pTee,
&hr, szbuf,
m_NextOutputPinNumber);
if (FAILED(hr) || pPin == NULL) {
delete pPin;
return NULL;
}
pPin->AddRef();
return pPin;
} // CreateNextOutputPin
//
// DeleteOutputPin
//
void CTee::DeleteOutputPin(CTeeOutputPin *pPin)
{
POSITION pos = m_OutputPinsList.GetHeadPosition();
while(pos) {
POSITION posold = pos; // Remember this position
CTeeOutputPin *pOutputPin = m_OutputPinsList.GetNext(pos);
if (pOutputPin == pPin) {
// If this pin holds the seek interface release it
if (pPin->m_bHoldsSeek) {
InterlockedExchange(&m_lCanSeek, FALSE);
pPin->m_bHoldsSeek = FALSE;
pPin->m_pPosition->Release();
}
m_OutputPinsList.Remove(posold);
ASSERT(pOutputPin->m_pOutputQueue == NULL);
delete pPin;
m_NumOutputPins--;
IncrementPinVersion();
break;
}
}
} // DeleteOutputPin
//
// GetNumFreePins
//
int CTee::GetNumFreePins()
{
int n = 0;
POSITION pos = m_OutputPinsList.GetHeadPosition();
while(pos) {
CTeeOutputPin *pOutputPin = m_OutputPinsList.GetNext(pos);
if (pOutputPin->m_Connected == NULL)
n++;
}
return n;
} // GetNumFreePins
//
// GetPinNFromList
//
CTeeOutputPin *CTee::GetPinNFromList(int n)
{
// Validate the position being asked for
if (n >= m_NumOutputPins)
return NULL;
// Get the head of the list
POSITION pos = m_OutputPinsList.GetHeadPosition();
n++; // Make the number 1 based
CTeeOutputPin *pOutputPin;
while(n) {
pOutputPin = m_OutputPinsList.GetNext(pos);
n--;
}
return pOutputPin;
} // GetPinNFromList
//
// Stop
//
// Overriden to handle no input connections
//
STDMETHODIMP CTee::Stop()
{
CBaseFilter::Stop();
m_State = State_Stopped;
return NOERROR;
}
//
// Pause
//
// Overriden to handle no input connections
//
STDMETHODIMP CTee::Pause()
{
CAutoLock cObjectLock(m_pLock);
HRESULT hr = CBaseFilter::Pause();
if (m_Input.IsConnected() == FALSE) {
m_Input.EndOfStream();
}
return hr;
}
//
// Run
//
// Overriden to handle no input connections
//
STDMETHODIMP CTee::Run(REFERENCE_TIME tStart)
{
CAutoLock cObjectLock(m_pLock);
HRESULT hr = CBaseFilter::Run(tStart);
if (m_Input.IsConnected() == FALSE) {
m_Input.EndOfStream();
}
return hr;
}
//
// CTeeInputPin constructor
//
CTeeInputPin::CTeeInputPin(TCHAR *pName,
CTee *pTee,
HRESULT *phr,
LPCWSTR pPinName) :
CBaseInputPin(pName, pTee, pTee, phr, pPinName),
m_pTee(pTee),
m_bInsideCheckMediaType(FALSE)
{
ASSERT(pTee);
}
#ifdef DEBUG
//
// CTeeInputPin destructor
//
CTeeInputPin::~CTeeInputPin()
{
DbgLog((LOG_TRACE,2,TEXT("CTeeInputPin destructor")));
ASSERT(m_pTee->m_pAllocator == NULL);
}
#endif
#ifdef DEBUG
//
// DisplayMediaType -- (DEBUG ONLY)
//
void DisplayMediaType(TCHAR *pDescription,const CMediaType *pmt)
{
// Dump the GUID types and a short description
DbgLog((LOG_TRACE,2,TEXT("")));
DbgLog((LOG_TRACE,2,TEXT("%s"),pDescription));
DbgLog((LOG_TRACE,2,TEXT("")));
DbgLog((LOG_TRACE,2,TEXT("Media Type Description")));
DbgLog((LOG_TRACE,2,TEXT("Major type %s"),GuidNames[*pmt->Type()]));
DbgLog((LOG_TRACE,2,TEXT("Subtype %s"),GuidNames[*pmt->Subtype()]));
DbgLog((LOG_TRACE,2,TEXT("Subtype description %s"),GetSubtypeName(pmt->Subtype())));
DbgLog((LOG_TRACE,2,TEXT("Format size %d"),pmt->cbFormat));
// Dump the generic media types */
DbgLog((LOG_TRACE,2,TEXT("Fixed size sample %d"),pmt->IsFixedSize()));
DbgLog((LOG_TRACE,2,TEXT("Temporal compression %d"),pmt->IsTemporalCompressed()));
DbgLog((LOG_TRACE,2,TEXT("Sample size %d"),pmt->GetSampleSize()));
} // DisplayMediaType
#endif
//
// CheckMediaType
//
HRESULT CTeeInputPin::CheckMediaType(const CMediaType *pmt)
{
CAutoLock lock_it(m_pLock);
// If we are already inside checkmedia type for this pin, return NOERROR
// It is possble to hookup two of the tee filters and some other filter
// like the video effects sample to get into this situation. If we don't
// detect this situation, we will carry on looping till we blow the stack
if (m_bInsideCheckMediaType == TRUE)
return NOERROR;
m_bInsideCheckMediaType = TRUE;
HRESULT hr = NOERROR;
#ifdef DEBUG
// Display the type of the media for debugging perposes
DisplayMediaType(TEXT("Input Pin Checking"), pmt);
#endif
// The media types that we can support are entirely dependent on the
// downstream connections. If we have downstream connections, we should
// check with them - walk through the list calling each output pin
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL) {
if (pOutputPin->m_Connected != NULL) {
// The pin is connected, check its peer
hr = pOutputPin->m_Connected->QueryAccept(pmt);
if (hr != NOERROR) {
m_bInsideCheckMediaType = FALSE;
return VFW_E_TYPE_NOT_ACCEPTED;
}
}
} else {
// We should have as many pins as the count says we have
ASSERT(FALSE);
}
n--;
}
// Either all the downstream pins have accepted or there are none.
m_bInsideCheckMediaType = FALSE;
return NOERROR;
} // CheckMediaType
//
// SetMediaType
//
HRESULT CTeeInputPin::SetMediaType(const CMediaType *pmt)
{
CAutoLock lock_it(m_pLock);
HRESULT hr = NOERROR;
// Make sure that the base class likes it
hr = CBaseInputPin::SetMediaType(pmt);
if (FAILED(hr))
return hr;
ASSERT(m_Connected != NULL);
return NOERROR;
} // SetMediaType
//
// BreakConnect
//
HRESULT CTeeInputPin::BreakConnect()
{
// Release any allocator that we are holding
if (m_pTee->m_pAllocator)
{
m_pTee->m_pAllocator->Release();
m_pTee->m_pAllocator = NULL;
}
return NOERROR;
} // BreakConnect
//
// NotifyAllocator
//
STDMETHODIMP
CTeeInputPin::NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly)
{
CAutoLock lock_it(m_pLock);
if (pAllocator == NULL)
return E_FAIL;
// Free the old allocator if any
if (m_pTee->m_pAllocator)
m_pTee->m_pAllocator->Release();
// Store away the new allocator
pAllocator->AddRef();
m_pTee->m_pAllocator = pAllocator;
// Notify the base class about the allocator
return CBaseInputPin::NotifyAllocator(pAllocator,bReadOnly);
} // NotifyAllocator
//
// EndOfStream
//
HRESULT CTeeInputPin::EndOfStream()
{
CAutoLock lock_it(m_pLock);
ASSERT(m_pTee->m_NumOutputPins);
HRESULT hr = NOERROR;
// Walk through the output pins list, sending the message downstream
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL) {
hr = pOutputPin->DeliverEndOfStream();
if (FAILED(hr))
return hr;
} else {
// We should have as many pins as the count says we have
ASSERT(FALSE);
}
n--;
}
return(NOERROR);
} // EndOfStream
//
// BeginFlush
//
HRESULT CTeeInputPin::BeginFlush()
{
CAutoLock lock_it(m_pLock);
ASSERT(m_pTee->m_NumOutputPins);
HRESULT hr = NOERROR;
// Walk through the output pins list, sending the message downstream
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL) {
hr = pOutputPin->DeliverBeginFlush();
if (FAILED(hr))
return hr;
} else {
// We should have as many pins as the count says we have
ASSERT(FALSE);
}
n--;
}
return CBaseInputPin::BeginFlush();
} // BeginFlush
//
// EndFlush
//
HRESULT CTeeInputPin::EndFlush()
{
CAutoLock lock_it(m_pLock);
ASSERT(m_pTee->m_NumOutputPins);
HRESULT hr = NOERROR;
// Walk through the output pins list, sending the message downstream
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL) {
hr = pOutputPin->DeliverEndFlush();
if (FAILED(hr))
return hr;
} else {
// We should have as many pins as the count says we have
ASSERT(FALSE);
}
n--;
}
return CBaseInputPin::EndFlush();
} // EndFlush
//
// NewSegment
//
HRESULT CTeeInputPin::NewSegment(REFERENCE_TIME tStart,
REFERENCE_TIME tStop,
double dRate)
{
CAutoLock lock_it(m_pLock);
ASSERT(m_pTee->m_NumOutputPins);
HRESULT hr = NOERROR;
// Walk through the output pins list, sending the message downstream
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL) {
hr = pOutputPin->DeliverNewSegment(tStart, tStop, dRate);
if (FAILED(hr))
return hr;
} else {
// We should have as many pins as the count says we have
ASSERT(FALSE);
}
n--;
}
return CBaseInputPin::NewSegment(tStart, tStop, dRate);
} // NewSegment
//
// Receive
//
HRESULT CTeeInputPin::Receive(IMediaSample *pSample)
{
CAutoLock lock_it(m_pLock);
// Check that all is well with the base class
HRESULT hr = NOERROR;
hr = CBaseInputPin::Receive(pSample);
if (hr != NOERROR)
return hr;
// Walk through the output pins list, delivering to each in turn
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL) {
hr = pOutputPin->Deliver(pSample);
if (hr != NOERROR)
return hr;
} else {
// We should have as many pins as the count says we have
ASSERT(FALSE);
}
n--;
}
return NOERROR;
} // Receive
//
// Completed a connection to a pin
//
HRESULT CTeeInputPin::CompleteConnect(IPin *pReceivePin)
{
HRESULT hr = CBaseInputPin::CompleteConnect(pReceivePin);
if (FAILED(hr)) {
return hr;
}
// Force any output pins to use our type
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL) {
// Check with downstream pin
if (pOutputPin->m_Connected != NULL) {
if (m_mt != pOutputPin->m_mt)
m_pTee->ReconnectPin(pOutputPin, &m_mt);
}
} else {
// We should have as many pins as the count says we have
ASSERT(FALSE);
}
n--;
}
return S_OK;
}
//
// CTeeOutputPin constructor
//
CTeeOutputPin::CTeeOutputPin(TCHAR *pName,
CTee *pTee,
HRESULT *phr,
LPCWSTR pPinName,
int PinNumber) :
CBaseOutputPin(pName, pTee, pTee, phr, pPinName) ,
m_pOutputQueue(NULL),
m_bHoldsSeek(FALSE),
m_pPosition(NULL),
m_pTee(pTee),
m_cOurRef(0),
m_bInsideCheckMediaType(FALSE)
{
ASSERT(pTee);
}
#ifdef DEBUG
//
// CTeeOutputPin destructor
//
CTeeOutputPin::~CTeeOutputPin()
{
ASSERT(m_pOutputQueue == NULL);
}
#endif
//
// NonDelegatingQueryInterface
//
// This function is overwritten to expose IMediaPosition and IMediaSelection
// Note that only one output stream can be allowed to expose this to avoid
// conflicts, the other pins will just return E_NOINTERFACE and therefore
// appear as non seekable streams. We have a LONG value that if exchanged to
// produce a TRUE means that we have the honor. If it exchanges to FALSE then
// someone is already in. If we do get it and error occurs then we reset it
// to TRUE so someone else can get it.
//
STDMETHODIMP
CTeeOutputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
CheckPointer(ppv,E_POINTER);
ASSERT(ppv);
*ppv = NULL;
HRESULT hr = NOERROR;
// See what interface the caller is interested in.
if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking) {
if (m_pPosition) {
if (m_bHoldsSeek == FALSE)
return E_NOINTERFACE;
return m_pPosition->QueryInterface(riid, ppv);
}
} else
return CBaseOutputPin::NonDelegatingQueryInterface(riid, ppv);
CAutoLock lock_it(m_pLock);
ASSERT(m_pPosition == NULL);
IUnknown *pMediaPosition = NULL;
// Try to create a seeking implementation
if (InterlockedExchange(&m_pTee->m_lCanSeek, FALSE) == FALSE)
return E_NOINTERFACE;
// Create implementation of this dynamically as sometimes we may never
// try and seek. The helper object implements IMediaPosition and also
// the IMediaSelection control interface and simply takes the calls
// normally from the downstream filter and passes them upstream
hr = CreatePosPassThru(
GetOwner(),
FALSE,
(IPin *)&m_pTee->m_Input,
&pMediaPosition);
if (pMediaPosition == NULL) {
InterlockedExchange(&m_pTee->m_lCanSeek, TRUE);
return E_OUTOFMEMORY;
}
if (FAILED(hr)) {
InterlockedExchange(&m_pTee->m_lCanSeek, TRUE);
pMediaPosition->Release ();
return hr;
}
m_pPosition = pMediaPosition;
m_bHoldsSeek = TRUE;
return NonDelegatingQueryInterface(riid, ppv);
} // NonDelegatingQueryInterface
//
// NonDelegatingAddRef
//
// We need override this method so that we can do proper reference counting
// on our output pin. The base class CBasePin does not do any reference
// counting on the pin in RETAIL.
//
// Please refer to the comments for the NonDelegatingRelease method for more
// info on why we need to do this.
//
STDMETHODIMP_(ULONG) CTeeOutputPin::NonDelegatingAddRef()
{
CAutoLock lock_it(m_pLock);
#ifdef DEBUG
// Update the debug only variable maintained by the base class
m_cRef++;
ASSERT(m_cRef > 0);
#endif
// Now update our reference count
m_cOurRef++;
ASSERT(m_cOurRef > 0);
return m_cOurRef;
} // NonDelegatingAddRef
//
// NonDelegatingRelease
//
// CTeeOutputPin overrides this class so that we can take the pin out of our
// output pins list and delete it when its reference count drops to 1 and there
// is atleast two free pins.
//
// Note that CreateNextOutputPin holds a reference count on the pin so that
// when the count drops to 1, we know that no one else has the pin.
//
// Moreover, the pin that we are about to delete must be a free pin(or else
// the reference would not have dropped to 1, and we must have atleast one
// other free pin(as the filter always wants to have one more free pin)
//
// Also, since CBasePin::NonDelegatingAddRef passes the call to the owning
// filter, we will have to call Release on the owning filter as well.
//
// Also, note that we maintain our own reference count m_cOurRef as the m_cRef
// variable maintained by CBasePin is debug only.
//
STDMETHODIMP_(ULONG) CTeeOutputPin::NonDelegatingRelease()
{
CAutoLock lock_it(m_pLock);
#ifdef DEBUG
// Update the debug only variable in CBasePin
m_cRef--;
ASSERT(m_cRef >= 0);
#endif
// Now update our reference count
m_cOurRef--;
ASSERT(m_cOurRef >= 0);
// if the reference count on the object has gone to one, remove
// the pin from our output pins list and physically delete it
// provided there are atealst two free pins in the list(including
// this one)
// Also, when the ref count drops to 0, it really means that our
// filter that is holding one ref count has released it so we
// should delete the pin as well.
if (m_cOurRef <= 1) {
int n = 2; // default forces pin deletion
if (m_cOurRef == 1) {
// Walk the list of pins, looking for count of free pins
n = m_pTee->GetNumFreePins();
}
// If there are two free pins, delete this one.
// NOTE: normall
if (n >= 2 ) {
m_cOurRef = 0;
#ifdef DEBUG
m_cRef = 0;
#endif
m_pTee->DeleteOutputPin(this);
return(ULONG) 0;
}
}
return(ULONG) m_cOurRef;
} // NonDelegatingRelease
//
// DecideBufferSize
//
// This has to be present to override the PURE virtual class base function
//
HRESULT CTeeOutputPin::DecideBufferSize(IMemAllocator *pMemAllocator,
ALLOCATOR_PROPERTIES * ppropInputRequest)
{
return NOERROR;
} // DecideBufferSize
//
// DecideAllocator
//
HRESULT CTeeOutputPin::DecideAllocator(IMemInputPin *pPin, IMemAllocator **ppAlloc)
{
ASSERT(m_pTee->m_pAllocator != NULL);
*ppAlloc = NULL;
// Tell the pin about our allocator, set by the input pin.
HRESULT hr = NOERROR;
hr = pPin->NotifyAllocator(m_pTee->m_pAllocator,TRUE);
if (FAILED(hr))
return hr;
// Return the allocator
*ppAlloc = m_pTee->m_pAllocator;
m_pTee->m_pAllocator->AddRef();
return NOERROR;
} // DecideAllocator
//
// CheckMediaType
//
HRESULT CTeeOutputPin::CheckMediaType(const CMediaType *pmt)
{
CAutoLock lock_it(m_pLock);
// If we are already inside checkmedia type for this pin, return NOERROR
// It is possble to hookup two of the tee filters and some other filter
// like the video effects sample to get into this situation. If we
// do not detect this, we will loop till we blow the stack
if (m_bInsideCheckMediaType == TRUE)
return NOERROR;
m_bInsideCheckMediaType = TRUE;
HRESULT hr = NOERROR;
#ifdef DEBUG
// Display the type of the media for debugging purposes
DisplayMediaType(TEXT("Output Pin Checking"), pmt);
#endif
// The input needs to have been conneced first
if (m_pTee->m_Input.m_Connected == NULL) {
m_bInsideCheckMediaType = FALSE;
return VFW_E_NOT_CONNECTED;
}
// Make sure that our input pin peer is happy with this
hr = m_pTee->m_Input.m_Connected->QueryAccept(pmt);
if (hr != NOERROR) {
m_bInsideCheckMediaType = FALSE;
return VFW_E_TYPE_NOT_ACCEPTED;
}
// Check the format with the other outpin pins
int n = m_pTee->m_NumOutputPins;
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
while(n) {
CTeeOutputPin *pOutputPin = m_pTee->m_OutputPinsList.GetNext(pos);
if (pOutputPin != NULL && pOutputPin != this) {
if (pOutputPin->m_Connected != NULL) {
// The pin is connected, check its peer
hr = pOutputPin->m_Connected->QueryAccept(pmt);
if (hr != NOERROR) {
m_bInsideCheckMediaType = FALSE;
return VFW_E_TYPE_NOT_ACCEPTED;
}
}
}
n--;
}
m_bInsideCheckMediaType = FALSE;
return NOERROR;
} // CheckMediaType
//
// EnumMediaTypes
//
STDMETHODIMP CTeeOutputPin::EnumMediaTypes(IEnumMediaTypes **ppEnum)
{
CAutoLock lock_it(m_pLock);
ASSERT(ppEnum);
// Make sure that we are connected
if (m_pTee->m_Input.m_Connected == NULL)
return VFW_E_NOT_CONNECTED;
// We will simply return the enumerator of our input pin's peer
return m_pTee->m_Input.m_Connected->EnumMediaTypes(ppEnum);
} // EnumMediaTypes
//
// SetMediaType
//
HRESULT CTeeOutputPin::SetMediaType(const CMediaType *pmt)
{
CAutoLock lock_it(m_pLock);
#ifdef DEBUG
// Display the format of the media for debugging purposes
DisplayMediaType(TEXT("Output pin type agreed"), pmt);
#endif
// Make sure that we have an input connected
if (m_pTee->m_Input.m_Connected == NULL)
return VFW_E_NOT_CONNECTED;
// Make sure that the base class likes it
HRESULT hr = NOERROR;
hr = CBaseOutputPin::SetMediaType(pmt);
if (FAILED(hr))
return hr;
return NOERROR;
} // SetMediaType
//
// CompleteConnect
//
HRESULT CTeeOutputPin::CompleteConnect(IPin *pReceivePin)
{
CAutoLock lock_it(m_pLock);
ASSERT(m_Connected == pReceivePin);
HRESULT hr = NOERROR;
hr = CBaseOutputPin::CompleteConnect(pReceivePin);
if (FAILED(hr))
return hr;
// If the type is not the same as that stored for the input
// pin then force the input pins peer to be reconnected
if (m_mt != m_pTee->m_Input.m_mt)
{
hr = m_pTee->ReconnectPin(m_pTee->m_Input.m_Connected, &m_mt);
if(FAILED(hr)) {
return hr;
}
}
// Since this pin has been connected up, create another output pin. We
// will do this only if there are no unconnected pins on us. However
// CompleteConnect will get called for the same pin during reconnection
int n = m_pTee->GetNumFreePins();
ASSERT(n <= 1);
if (n == 1 || m_pTee->m_NumOutputPins == INFTEE_MAX_PINS)
return NOERROR;
// No unconnected pins left so spawn a new one
CTeeOutputPin *pOutputPin = m_pTee->CreateNextOutputPin(m_pTee);
if (pOutputPin != NULL )
{
m_pTee->m_NumOutputPins++;
m_pTee->m_OutputPinsList.AddTail(pOutputPin);
m_pTee->IncrementPinVersion();
}
// At this point we should be able to send some
// notification that we have sprung a new pin
return NOERROR;
} // CompleteConnect
//
// Active
//
// This is called when we start running or go paused. We create the
// output queue object to send data to our associated peer pin
//
HRESULT CTeeOutputPin::Active()
{
CAutoLock lock_it(m_pLock);
HRESULT hr = NOERROR;
// Make sure that the pin is connected
if (m_Connected == NULL)
return NOERROR;
// Create the output queue if we have to
if (m_pOutputQueue == NULL)
{
m_pOutputQueue = new COutputQueue(m_Connected, &hr, TRUE, FALSE);
if (m_pOutputQueue == NULL)
return E_OUTOFMEMORY;
// Make sure that the constructor did not return any error
if (FAILED(hr))
{
delete m_pOutputQueue;
m_pOutputQueue = NULL;
return hr;
}
}
// Pass the call on to the base class
CBaseOutputPin::Active();
return NOERROR;
} // Active
//
// Inactive
//
// This is called when we stop streaming
// We delete the output queue at this time
//
HRESULT CTeeOutputPin::Inactive()
{
CAutoLock lock_it(m_pLock);
// Delete the output queus associated with the pin.
if (m_pOutputQueue)
{
delete m_pOutputQueue;
m_pOutputQueue = NULL;
}
CBaseOutputPin::Inactive();
return NOERROR;
} // Inactive
//
// Deliver
//
HRESULT CTeeOutputPin::Deliver(IMediaSample *pMediaSample)
{
// Make sure that we have an output queue
if (m_pOutputQueue == NULL)
return NOERROR;
pMediaSample->AddRef();
return m_pOutputQueue->Receive(pMediaSample);
} // Deliver
//
// DeliverEndOfStream
//
HRESULT CTeeOutputPin::DeliverEndOfStream()
{
// Make sure that we have an output queue
if (m_pOutputQueue == NULL)
return NOERROR;
m_pOutputQueue->EOS();
return NOERROR;
} // DeliverEndOfStream
//
// DeliverBeginFlush
//
HRESULT CTeeOutputPin::DeliverBeginFlush()
{
// Make sure that we have an output queue
if (m_pOutputQueue == NULL)
return NOERROR;
m_pOutputQueue->BeginFlush();
return NOERROR;
} // DeliverBeginFlush
//
// DeliverEndFlush
//
HRESULT CTeeOutputPin::DeliverEndFlush()
{
// Make sure that we have an output queue
if (m_pOutputQueue == NULL)
return NOERROR;
m_pOutputQueue->EndFlush();
return NOERROR;
} // DeliverEndFlish
//
// DeliverNewSegment
//
HRESULT CTeeOutputPin::DeliverNewSegment(REFERENCE_TIME tStart,
REFERENCE_TIME tStop,
double dRate)
{
// Make sure that we have an output queue
if (m_pOutputQueue == NULL)
return NOERROR;
m_pOutputQueue->NewSegment(tStart, tStop, dRate);
return NOERROR;
} // DeliverNewSegment
//
// Notify
//
STDMETHODIMP CTeeOutputPin::Notify(IBaseFilter *pSender, Quality q)
{
// We pass the message on, which means that we find the quality sink
// for our input pin and send it there
POSITION pos = m_pTee->m_OutputPinsList.GetHeadPosition();
CTeeOutputPin *pFirstOutput = m_pTee->m_OutputPinsList.GetNext(pos);
if (this == pFirstOutput) {
if (m_pTee->m_Input.m_pQSink!=NULL) {
return m_pTee->m_Input.m_pQSink->Notify(m_pTee, q);
} else {
// No sink set, so pass it upstream
HRESULT hr;
IQualityControl * pIQC;
hr = VFW_E_NOT_FOUND;
if (m_pTee->m_Input.m_Connected) {
m_pTee->m_Input.m_Connected->QueryInterface(IID_IQualityControl,(void**)&pIQC);
if (pIQC!=NULL) {
hr = pIQC->Notify(m_pTee, q);
pIQC->Release();
}
}
return hr;
}
}
// Quality management is too hard to do
return NOERROR;
} // Notify
| 26.379523
| 89
| 0.609274
|
npocmaka
|
f4fdcf9263914ccf76be06a87351d5576a534c0f
| 52,096
|
cpp
|
C++
|
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/sock-new.cpp
|
qiuhere/Bench
|
80f15facb81120b754547586cf3a7e5f46ca1551
|
[
"Apache-2.0"
] | null | null | null |
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/sock-new.cpp
|
qiuhere/Bench
|
80f15facb81120b754547586cf3a7e5f46ca1551
|
[
"Apache-2.0"
] | null | null | null |
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/sock-new.cpp
|
qiuhere/Bench
|
80f15facb81120b754547586cf3a7e5f46ca1551
|
[
"Apache-2.0"
] | null | null | null |
#include "sock.h"
#ifdef GLib_UNIX
class TSocketTimer : public TTTimer {
private:
int SockId;
public:
TSocketTimer(const int TimeOut, /*PSock &_Socket*/ const int _SockId) : TTTimer(TimeOut), SockId(_SockId) {}
~TSocketTimer() {}
void OnTimeOut();
};
#endif
/////////////////////////////////////////////////
// Socket-System
class TSockSys{
public:
// socket-system initialized
static bool Active;
#ifdef GLib_WIN32
// window handles
static HWND SockWndHnd;
static HWND DnsWndHnd;
static HWND ReportWndHnd;
static HWND TimerWndHnd;
// message-handles
static UINT SockMsgHnd;
static UINT SockErrMsgHnd;
static UINT DnsMsgHnd;
static UINT ReportMsgHnd;
#endif
#ifdef GLib_UNIX
static int TimerSignal;
static int ResolverSignal;
static int ET_epoll_fd, LT_epoll_fd;
#endif
// sockets
static uint64 SockBytesRead;
static uint64 SockBytesWritten;
static THash<TInt, TUInt64> SockIdToHndH;
static THash<TUInt64, TInt> SockHndToIdH;
static THash<TUInt64, TInt> SockHndToEventIdH;
#ifdef GLib_WIN32
static TIntH SockTimerIdH;
#elif defined(GLib_UNIX)
static THash<TInt, TInt> SockToTimerIdH;
static THash<TInt, TInt> SockHndToStateH;
#endif
static TUInt64H ActiveSockHndH;
// socket-host
static THash<TUInt64, PSockHost> HndToSockHostH;
// socket-event
static THash<TInt, PSockEvent> IdToSockEventH;
static TIntH ActiveSockEventIdH;
// report-event
static THash<TInt, PReportEvent> IdToReportEventH;
// timer
static THash<TInt, ATimer> IdToTimerH;
public:
// windows-sockets messages
static TStr GetErrStr(const int ErrCd);
#ifdef GLib_WIN32
// main message handler
static LRESULT CALLBACK MainWndProc(
HWND WndHnd, UINT Msg, WPARAM wParam, LPARAM lParam);
#endif
public:
TSockSys();
~TSockSys();
TSockSys& operator=(const TSockSys&){Fail; return *this;}
#ifdef GLib_WIN32
// window handles
static HWND GetSockWndHnd(){IAssert(Active); return SockWndHnd;}
static HWND GetDnsWndHnd(){IAssert(Active); return DnsWndHnd;}
static HWND GetReportWndHnd(){IAssert(Active); return ReportWndHnd;}
static HWND GetTimerWndHnd(){IAssert(Active); return TimerWndHnd;}
// message handles
static UINT GetSockMsgHnd(){IAssert(Active); return SockMsgHnd;}
static UINT GetSockErrMsgHnd(){IAssert(Active); return SockErrMsgHnd;}
static UINT GetDnsMsgHnd(){IAssert(Active); return DnsMsgHnd;}
static UINT GetReportMsgHnd(){IAssert(Active); return ReportMsgHnd;}
// event set
static int GetAllSockEventCdSet(){
return (FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT|FD_CLOSE);}
#endif
#ifdef GLib_UNIX
static int GetFreeRTSig(int Start);
static void SetupFAsync(int fd);
static void DoIOEvent(struct epoll_event *e);
static void DoIO();
static void DoTimer(siginfo_t *si);
static void DoResolver(siginfo_t *si);
static void AsyncLoop();
#endif
// sockets (SockIdToHndH, SockHndToIdH, SockHndToEventH)
static uint64 GetSockBytesRead(){return SockBytesRead;}
static uint64 GetSockBytesWritten(){return SockBytesWritten;}
static void AddSock(
const int& SockId, const TSockHnd& SockHnd, const int& SockEventId);
static void DelSock(const int& SockId);
static bool IsSockId(const int& SockId){
IAssert(Active); return SockIdToHndH.IsKey(SockId);}
static bool IsSockHnd(const TSockHnd& SockHnd){
IAssert(Active); return SockHndToIdH.IsKey(SockHnd);}
static TSockHnd GetSockHnd(const int& SockId){
IAssert(Active); return TSockHnd(SockIdToHndH.GetDat(SockId));}
static TSockHnd GetSockId(const TSockHnd& SockHnd){
IAssert(Active); return SockHndToIdH.GetDat(SockHnd);}
static int GetSockEventId(const TSockHnd& SockHnd){
IAssert(Active); return SockHndToEventIdH.GetDat(SockHnd);}
#ifdef GLib_WIN32
static void AddSockTimer(const int& SockId, const int& MSecs){
UINT ErrCd=(UINT)SetTimer(TSockSys::GetSockWndHnd(), SockId, uint(MSecs), NULL);
ESAssert(ErrCd!=0);
TSockSys::SockTimerIdH.AddKey(SockId);}
static void DelIfSockTimer(const int& SockId){
KillTimer(TSockSys::GetSockWndHnd(), SockId);
TSockSys::SockTimerIdH.DelIfKey(SockId);}
#elif defined(GLib_UNIX)
static void AddSockTimer(const int& SockId, const int& MSecs);
static void DelIfSockTimer(const int& SockId);
#endif
static bool IsSockActive(const TSockHnd& SockHnd){
return ActiveSockHndH.IsKey(SockHnd);}
static void SetSockActive(const TSockHnd& SockHnd, const bool& Active){
IAssert(
(Active&&!IsSockActive(SockHnd))||
(!Active&&IsSockActive(SockHnd)));
if (Active){ActiveSockHndH.AddKey(SockHnd);}
else {ActiveSockHndH.DelKey(SockHnd);}}
static const int MxSockBfL;
// socket host (HndToSockHostH)
static void AddSockHost(const TUInt64& SockHostHnd, const PSockHost& SockHost){
HndToSockHostH.AddDat(SockHostHnd, SockHost);}
static void DelSockHost(const TUInt64& SockHostHnd){
HndToSockHostH.DelKey(SockHostHnd);}
static bool IsSockHost(const TUInt64& SockHostHnd){
return HndToSockHostH.IsKey(SockHostHnd);}
static PSockHost GetSockHost(const TUInt64& SockHostHnd){
return HndToSockHostH.GetDat(SockHostHnd);}
// socket event (IdToSockEventH, ActiveSockEventIdH)
static void AddSockEvent(const PSockEvent& SockEvent){
IAssert(!IsSockEvent(SockEvent));
IdToSockEventH.AddDat(SockEvent->GetSockEventId(), SockEvent);}
static void DelSockEvent(const PSockEvent& SockEvent){
IdToSockEventH.DelKey(SockEvent->GetSockEventId());}
static bool IsSockEvent(const int& SockEventId){
return IdToSockEventH.IsKey(TInt(SockEventId));}
static bool IsSockEvent(const PSockEvent& SockEvent){
return IdToSockEventH.IsKey(TInt(SockEvent->GetSockEventId()));}
static PSockEvent GetSockEvent(const int& SockEventId){
return IdToSockEventH.GetDat(SockEventId);}
static bool IsSockEventActive(const int& SockEventId){
return ActiveSockEventIdH.IsKey(SockEventId);}
static void SetSockEventActive(const int& SockEventId, const bool& Active){
IAssert(
(Active&&!IsSockEventActive(SockEventId))||
(!Active&&IsSockEventActive(SockEventId)));
if (Active){ActiveSockEventIdH.AddKey(SockEventId);}
else {ActiveSockEventIdH.DelKey(SockEventId);}}
// report event (IdToReportEventH)
static void AddReportEvent(const PReportEvent& ReportEvent){
IAssert(!IsReportEvent(ReportEvent));
IdToReportEventH.AddDat(TInt(ReportEvent->GetReportEventId()), ReportEvent);}
static void DelReportEvent(const PReportEvent& ReportEvent){
IdToReportEventH.DelKey(TInt(ReportEvent->GetReportEventId()));}
static bool IsReportEvent(const PReportEvent& ReportEvent){
return IdToReportEventH.IsKey(TInt(ReportEvent->GetReportEventId()));}
static PReportEvent GetReportEvent(const int& ReportEventId){
return IdToReportEventH.GetDat(ReportEventId);}
// timer (IdToTimerH)
static void AddTimer(const ATimer& Timer){
IAssert(!IsTimer(Timer->GetTimerId()));
IdToTimerH.AddDat(TInt(Timer->GetTimerId()), Timer);}
static void DelTimer(const int& TimerId){
IdToTimerH.DelKey(TimerId);}
static bool IsTimer(const int& TimerId){
return IdToTimerH.IsKey(TimerId);}
static ATimer GetTimer(const int& TimerId){
return IdToTimerH.GetDat(TimerId);}
// socket & host events
static void OnRead(const TSockHnd& SockHnd, const PSockEvent& SockEvent);
static void OnWrite(const TSockHnd& SockHnd, const PSockEvent& SockEvent);
static void OnOob(const TSockHnd& SockHnd, const PSockEvent& SockEvent);
static void OnAccept(const TSockHnd& SockHnd, const PSockEvent& SockEvent);
static void OnConnect(const TSockHnd& SockHnd, const PSockEvent& SockEvent);
static void OnClose(const TSockHnd& SockHnd, const PSockEvent& SockEvent);
static void OnTimeOut(const TSockHnd& SockHnd, const PSockEvent& SockEvent);
static void OnError(
const TSockHnd& SockHnd, const PSockEvent& SockEvent, const int& ErrCd);
static void OnGetHost(const PSockHost& SockHost);
// status
static TStr GetStatusStr();
};
// socket system initialized
bool TSockSys::Active=false;
#ifdef GLib_WIN32
// window handles
HWND TSockSys::SockWndHnd=0;
HWND TSockSys::DnsWndHnd=0;
HWND TSockSys::ReportWndHnd=0;
HWND TSockSys::TimerWndHnd=0;
// message handles
UINT TSockSys::SockMsgHnd=0;
UINT TSockSys::SockErrMsgHnd=0;
UINT TSockSys::DnsMsgHnd=0;
UINT TSockSys::ReportMsgHnd=0;
#endif
#ifdef GLib_UNIX
int TSockSys::TimerSignal = -1;
int TSockSys::ResolverSignal = -1;
int TSockSys::ET_epoll_fd = -1;
int TSockSys::LT_epoll_fd = -1;
#endif
// sockets
uint64 TSockSys::SockBytesRead=0;
uint64 TSockSys::SockBytesWritten=0;
THash<TInt, TUInt64> TSockSys::SockIdToHndH;
THash<TUInt64, TInt> TSockSys::SockHndToIdH;
THash<TUInt64, TInt> TSockSys::SockHndToEventIdH;
#ifdef GLib_WIN32
TIntH TSockSys::SockTimerIdH;
#elif defined(GLib_UNIX)
THash<TInt, TInt> TSockSys::SockToTimerIdH;
THash<TInt, TInt> TSockSys::SockHndToStateH;
#endif
TUInt64H TSockSys::ActiveSockHndH;
const int TSockSys::MxSockBfL=100*1024;
// socket host
THash<TUInt64, PSockHost> TSockSys::HndToSockHostH;
// socket event
THash<TInt, PSockEvent> TSockSys::IdToSockEventH;
TIntH TSockSys::ActiveSockEventIdH;
// report event
THash<TInt, PReportEvent> TSockSys::IdToReportEventH;
// timer
THash<TInt, ATimer> TSockSys::IdToTimerH;
TSockSys SockSys; // the only instance of TSockSys
#ifdef GLib_WIN32
TStr TSockSys::GetErrStr(const int ErrCd){
switch (ErrCd){
// WSAStartup errors
case WSASYSNOTREADY: return "Underlying network subsystem is not ready for network communication.";
case WSAVERNOTSUPPORTED: return "The version of Windows Sockets support requested is not provided by this particular Windows Sockets implementation.";
case WSAEPROCLIM: return "Limit on the number of tasks supported by the Windows Sockets implementation has been reached.";
// WSACleanup error
case WSANOTINITIALISED: return "Windows Sockets not initialized.";
case WSAENETDOWN: return "The network subsystem has failed.";
// general errors
case WSAEWOULDBLOCK: return "Resource temporarily unavailable (op. would block).";
case WSAEINPROGRESS: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case WSAEADDRINUSE: return "The specified address is already in use.";
case WSAEADDRNOTAVAIL: return "The specified address is not available from the local machine.";
case WSAEAFNOSUPPORT: return "Addresses in the specified family cannot be used with this socket.";
case WSAECONNREFUSED: return "The attempt to connect was forcefully rejected.";
case WSAENETUNREACH: return "The network cannot be reached from this host at this time.";
case WSAEFAULT: return "Bad parameter.";
case WSAEINVAL: return "The socket is already bound to an address.";
case WSAEISCONN: return "The socket is already connected.";
case WSAEMFILE: return "No more file descriptors are available.";
case WSAENOBUFS: return "No buffer space is available. The socket cannot be connected.";
case WSAENOTCONN: return "The socket is not connected.";
case WSAETIMEDOUT: return "Attempt to connect timed out without establishing a connection.";
case WSAECONNRESET: return "The connection was reset by the remote side.";
case WSAECONNABORTED: return "The connection was terminated due to a time-out or other failure.";
default: return TStr("Unknown socket error (code ")+TInt::GetStr(ErrCd)+TStr(").");
}
}
LRESULT CALLBACK TSockSys::MainWndProc(
HWND WndHnd, UINT MsgHnd, WPARAM wParam, LPARAM lParam){
if (MsgHnd==TSockSys::SockMsgHnd){
IAssert(WndHnd==GetSockWndHnd());
TSockHnd SockHnd=wParam;
if (IsSockHnd(SockHnd)){
int SockEventId=GetSockEventId(SockHnd);
PSockEvent SockEvent=GetSockEvent(SockEventId);
//SetSockActive(SockHnd, true);
SetSockEventActive(SockEventId, true);
try {
int ErrCd=WSAGETSELECTERROR(lParam);
if (ErrCd==0){
int EventCd=WSAGETSELECTEVENT(lParam);
switch (EventCd){
case FD_READ: OnRead(SockHnd, SockEvent); break;
case FD_WRITE: OnWrite(SockHnd, SockEvent); break;
case FD_OOB: OnOob(SockHnd, SockEvent); break;
case FD_ACCEPT: OnAccept(SockHnd, SockEvent); break;
case FD_CONNECT: OnConnect(SockHnd, SockEvent); break;
case FD_CLOSE: OnClose(SockHnd, SockEvent); break;
default: Fail;
}
} else {
OnError(SockHnd, SockEvent, ErrCd);
}
} catch (...){
SaveToErrLog("Exception from 'switch (EventCd)'");
}
SetSockEventActive(SockEventId, false);
//SetSockActive(SockHnd, false);
}
} else
if (MsgHnd==TSockSys::SockErrMsgHnd){
IAssert(WndHnd==GetSockWndHnd());
TSockHnd SockHnd=wParam;
if (IsSockHnd(SockHnd)){
int SockEventId=GetSockEventId(SockHnd);
PSockEvent SockEvent=GetSockEvent(SockEventId);
//SetSockActive(SockHnd, true);
SetSockEventActive(SockEventId, true);
try {
int ErrCd=int(lParam);
OnError(SockHnd, SockEvent, ErrCd);
} catch (...){
SaveToErrLog("Exception from 'OnError(SockHnd, SockEvent, ErrCd)'");
}
SetSockEventActive(SockEventId, false);
//SetSockActive(SockHnd, false);
}
} else
if (MsgHnd==WM_TIMER){
if (WndHnd==GetSockWndHnd()){
int SockId=int(wParam);
DelIfSockTimer(SockId);
if (IsSockId(SockId)){
TSockHnd SockHnd=GetSockHnd(SockId);
int SockEventId=GetSockEventId(SockHnd);
PSockEvent SockEvent=GetSockEvent(SockEventId);
//SetSockActive(SockHnd, true);
SetSockEventActive(SockEventId, true);
try {
OnTimeOut(SockHnd, SockEvent);
} catch (...){
SaveToErrLog("Exception from OnTimeOut(SockHnd, SockEvent);");
}
SetSockEventActive(SockEventId, false);
//SetSockActive(SockHnd, false);
}
} else
if (WndHnd==GetTimerWndHnd()){
int TimerId=int(wParam);
if (TSockSys::IsTimer(TimerId)){
PTimer Timer=TSockSys::GetTimer(TimerId)();
Timer->IncTicks();
try {
Timer->OnTimeOut();
} catch (...){
SaveToErrLog("Exception from Timer->OnTimeOut();");
}
}
} else {
Fail;
}
} else
if (MsgHnd==TSockSys::DnsMsgHnd){
IAssert(WndHnd==GetDnsWndHnd());
uint SockHostHnd=int(wParam);
if (TSockSys::IsSockHost(SockHostHnd)){
TSockHostStatus Status=TSockHost::GetStatus(WSAGETASYNCERROR(lParam));
PSockHost SockHost=TSockSys::GetSockHost(SockHostHnd);
SockHost->GetFromHostEnt(Status, (hostent*)SockHost->HostEntBf);
DelSockHost(SockHostHnd); // !!! !bn: kaj se zgodi ce unics TSockHost prezgodi? sej se ne deregistrira?
try {
OnGetHost(SockHost);
} catch (...){
SaveToErrLog("Exception from OnGetHost(SockHost);");
}
}
} else
if (MsgHnd==TSockSys::ReportMsgHnd){
IAssert(WndHnd==GetReportWndHnd());
int ReportEventId=int(lParam);
PReportEvent ReportEvent=TSockSys::GetReportEvent(ReportEventId);
try {
ReportEvent->OnReport();
} catch (...){
SaveToErrLog("Exception from ReportEvent->OnReport()");
}
TSockSys::DelReportEvent(ReportEvent);
} else {
return DefWindowProc(WndHnd, MsgHnd, wParam, lParam);
}
return 0;
}
TSockSys::TSockSys(){
IAssert(Active==false);
WNDCLASS WndClass;
WndClass.style=0;
WndClass.lpfnWndProc=MainWndProc;
WndClass.cbClsExtra=0;
WndClass.cbWndExtra=0;
FSAssert((WndClass.hInstance=GetModuleHandle(NULL))!=NULL);
WndClass.hIcon=NULL;
WndClass.hCursor=NULL;
WndClass.hbrBackground=NULL;
WndClass.lpszMenuName=NULL;
WndClass.lpszClassName="SockWndClass";
FSAssert(RegisterClass(&WndClass)!=0);
TSockSys::SockWndHnd=CreateWindow(
"SockWndClass", "Socket Window",
WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
GetModuleHandle(NULL), NULL);
FSAssert(TSockSys::SockWndHnd!=NULL);
TSockSys::DnsWndHnd=CreateWindow(
"SockWndClass", "Dns Window",
WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
GetModuleHandle(NULL), NULL);
FSAssert(TSockSys::DnsWndHnd!=NULL);
TSockSys::ReportWndHnd=CreateWindow(
"SockWndClass", "RepMsg Window",
WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
GetModuleHandle(NULL), NULL);
FSAssert(TSockSys::ReportWndHnd!=NULL);
TSockSys::TimerWndHnd=CreateWindow(
"SockWndClass", "Net Timer",
WS_OVERLAPPEDWINDOW, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
GetModuleHandle(NULL), NULL);
FSAssert(TSockSys::TimerWndHnd!=NULL);
SockMsgHnd=RegisterWindowMessage("SockSys.SockMsg"); FSAssert(SockMsgHnd!=0);
SockErrMsgHnd=RegisterWindowMessage("SockSys.SockErrorMsg"); FSAssert(SockErrMsgHnd!=0);
DnsMsgHnd=RegisterWindowMessage("SockSys.DnsMsg"); FSAssert(DnsMsgHnd!=0);
ReportMsgHnd=RegisterWindowMessage("SockSys.RepMsg"); FSAssert(ReportMsgHnd!=0);
//WORD Version=MAKEWORD((2),(0));
WORD Version=((WORD) (((BYTE) (2)) | (((WORD) ((BYTE) (0))) << 8)));
WSADATA WsaData;
int WsaErrCd=WSAStartup(Version, &WsaData);
FAssert(WsaErrCd==0, TSockSys::GetErrStr(WsaErrCd));
FAssert(
WsaData.wVersion==Version,
"Can not find appropriate version of WinSock DLL.");
Active=true;
}
TSockSys::~TSockSys(){
if (Active){
IAssert(ActiveSockHndH.Len()==0);
IAssert(ActiveSockEventIdH.Len()==0);
int WsaErrCd=WSACleanup();
FAssert(WsaErrCd==0, TSockSys::GetErrStr(WsaErrCd));
Active=false;
}
}
#elif defined(GLib_UNIX)
TStr TSockSys::GetErrStr(const int ErrCd) {
char b[1024];
/* -- somewhat annoying - strerror_r as defined by SUSv3 doesn't want to work here.
int ret = strerror_r(ErrCd, b, 1023);
if (ret == -1) {
if (errno == EINVAL) strcpy(b, "Invalid error number.");
else if (errno == ERANGE) strcpy(b, "Insufficient storage space for error string.");
else strcpy(b, "Error.");
}
return TStr(b);
*/
return TStr(strerror_r(ErrCd, b, 1023));
}
void TSockSys::AddSockTimer(const int& SockId, const int& MSecs) {
ATimer Tmr = new TSocketTimer(MSecs, SockId);
AddTimer(Tmr);
SockToTimerIdH.AddDat(SockId, Tmr->GetTimerId());
}
void TSockSys::DelIfSockTimer(const int& SockId) {
// can be called from within TSocketTimer::OnTimeout() !
// !!! !bn: error handling.
ATimer Tmr = GetTimer(SockToTimerIdH[SockId]);
DelTimer(SockToTimerIdH[SockId]); // first take from timer list, then destroy object!
delete Tmr();
}
int TSockSys::GetFreeRTSig(int Start) {
sigset_t ss, cs;
sigemptyset(&ss);
sigprocmask(SIG_BLOCK, &ss, &cs);
for (int i=Start;i<=SIGRTMAX;i++) {
if (sigismember(&cs, i)) {
// it's not blocked. if it does not have a signal handler, it's ours.
struct sigaction sa;
if (sigaction(i, NULL, &sa) != 0) {
// !!! !bn: error handling. EINTR possible?
}
if ((sa.sa_flags & SA_SIGINFO) && (sa.sa_sigaction != NULL)) continue;
if (!(sa.sa_flags & SA_SIGINFO) && (sa.sa_handler != NULL)) continue;
return i;
}
}
return -1;
}
TSockSys::TSockSys() {
IAssert(Active==false);
TimerSignal = GetFreeRTSig(SIGRTMIN);
ResolverSignal = GetFreeRTSig(TimerSignal+1);
sigset_t css;
sigemptyset(&css);
sigaddset(&css, SIGIO);
sigaddset(&css, TimerSignal);
sigaddset(&css, ResolverSignal);
sigaddset(&css, SIGPIPE); // these two could kill the process on socket errors / OOB.
sigaddset(&css, SIGURG); // we'll handle errors synchronously
sigprocmask(SIG_BLOCK, &css, NULL);
ET_epoll_fd = epoll_create(20);
LT_epoll_fd = epoll_create(20);
Active = true;
}
TSockSys::~TSockSys() {
if (Active){
IAssert(ActiveSockHndH.Len()==0);
IAssert(ActiveSockEventIdH.Len()==0);
close(ET_epoll_fd);
close(LT_epoll_fd);
sigset_t css;
sigemptyset(&css);
sigaddset(&css, SIGIO);
sigaddset(&css, TimerSignal);
sigaddset(&css, ResolverSignal);
sigprocmask(SIG_UNBLOCK, &css, NULL);
TimerSignal = ResolverSignal = -1;
Active = false;
}
}
void TSockSys::SetupFAsync(int fd) {
IAssert(Active==true);
fcntl(fd, F_SETOWN, (int)getpid());
int flags = fcntl(fd, F_GETFL);
flags |= O_NONBLOCK|O_ASYNC;
fcntl(fd, F_SETFL, flags);
struct epoll_event epe;
epe.events = EPOLLIN;
epe.data.fd = fd;
if (epoll_ctl(LT_epoll_fd, EPOLL_CTL_ADD, fd, &epe) == -1) perror("epoll_ctl"); // !!!! TODO: kaksn assert nej bi dau tle?
epe.events = EPOLLOUT | EPOLLET;
if (epoll_ctl(ET_epoll_fd, EPOLL_CTL_ADD, fd, &epe) == -1) perror("epoll_ctl");
}
void TSockSys::DoIOEvent(struct epoll_event *e) {
printf(" event = %d on fd = %d\n", e->events, e->data.fd);
TSockHnd SockHnd=e->data.fd;
int Events = e->events;
if (IsSockHnd(SockHnd)){
int SockEventId=GetSockEventId(SockHnd);
PSockEvent SockEvent=GetSockEvent(SockEventId);
//SetSockActive(SockHnd, true);
SetSockEventActive(SockEventId, true);
// what was the event?
// note: close is handled in OnRead()
// connect generates IN and OUT events, but only one is delivered [lt/et descriptors are separate, event aggregation not done]
// -> if socket not connected
// * OUT event ignored
// * IN event triggers OnConnect [if the first-delivered event triggered connect,
// then OnRead() could be called on freshly connected socket and nothing to read.]
// -> if it's a listening socket, do OnAccept()
// err, oob, read|close, write
try {
int ErrCd=TSock::GetSockErr(SockHnd);
if (ErrCd==0) {
if (Events & EPOLLIN) {
if (SockHndToStateH[SockHnd] == scsConnected) {
OnRead(SockHnd, SockEvent);
} else if (SockHndToStateH[SockHnd] == scsListening) {
OnAccept(SockHnd, SockEvent);
} else {
SockHndToStateH[SockHnd] = scsConnected;
OnConnect(SockHnd, SockEvent);
}
}
if ((Events & EPOLLOUT)&&(SockHndToStateH[SockHnd] == scsConnected)) {
OnWrite(SockHnd, SockEvent);
}
if (Events & EPOLLPRI) {
OnOob(SockHnd, SockEvent); }
if (Events & EPOLLERR) {
OnError(SockHnd, SockEvent, TSock::GetSockErr(SockHnd)); } // !bn: !!! to je blo not ze pred win32 SockErrReportHnd in processing kodo. a je prov?
if (Events & EPOLLHUP) {
// !!! a nas to sploh zanima? not really - dokler podatki so jih beremo, ko jih zmanjka jih je konc. al kako.
}
} else {
OnError(SockHnd, SockEvent, ErrCd);
}
} catch (...){
SaveToErrLog("Exception from 'switch (EventCd)'");
}
SetSockEventActive(SockEventId, false);
//SetSockActive(SockHnd, false);
}
}
void TSockSys::DoIO() {
printf(":: do_io\n");
while (true) { // process ALL I/O events, 64+64 at a time, interleaved. that's why DelayedIO.
struct epoll_event evt[2][64];
int ret = epoll_wait(LT_epoll_fd, evt[0], 64, 0);
printf("lt epoll_wait.ret = %d\n", ret);
int eret = epoll_wait(ET_epoll_fd, evt[1], 64, 0);
printf("et epoll_wait.ret = %d\n", eret);
if (ret == 0 && eret == 0) break;
for (int i=0;i<ret;i++) DoIOEvent(&evt[0][i]);
for (int i=0;i<eret;i++) DoIOEvent(&evt[1][i]);
}
}
void TSockSys::DoTimer(siginfo_t *si) {
int TimerId = si->si_int;
if (TSockSys::IsTimer(TimerId)){
PTimer Timer=TSockSys::GetTimer(TimerId)();
Timer->IncTicks();
try {
Timer->OnTimeOut();
} catch (...){
SaveToErrLog("Exception from Timer->OnTimeOut();");
}
}
}
void TSockSys::DoResolver(siginfo_t *si) {
int SockHostHnd = si->si_int;
if (TSockSys::IsSockHost(SockHostHnd)) {
PSockHost SockHost=TSockSys::GetSockHost(SockHostHnd);
TSockHostStatus Status=TSockHost::GetStatus(&(SockHost->GAI));
SockHost->GetFromHostEnt(Status, &(SockHost->GAI));
DelSockHost(SockHostHnd);
try {
OnGetHost(SockHost);
} catch (...){
SaveToErrLog("Exception from OnGetHost(SockHost);");
}
}
}
void TSockSys::AsyncLoop() {
bool DelayedIO = false;
while (true) {
int ret;
sigset_t ss;
siginfo_t si;
sigemptyset(&ss);
sigaddset(&ss, SIGIO);
sigaddset(&ss, TimerSignal);
sigaddset(&ss, ResolverSignal);
if (DelayedIO) {
struct timespec tsp;
tsp.tv_sec = tsp.tv_nsec = 0;
ret = sigtimedwait(&ss, &si, &tsp);
} else {
ret = sigwaitinfo(&ss, &si);
}
if (ret == -1) {
if (errno == EINTR) continue;
if (errno == EAGAIN) { DelayedIO = false; DoIO(); }
} else {
if (si.si_signo == SIGIO) {
DelayedIO = true;
} else if (si.si_signo == TimerSignal) {
DoTimer(&si);
} else if (si.si_signo == ResolverSignal) {
DoResolver(&si);
}
}
}
}
#endif
void TSockSys::AddSock(
const int& SockId, const TSockHnd& SockHnd, const int& SockEventId){
IAssert(Active);
SockIdToHndH.AddDat(SockId, SockHnd);
SockHndToIdH.AddDat(SockHnd, SockId);
SockHndToEventIdH.AddDat(SockHnd, SockEventId);
#ifdef GLib_UNIX
SockHndToStateH.AddDat(SockHnd, scsCreated);
SetupFAsync(SockHnd);
#endif
}
void TSockSys::DelSock(const int& SockId){
IAssert(Active);
TSockHnd SockHnd=TSockHnd(SockIdToHndH.GetDat(SockId));
IAssert(!IsSockActive(SockHnd));
// delete socket entries
SockIdToHndH.DelKey(SockId);
SockHndToIdH.DelKey(SockHnd);
SockHndToEventIdH.DelKey(SockHnd);
#ifdef GLib_UNIX
SockHndToStateH.DelKey(SockHnd);
#endif
// kill associated timer if exists
DelIfSockTimer(SockId);
}
#ifdef GLib_UNIX
// !!! TODO: prever za vse kar si splitnu zarad SOCKET_ERROR - a je v vseh primerih -1 to ? kaj je to na windowsih?
// v tem primeru bi blo upraviceno tole generalno nardit pa dat mir.
#define SOCKET_ERROR -1
// !bn: GLib_UNIX -> OnReadOrClose() :)
// "all subsequent reads will return -1" -> prvic ko recv() vrne 0, mormo klicat onclose()
// - kje sm ze to brau?
// eniwejz. al tko, al pa dobimo ENOTCONN. druzga ze ne more bit.
#endif
void TSockSys::OnRead(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
TMem Mem(MxSockBfL);
char* Bf=new char[MxSockBfL]; int BfL;
do {
BfL=recv(SockHnd, Bf, MxSockBfL, 0);
if (BfL!=SOCKET_ERROR){
Mem.AddBf(Bf, BfL); SockBytesRead+=BfL;}
} while ((BfL>0)&&(BfL!=SOCKET_ERROR));
#ifdef GLib_UNIX
bool Closed = (BfL == 0);
#endif
delete[] Bf;
if (Closed && !SockEvent.Empty()){
PSIn SIn=Mem.GetSIn();
SockEvent->OnRead(int(GetSockId(SockHnd)), SIn);
}
}
void TSockSys::OnWrite(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
if (!SockEvent.Empty()){
SockEvent->OnWrite(int(GetSockId(SockHnd)));}
}
void TSockSys::OnOob(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
if (!SockEvent.Empty()){
SockEvent->OnOob(int(GetSockId(SockHnd)));}
}
void TSockSys::OnAccept(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
PSock AccSock=TSock::Accept(SockHnd, SockEvent);
if (AccSock() == NULL) return; // !bn: discard async networks errors; don't die on them.
if (!SockEvent.Empty()){
SockEvent->OnAccept(AccSock->GetSockId(), AccSock);}
}
void TSockSys::OnConnect(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
if (!SockEvent.Empty()){
SockEvent->OnConnect(int(GetSockId(SockHnd)));}
}
void TSockSys::OnClose(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
if (!SockEvent.Empty()){
SockEvent->OnClose(int(GetSockId(SockHnd)));}
}
void TSockSys::OnTimeOut(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
if (!SockEvent.Empty()){
SockEvent->OnTimeOut(int(GetSockId(SockHnd)));}
}
void TSockSys::OnError(
const TSockHnd& SockHnd, const PSockEvent& SockEvent, const int& ErrCd){
if (!SockEvent.Empty()){
SockEvent->OnError(int(GetSockId(SockHnd)), ErrCd, GetErrStr(ErrCd));}
}
void TSockSys::OnGetHost(const PSockHost& SockHost){
if (IsSockEvent(SockHost->GetSockEventId())){
PSockEvent SockEvent=SockHost->GetSockEvent();
if (!SockEvent.Empty()){
SockEvent->OnGetHost(SockHost);}
}
}
TStr TSockSys::GetStatusStr(){
TChA ChA;
ChA+="Sockets: "; ChA+=TInt::GetStr(SockIdToHndH.Len()); ChA+="\r\n";
ChA+="Host-Resolutions: "; ChA+=TInt::GetStr(HndToSockHostH.Len()); ChA+="\r\n";
ChA+="Socket-Events: "; ChA+=TInt::GetStr(IdToSockEventH.Len()); ChA+="\r\n";
ChA+="Report-Events: "; ChA+=TInt::GetStr(IdToReportEventH.Len()); ChA+="\r\n";
ChA+="Timers: "; ChA+=TInt::GetStr(IdToTimerH.Len()); ChA+="\r\n";
return ChA;
}
/////////////////////////////////////////////////
// Socket-Event
int TSockEvent::LastSockEventId=0;
TSockEvent::~TSockEvent(){
IAssert(!TSockSys::IsSockEventActive(SockEventId));
}
bool TSockEvent::IsReg(const PSockEvent& SockEvent){
return TSockSys::IsSockEvent(SockEvent);
}
void TSockEvent::Reg(const PSockEvent& SockEvent){
IAssert(!TSockSys::IsSockEvent(SockEvent));
TSockSys::AddSockEvent(SockEvent);
}
void TSockEvent::UnReg(const PSockEvent& SockEvent){
IAssert(TSockSys::IsSockEvent(SockEvent));
TSockSys::DelSockEvent(SockEvent);
}
/////////////////////////////////////////////////
// Socket-Host
int TSockHost::LastSockHostId = 0;
#ifdef GLib_WIN32
void TSockHost::GetFromHostEnt(
const TSockHostStatus& _Status, const hostent* HostEnt){
if ((Status=_Status)==shsOk){
IAssert(HostEnt!=NULL);
IAssert(HostEnt->h_addrtype==AF_INET);
IAssert(HostEnt->h_length==4);
HostNmV.Add(TStr(HostEnt->h_name).GetLc());
int HostNmN=0;
while (HostEnt->h_aliases[HostNmN]!=NULL){
HostNmV.Add(TStr(HostEnt->h_aliases[HostNmN]).GetLc()); HostNmN++;}
int IpNumN=0;
while (HostEnt->h_addr_list[IpNumN]!=NULL){
TStr IpNum=
TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][0]))+"."+
TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][1]))+"."+
TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][2]))+"."+
TInt::GetStr(uchar(HostEnt->h_addr_list[IpNumN][3]));
IpNumV.Add(IpNum); IpNumN++;
}
}
}
#elif defined(GLib_UNIX)
// !!! tole nalozi TSockHost iz addrinfo strukture (hostent na starih unixih in win32)
// !!! zato je TSockSys nas frend - da lahko zahteva da se nalozimo iz async odgovora.
// addrinfa ni treba posiljat, zato ker ga async dobimo direkt v nas gaicb
void TSockHost::GetFromHostEnt(
const TSockHostStatus& _Status, gaicb *gcb) {
if ((Status=_Status)==shsOk){
// !!! TODO !bn: implement load from addrinfo.
if ((Status=_Status)==shsOk) {
IAssert(gcb!=NULL);
addrinfo *ai = gcb->ar_result;
// !!! kaj pa ce host nima imena? v vsakem primeru v name vtaknemo query. drgac bi biu lahko cist prazn.
HostNmV.Add(gcb->ar_name);
//HostNmV.Add(HNm);
free((char *)gcb->ar_name);
while (ai) {
if (ai->ai_canonname) HostNmV.Add(ai->ai_canonname);
if (ai->ai_family == PF_INET) {
uchar *ia = (uchar*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr.s_addr);
// !!! tole je pa narobe. sej je v network-order zapisan ip?
TStr IpNum=
TInt::GetStr(ia[0])+"." + TInt::GetStr(ia[1])+"."+
TInt::GetStr(ia[2])+"." + TInt::GetStr(ia[3]);
IpNumV.Add(IpNum);
}
addrinfo *oai = ai;
ai = ai->ai_next;
freeaddrinfo(oai);
}
}
}
}
#endif
PSockEvent TSockHost::GetSockEvent() const {
return TSockSys::GetSockEvent(SockEventId);
}
bool TSockHost::IsIpNum(const TStr& HostNm){
int HostNmLen=HostNm.Len();
for (int ChN=0; ChN<HostNmLen; ChN++){
if (TCh::IsAlpha(HostNm[ChN])){return false;}}
return true;
}
TStr TSockHost::GetIpNum(const uint& IpNum){
TChA IpNumChA;
IpNumChA+=TUInt::GetStr(IpNum/0x1000000);
IpNumChA+='.'; IpNumChA+=TUInt::GetStr((IpNum/0x10000)%0x100);
IpNumChA+='.'; IpNumChA+=TUInt::GetStr((IpNum/0x100)%0x100);
IpNumChA+='.'; IpNumChA+=TUInt::GetStr(IpNum%0x100);
return IpNumChA;
}
#ifdef GLib_WIN32
PSockHost TSockHost::GetSyncSockHost(const TStr& HostNm){
hostent* HostEnt; TSockHostStatus Status(shsUndef);
if ((HostNm.Len()>0)&&(!IsIpNum(HostNm))){
HostEnt=gethostbyname(HostNm.CStr());
if (HostEnt==NULL){Status=GetStatus(WSAGetLastError());}
else {Status=shsOk;}
} else {
uint HostIpNum=inet_addr(HostNm.CStr());
if (HostIpNum==INADDR_NONE){
Status=shsError; HostEnt=NULL;
} else {
HostEnt=gethostbyaddr((char*)&HostIpNum, 4, AF_INET);
if (HostEnt==NULL){Status=GetStatus(WSAGetLastError());}
else {Status=shsOk;}
}
}
PSockHost SockHost=PSockHost(new TSockHost());
SockHost->GetFromHostEnt(Status, HostEnt);
return SockHost;
}
void TSockHost::GetAsyncSockHost(
const TStr& HostNm, const PSockEvent& SockEvent){
PSockHost SockHost=PSockHost(new TSockHost(SockEvent));
HANDLE SockHostHnd=0;
// if ((HostNm.Len()>0)&&(!IsIpNum(HostNm))){
if ((HostNm.Len()>0)){
SockHostHnd=WSAAsyncGetHostByName(TSockSys::GetDnsWndHnd(),
TSockSys::GetDnsMsgHnd(), HostNm.CStr(),
SockHost->HostEntBf, MAXGETHOSTSTRUCT);
} else {
uint HostIpNum=inet_addr(HostNm.CStr());
if (HostIpNum==INADDR_NONE){
SockHostHnd=0;
} else {
SockHostHnd=WSAAsyncGetHostByAddr(TSockSys::GetDnsWndHnd(),
TSockSys::GetDnsMsgHnd(), (char*)&HostIpNum, 4, AF_INET,
SockHost->HostEntBf, MAXGETHOSTSTRUCT);
}
}
EAssertR(SockHostHnd!=0, TSockSys::GetErrStr(WSAGetLastError()));
if (SockHostHnd!=0){
TSockSys::AddSockHost(TUInt64(SockHostHnd), SockHost);
}
}
TSockHostStatus TSockHost::GetStatus(const int& ErrCd){
switch (ErrCd){
case 0: return shsOk;
case WSAHOST_NOT_FOUND: return shsHostNotFound;
case WSATRY_AGAIN: return shsTryAgain;
default: return shsError;
}
}
TSockHost::~TSockHost(){}
#elif defined(GLib_UNIX)
TSockHostStatus TSockHost::GetStatus(gaicb *gcb){
switch (gai_error(gcb)){
case 0: return shsOk;
case EAI_NONAME: return shsHostNotFound;
case EAI_AGAIN: return shsTryAgain;
case EAI_INPROGRESS: return shsInProgress;
default: return shsError;
}
}
TStr TSockHost::GetGaiErrStr(const int ErrCd) {
/* switch (ErrCd) {
case EAI_AGAIN: return "The name could not be resolved at this time.";
case EAI_BADFLAGS: return "The flags had an invalid value.";
case EAI_FAIL: return "A non-recoverable error occured.";
case EAI_FAMILY: return "The address family was not recognized or the address length was invalid.";
case EAI_MEMORY: return "Memory allocation failure.";
case EAI_NONAME: return "The name does not resolve for the supplied parameters.";
case EAI_SERVICE: return "The service passed was not recognized for the specified socket type.";
case EAI_INPROGRESS: return "The asynchronous lookup has not yet finished.";
case EAI_INTR: return "The operation was interrupted by a signal.";
case EAI_CANCELED: return "The asynchronous request was canceled.";
case EAI_NOTCANCELED: return "The asynchronous request was not canceled.";
case EAI_ALLDONE: return "Nothing had to be done.";
case EAI_SYSTEM: return TSockSys::GetErrStr(errno);
default: return "Unknown error.";
}
*/
return gai_strerror(ErrCd);
}
TSockHostStatus TSockHost::SubmitQuery(const TStr &HostStr, gaicb *gcb, addrinfo *request, bool sync, uint32 EventId) {
sigevent ev;
if (!sync) {
ev.sigev_notify = SIGEV_SIGNAL;
ev.sigev_signo = TSockSys::ResolverSignal;
ev.sigev_value.sival_int = EventId;
ev.sigev_notify_attributes = NULL;
}
memset(gcb, 0, sizeof(*gcb));
memset(request, 0, sizeof(*request));
gcb->ar_name = strdup(HostStr.CStr()); // !!! TODO: pocistt za tem. oz pocistt sploh za vsemskup. like v GetFromHostEnt je treba tole sprostit in sprostit gcb result.
// HNm = HostStr;
// !!! TODO !!! MEMORY LEAK !!!
// ne res. ar_name je const. submitquery je pa static. torej ne more spreminjat objektov.
// !!!!!!!!!!!!!!!!!!!!! nekak freeji result. :)
//gcb->ar_name = HostStr.CStr();
if (gcb->ar_name == NULL) return shsError; // v destruktorju pazi .. ce si naredu submit, si mogu tud pobrat rezultate. ce je pa outstanding, mors pa vsaj skenslat in
gcb->ar_service = NULL; // deregistrirat, drugac bos v velki p***. vbistvu mors PREJ unregister nardit predn cekiras ce si spucu za sabo,
gcb->ar_request = request; // drugac med pucanjem lahk pride rezultat not, pa mas leak.
gcb->ar_result = NULL;
/*if (IsIpNm(HostStr))*/
request->ai_flags = AI_CANONNAME;
request->ai_family = PF_INET;
// gcb->ar_request->ai_flags = AI_CANONNAME; // !!! ce se odlocas o completionu na podlagi Status polja, preglej ce pravilno povsod vpises to polje.
// gcb->ar_request->ai_family = PF_INET;
gcb->ar_request = request;
gaicb *gca[1] = { gcb };
int ret = getaddrinfo_a(sync?GAI_WAIT:GAI_NOWAIT, gca, 1, sync?NULL:&ev);
if (ret == 0) {
return shsOk;
} else {
return GetStatus(gcb);
}
}
PSockHost TSockHost::GetSyncSockHost(const TStr& HostStr){
gaicb gcb; addrinfo ai; TSockHostStatus Status(shsUndef);
Status = SubmitQuery(HostStr, &gcb, &ai);
PSockHost SockHost=PSockHost(new TSockHost());
SockHost->GetFromHostEnt(Status, &gcb);
return SockHost;
}
void TSockHost::GetAsyncSockHost(
const TStr& HostStr, const PSockEvent& SockEvent){
PSockHost SockHost=PSockHost(new TSockHost(SockEvent));
SockHost->Status = shsInProgress;
TSockHostStatus Status = SubmitQuery(HostStr, &(SockHost->GAI), &(SockHost->request), false, SockHost->SockHostId);
EAssertR(Status == shsOk, TSockHost::GetGaiErrStr(gai_error(&(SockHost->GAI))));
if (Status == shsOk){
TSockSys::AddSockHost(SockHost->SockHostId, SockHost);
} else {
SockHost->Status = Status; // need this for the destructor.
}
}
TSockHost::~TSockHost() {
if (Status == shsInProgress) {
TSockSys::DelSockHost(SockHostId); // we don't want an async result to happen if we don't exist anymore. do we?
int ret;
do {
ret = gai_cancel(&GAI); // !!! problem. tole lahko vrne 'glih dugaja'. ce izmaknemo objekt, bo stala.
} while (ret == EAI_NOTCANCELED); // !!! ni lepo da se vrtimo v zanki, ampak objekta NE SMEMO BRISAT.
addrinfo *ai = GAI.ar_result;
while (ai) {
addrinfo *oai = ai;
ai = ai->ai_next;
freeaddrinfo(oai);
}
free((char*)GAI.ar_name); // it was allocated once and never cleaned up by AI->SH
} // !!! povozil smo const kvalifikator. upam da se svet ne bo podru. :)
}
#endif
PSockHost TSockHost::GetLocalSockHost(){
PSockHost SockHost=TSockHost::GetSyncSockHost(LocalHostNm);
if (SockHost->IsOk()){
SockHost=TSockHost::GetSyncSockHost(SockHost->GetHostNm());}
return SockHost;
}
const TStr TSockHost::LocalHostNm("localhost");
/////////////////////////////////////////////////
// Socket
int TSock::LastSockId=0;
TSock::TSock(const PSockEvent& SockEvent):
SockId(++LastSockId), SockHnd(0),
SockEventId(SockEvent->GetSockEventId()){
SockHnd=socket(PF_INET, SOCK_STREAM, 0); // !bn: changed. was: AF_INET. it is the same, for now. documentation says PF_INET.
#ifdef GLib_WIN32
EAssertR(SockHnd!=INVALID_SOCKET, TSockSys::GetErrStr(WSAGetLastError()));
#elif defined(GLib_UNIX)
EAssertR(SockHnd!=-1, TSockSys::GetErrStr(TSock::GetSockErr(SockHnd)));
#endif
TSockSys::AddSock(SockId, SockHnd, SockEventId);
IAssert(TSockEvent::IsReg(SockEvent));
}
TSock::TSock(const TSockHnd& _SockHnd, const PSockEvent& SockEvent):
SockId(++LastSockId), SockHnd(_SockHnd),
SockEventId(SockEvent->GetSockEventId()){
TSockSys::AddSock(SockId, SockHnd, SockEventId);
IAssert(TSockEvent::IsReg(SockEvent));
}
TSock::~TSock(){
IAssert(!TSockSys::IsSockActive(SockHnd));
TSockSys::DelSock(SockId);
#ifdef GLib_WIN32
closesocket(SockHnd);
#elif defined(GLib_UNIX)
close(SockHnd);
#endif
//EAssertR(closesocket(SockHnd)==0, TSockSys::GetErrStr(WSAGetLastError()));
}
PSockEvent TSock::GetSockEvent() const {
return TSockSys::GetSockEvent(SockEventId);
}
int TSock::GetSockErr(const TSockHnd s) {
int err;
socklen_t sz = sizeof(err);
getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &sz);
return err;
}
void TSock::Listen(const int& PortN){
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
SockAddr.sin_family=AF_INET;
#ifdef GLib_WIN32
SockAddr.sin_addr.s_addr=INADDR_ANY;
#elif defined(GLib_UNIX)
SockAddr.sin_addr.s_addr=htonl(INADDR_ANY); // !bn: i think this is the 'correct' formulation. INADDR_ANY is 0 anyway, but perhaps might not remain so forever
#endif
SockAddr.sin_port=htons(u_short(PortN));
#ifdef GLib_WIN32
EAssertR(
bind(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr))==0,
TSockSys::GetErrStr(WSAGetLastError()));
EAssertR(
WSAAsyncSelect(SockHnd, TSockSys::GetSockWndHnd(),
TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0,
TSockSys::GetErrStr(WSAGetLastError()));
EAssertR(
listen(SockHnd, SOMAXCONN)==0,
TSockSys::GetErrStr(WSAGetLastError()));
#elif defined(GLib_UNIX)
// !!! copypaste :/ [almost]
// replace WSAGetLastError() with getsockopt() - returns per-socket error
// instead per-process/thread error which might be already invalid.
EAssertR(
bind(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr))==0,
TSockSys::GetErrStr(GetSockErr(SockHnd)));
// !!! why was there a select here?
EAssertR(
listen(SockHnd, SOMAXCONN)==0,
TSockSys::GetErrStr(GetSockErr(SockHnd)));
TSockSys::SockHndToStateH[SockHnd] = scsListening;
#endif
}
int TSock::GetPortAndListen(const int& MnPortN){
int PortN=MnPortN-1;
int ErrCd=0;
forever {
PortN++;
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
SockAddr.sin_family=AF_INET;
#ifdef GLib_WIN32
SockAddr.sin_addr.s_addr=INADDR_ANY;
#elif defined(GLib_UNIX)
SockAddr.sin_addr.s_addr=htonl(INADDR_ANY);
#endif
SockAddr.sin_port=htons(u_short(PortN));
int OkCd=bind(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr));
#ifdef GLib_WIN32
if (OkCd==SOCKET_ERROR){
ErrCd=WSAGetLastError();
if (ErrCd!=WSAEADDRINUSE){break;}
} else {
ErrCd=0; break;
}
#elif defined(GLib_UNIX)
if (OkCd==-1){
ErrCd=GetSockErr(SockHnd);
if (ErrCd!=EACCES){break;} // !!! !bn: a res bind vrne EACCESS ce ne more bindat?
} else {
ErrCd=0; break;
}
#endif
}
EAssertR(ErrCd==0, TSockSys::GetErrStr(ErrCd));
#ifdef GLib_WIN32
EAssertR(
WSAAsyncSelect(SockHnd, TSockSys::GetSockWndHnd(),
TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0,
TSockSys::GetErrStr(WSAGetLastError()));
EAssertR(
listen(SockHnd, SOMAXCONN)==0,
TSockSys::GetErrStr(WSAGetLastError()));
#elif defined(GLib_UNIX)
// !!! copypaste because of wsagetlasterror.
EAssertR(
listen(SockHnd, SOMAXCONN)==0,
TSockSys::GetErrStr(GetSockErr(SockHnd)));
#endif
return PortN;
}
void TSock::Connect(const PSockHost& SockHost, const int& PortN){
IAssert(SockHost->IsOk());
#ifdef GLib_WIN32
uint HostIpNum=inet_addr(SockHost->GetIpNum().CStr());
IAssert(HostIpNum!=INADDR_NONE);
#elif defined(GLib_UNIX)
uint HostIpNum;
IAssert(inet_aton(SockHost->GetIpNum().CStr(), (in_addr*)&HostIpNum) == 0); // !!! prov typecast?
#endif
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
memcpy(&(SockAddr.sin_addr), &HostIpNum, sizeof(HostIpNum));
SockAddr.sin_family=AF_INET;
SockAddr.sin_port=htons(u_short(PortN));
#ifdef GLib_WIN32
EAssertR(
WSAAsyncSelect(SockHnd, TSockSys::GetSockWndHnd(),
TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0,
TSockSys::GetErrStr(WSAGetLastError()));
#endif
int ErrCd=connect(SockHnd, (sockaddr*)&SockAddr, sizeof(SockAddr));
EAssertR(
#ifdef GLib_WIN32
(ErrCd==SOCKET_ERROR)&&(WSAGetLastError()==WSAEWOULDBLOCK),
#elif defined(GLib_UNIX)
// !!! !bn: tole je pa resno: na errno se ne gre zanasat ker ni mt-safe, ampak v errno-ju se najde EINPROGRESS. socket je pa lahko ze sconnectan do takrat.
// a je tale pogoj - EINPROGRESS || 0 uredu?
((ErrCd==-1)&&(GetSockErr(SockHnd)==EINPROGRESS))||(GetSockErr(SockHnd) == 0),
#endif
"Unsuccessful socket-connect.");
}
void TSock::Send(const PSIn& SIn, bool& Ok, int& ErrCd){
if (!SIn.Empty()){UnsentBf+=SIn;}
Ok=true; ErrCd=0;
int SentChs=0;
while (SentChs<UnsentBf.Len()){
int SendBfL=UnsentBf.Len()-SentChs;
if (SendBfL>TSockSys::MxSockBfL){SendBfL=TSockSys::MxSockBfL;}
int LSentChs=send(SockHnd, &UnsentBf[SentChs], SendBfL, 0);
#ifdef GLib_WIN32
if (LSentChs==SOCKET_ERROR){
ErrCd=WSAGetLastError();
Ok=(ErrCd==WSAEWOULDBLOCK);
#elif defined(GLib_UNIX)
if (LSentChs==-1){
ErrCd=GetSockErr(SockHnd);
Ok=(ErrCd==EWOULDBLOCK);
#endif
break;
} else {
SentChs+=LSentChs;
TSockSys::SockBytesWritten+=LSentChs;
}
}
UnsentBf.Del(0, SentChs-1);
}
void TSock::Send(const PSIn& SIn){
bool Ok; int ErrCd; Send(SIn, Ok, ErrCd);
#ifdef GLib_WIN32
if (!Ok){
ESAssert(PostMessage(
TSockSys::GetSockWndHnd(), TSockSys::SockErrMsgHnd, SockHnd, ErrCd));
}
#elif defined(GLib_UNIX)
if (!Ok){ // !!! !bn: why does win32 code post the error message instead of calling errorhandler?
// i don't want to do it by writing (sockhnd, errcd) in a pipe, because of a possible race condition (sockhnd is not unique)
GetSockEvent()->OnError(SockId, ErrCd, TSockSys::GetErrStr(ErrCd));
}
#endif
}
void TSock::SendSafe(const PSIn& SIn){
bool Ok; int ErrCd; Send(SIn, Ok, ErrCd);
}
TStr TSock::GetPeerIpNum() const {
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
#ifdef GLib_WIN32
int NmLen=sizeof(sockaddr_in);
#elif defined(GLib_UNIX)
socklen_t NmLen=sizeof(sockaddr_in);
#endif
EAssertR(
getpeername(SockHnd, (sockaddr*)&SockAddr, &NmLen)==0,
#ifdef GLib_WIN32
TSockSys::GetErrStr(WSAGetLastError()));
TStr IpNum=
TInt::GetStr(SockAddr.sin_addr.s_net)+"."+
TInt::GetStr(SockAddr.sin_addr.s_host)+"."+
TInt::GetStr(SockAddr.sin_addr.s_lh)+"."+
TInt::GetStr(SockAddr.sin_addr.s_impno);
#elif defined(GLib_UNIX)
TSockSys::GetErrStr(GetSockErr(SockHnd)));
uchar *s_addr = (uchar*)&SockAddr.sin_addr.s_addr;
TStr IpNum=
TInt::GetStr(s_addr[4])+"."+ // !!! like .. check. a ma kakrsnkol smisu tole.
TInt::GetStr(s_addr[3])+"."+
TInt::GetStr(s_addr[2])+"."+
TInt::GetStr(s_addr[1]);
#endif
return IpNum;
}
TStr TSock::GetLocalIpNum() const {
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
#ifdef GLib_WIN32
int NmLen=sizeof(sockaddr_in);
#elif defined(GLib_UNIX)
socklen_t NmLen=sizeof(sockaddr_in);
#endif
EAssertR(
getsockname(SockHnd, (sockaddr*)&SockAddr, &NmLen)==0,
#ifdef GLib_WIN32
TSockSys::GetErrStr(WSAGetLastError()));
TStr IpNum=
TInt::GetStr(SockAddr.sin_addr.s_net)+"."+
TInt::GetStr(SockAddr.sin_addr.s_host)+"."+
TInt::GetStr(SockAddr.sin_addr.s_lh)+"."+
TInt::GetStr(SockAddr.sin_addr.s_impno);
#elif defined(GLib_UNIX)
TSockSys::GetErrStr(GetSockErr(SockHnd)));
uchar *s_addr = (uchar*)&SockAddr.sin_addr.s_addr;
TStr IpNum=
TInt::GetStr(s_addr[4])+"."+ // !!! like .. check. a ma kakrsnkol smisu tole.
TInt::GetStr(s_addr[3])+"."+
TInt::GetStr(s_addr[2])+"."+
TInt::GetStr(s_addr[1]);
#endif
return IpNum;
}
void TSock::PutTimeOut(const int& MSecs){
TSockSys::AddSockTimer(SockId, MSecs);
}
void TSock::DelTimeOut(){
TSockSys::DelIfSockTimer(SockId);
}
PSock TSock::Accept(const TSockHnd& SockHnd, const PSockEvent& SockEvent){
sockaddr_in SockAddr;
#ifdef GLib_WIN32
int SockAddrLen=sizeof(SockAddr);
#elif defined(GLib_UNIX)
socklen_t SockAddrLen=sizeof(SockAddr);
#endif
memset(&SockAddr, 0, sizeof(SockAddr));
TSockHnd AccSockHnd=accept(SockHnd, (sockaddr*)&SockAddr, &SockAddrLen);
#ifdef GLib_WIN32
EAssertR(
AccSockHnd!=INVALID_SOCKET,
TSockSys::GetErrStr(WSAGetLastError()));
PSock AccSock=PSock(new TSock(AccSockHnd, SockEvent));
EAssertR(
WSAAsyncSelect(AccSock->GetSockHnd(), TSockSys::GetSockWndHnd(),
TSockSys::GetSockMsgHnd(), TSockSys::GetAllSockEventCdSet())==0,
TSockSys::GetErrStr(WSAGetLastError()));
return AccSock;
#elif defined(GLib_UNIX)
if (AccSockHnd == -1) {
// !!! !bn: a bi rajs GetSockErr()?
if ((errno == EWOULDBLOCK) || (errno == ECONNABORTED) || (errno == EINTR)) return NULL; // !!! ECONNABORTED -> just return NULL.
EAssertR( // !!! !bn: overkill. ret==-1 se lahko velikrat zgodi, mogl bi sam preprost ignorirat take evente pa vrnt null.
AccSockHnd!=-1,
TSockSys::GetErrStr(GetSockErr(SockHnd)));
return NULL;
} else {
PSock AccSock=PSock(new TSock(AccSockHnd, SockEvent));
TSockSys::SockHndToStateH[AccSock->SockHnd] = scsConnected;
return AccSock;
}
#endif
}
TStr TSock::GetSockSysStatusStr(){
return TSockSys::GetStatusStr();
}
uint64 TSock::GetSockSysBytesRead(){
return TSockSys::SockBytesRead;
}
uint64 TSock::GetSockSysBytesWritten(){
return TSockSys::SockBytesWritten;
}
bool TSock::IsSockId(const int& SockId){
return TSockSys::IsSockId(SockId);
}
/////////////////////////////////////////////////
// Report-Event
int TReportEvent::LastReportEventId=0;
void TReportEvent::SendReport(){
#ifdef GLib_WIN32
TSockSys::AddReportEvent(this);
ESAssert(PostMessage(
TSockSys::GetReportWndHnd(), TSockSys::GetReportMsgHnd(), 0, ReportEventId));
#elif defined(GLib_UNIX)
Fail; // !!! not implemented. [obsolete?]
#endif
}
/////////////////////////////////////////////////
// Timer
int TTTimer::LastTimerId=0;
TTTimer::TTTimer(const int& _TimeOut):
TimerId(++LastTimerId),
#ifdef GLib_WIN32
TimerHnd(0),
#endif
TimeOut(_TimeOut),
Ticks(0), StartTm(TSecTm::GetCurTm())
{
#ifdef GLib_UNIX
sigevent evp;
evp.sigev_notify = SIGEV_SIGNAL;
evp.sigev_signo = TSockSys::TimerSignal;
evp.sigev_value.sival_int = TimerId;
evp.sigev_notify_attributes = NULL;
IAssert(timer_create(CLOCK_MONOTONIC, &evp, &TimerHnd) == 0);
#endif
IAssert(TimeOut>=0);
StartTimer(TimeOut);
}
TTTimer::~TTTimer(){
StopTimer();
#ifdef GLib_UNIX
timer_delete(TimerHnd);
#endif
}
void TTTimer::StartTimer(const int& _TimeOut){
IAssert((_TimeOut==-1)||(_TimeOut>=0));
// if _TimeOut==-1 use previous TimeOut
if (_TimeOut!=-1){
TimeOut=_TimeOut;}
// stop current-timer
StopTimer();
if (TimeOut>0){
#ifdef GLib_WIN32
TimerHnd=uint(SetTimer(
TSockSys::GetTimerWndHnd(), UINT(TimerId), UINT(TimeOut), NULL));
ESAssert(TimerHnd!=0);
#elif defined(GLib_UNIX)
itimerspec its;
its.it_value.tv_sec = its.it_interval.tv_sec = TimeOut / 1000;
its.it_value.tv_nsec = its.it_interval.tv_nsec = (TimeOut % 1000) * 1000000;
EAssertR(timer_settime(TimerHnd, 0, &its, NULL) == 0, TSockSys::GetErrStr(errno)); // !!! TODO: check: ce je sigpending, pa ze pobrisemo timer pripadajoc. a prevermo ce smemo brskat?
#endif
TSockSys::AddTimer(this);
}
}
void TTTimer::StopTimer(){
if (TimerHnd!=0){
#ifdef GLib_WIN32
ESAssert(KillTimer(TSockSys::GetTimerWndHnd(), TimerId));
#elif defined(GLib_UNIX)
itimerspec its;
its.it_value.tv_sec = its.it_interval.tv_sec = 0;
its.it_value.tv_nsec = its.it_interval.tv_nsec = 0;
EAssertR(timer_settime(TimerHnd, 0, &its, NULL) == 0, TSockSys::GetErrStr(errno));
#endif
TSockSys::DelTimer(TimerId);
TimerHnd=0;
}
}
#ifdef GLib_UNIX
void TSocketTimer::OnTimeOut() {
TSockHnd SockHnd=TSockSys::GetSockHnd(SockId);
int SockEventId=TSockSys::GetSockEventId(SockHnd);
PSockEvent SockEvent=TSockSys::GetSockEvent(SockEventId);
TSockSys::SetSockEventActive(SockEventId, true);
try {
if (!SockEvent.Empty()) SockEvent->OnTimeOut(int(SockId));
} catch (...){
SaveToErrLog("Exception from OnTimeOut(SockHnd, SockEvent);");
}
TSockSys::SetSockEventActive(SockEventId, false);
TSockSys::DelIfSockTimer(SockId);
}
#endif
| 33.784695
| 188
| 0.690034
|
qiuhere
|
f4ffcc19fc0c4406900eb88970acc8eef163ae68
| 511
|
cpp
|
C++
|
drape/oglcontextfactory.cpp
|
bowlofstew/omim
|
8045157c95244aa8f862d47324df42a19b87e335
|
[
"Apache-2.0"
] | 1
|
2019-01-11T05:02:05.000Z
|
2019-01-11T05:02:05.000Z
|
drape/oglcontextfactory.cpp
|
bowlofstew/omim
|
8045157c95244aa8f862d47324df42a19b87e335
|
[
"Apache-2.0"
] | null | null | null |
drape/oglcontextfactory.cpp
|
bowlofstew/omim
|
8045157c95244aa8f862d47324df42a19b87e335
|
[
"Apache-2.0"
] | 1
|
2019-08-09T21:21:09.000Z
|
2019-08-09T21:21:09.000Z
|
#include "drape/oglcontextfactory.hpp"
namespace dp
{
ThreadSafeFactory::ThreadSafeFactory(OGLContextFactory * factory)
: m_factory(factory)
{
}
ThreadSafeFactory::~ThreadSafeFactory()
{
delete m_factory;
}
OGLContext *ThreadSafeFactory::getDrawContext()
{
threads::MutexGuard lock(m_mutex);
return m_factory->getDrawContext();
}
OGLContext *ThreadSafeFactory::getResourcesUploadContext()
{
threads::MutexGuard lock(m_mutex);
return m_factory->getResourcesUploadContext();
}
} // namespace dp
| 17.62069
| 65
| 0.772994
|
bowlofstew
|
f4ffdbc72af1209c3c20227409afe3684aac4f62
| 576
|
cpp
|
C++
|
libvermilion/core/src/stb_image.cpp
|
Jojojoppe/vermilion
|
2bfe545c5f2c02e11d96940c191bac6f6c491843
|
[
"Zlib",
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null |
libvermilion/core/src/stb_image.cpp
|
Jojojoppe/vermilion
|
2bfe545c5f2c02e11d96940c191bac6f6c491843
|
[
"Zlib",
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null |
libvermilion/core/src/stb_image.cpp
|
Jojojoppe/vermilion
|
2bfe545c5f2c02e11d96940c191bac6f6c491843
|
[
"Zlib",
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null |
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include "Texture.hpp"
#include <string>
unsigned char * Vermilion::Core::loadTextureData(const std::string& path, size_t * width, size_t * height, size_t * channels){
*width = 0;
*height = 0;
*channels = 4;
Vermilion::Core::flipLoading();
return stbi_load(path.c_str(), (int*)width, (int*)height, nullptr, STBI_rgb_alpha);
}
void Vermilion::Core::freeTextureData(unsigned char * data){
stbi_image_free(data);
}
void Vermilion::Core::flipLoading(){
stbi_set_flip_vertically_on_load(true);
}
| 28.8
| 126
| 0.713542
|
Jojojoppe
|
76028276bf7c9e6e899d16d6e47452956936c4f6
| 11,255
|
cpp
|
C++
|
src/Engine/Audio/CPianoKeyboard.cpp
|
slajerek/MTEngineSDL
|
19b5295d875c197ec03bc20ddacd48c228920365
|
[
"MIT"
] | 4
|
2021-12-16T11:22:30.000Z
|
2022-01-05T11:20:32.000Z
|
src/Engine/Audio/CPianoKeyboard.cpp
|
slajerek/MTEngineSDL
|
19b5295d875c197ec03bc20ddacd48c228920365
|
[
"MIT"
] | 1
|
2022-01-07T10:41:38.000Z
|
2022-01-09T12:04:03.000Z
|
src/Engine/Audio/CPianoKeyboard.cpp
|
slajerek/MTEngineSDL
|
19b5295d875c197ec03bc20ddacd48c228920365
|
[
"MIT"
] | null | null | null |
/*
* CPianoKeyboard (CPianoKeyboard.cpp)
* MobiTracker
*
* Created by Marcin Skoczylas on 09-11-26.
* Copyright 2009 Marcin Skoczylas. All rights reserved.
*
*/
#include "CPianoKeyboard.h"
#include "VID_Main.h"
#include "CGuiMain.h"
#include "CLayoutParameter.h"
#define OCT_NAME_FONT_SIZE_X 8.0
#define OCT_NAME_FONT_SIZE_Y 8.0
#define OCT_NAME_GAP_X 2.0
#define OCT_NAME_GAP_Y 1.0
const char *pianoKeyboardKeyNames = "CDEFGAB";
void CPianoKeyboardCallback::PianoKeyboardNotePressed(CPianoKeyboard *pianoKeyboard, u8 note)
{
}
void CPianoKeyboardCallback::PianoKeyboardNoteReleased(CPianoKeyboard *pianoKeyboard, u8 note)
{
}
CPianoKeyboard::CPianoKeyboard(const char *name, float posX, float posY, float posZ, float sizeX, float sizeY, CPianoKeyboardCallback *callback)
:CGuiView(name, posX, posY, posZ, sizeX, sizeY)
{
keyWhiteWidth = 1.0/7.0;
keyBlackOffset = keyWhiteWidth * (3.0f/4.0f);
keyBlackWidth = keyWhiteWidth * (2.0f/4.0f);
keyBlackHeight = (3.0f/5.0f);
this->numOctaves = 8;
this->octaveNames = new const char *[this->numOctaves];
octaveNames[0] = "0";
octaveNames[1] = "I";
octaveNames[2] = "II";
octaveNames[3] = "III";
octaveNames[4] = "IV";
octaveNames[5] = "V";
octaveNames[6] = "VI";
octaveNames[7] = "VII";
// octaveNames[8] = "VIII";
// octaveNames[9] = "IX";
SetKeysFadeOut(true);
SetKeysFadeOutSpeed(0.40f);
currentOctave = 4;
AddDefaultKeyCodes();
this->callback = callback;
this->InitKeys();
AddLayoutParameter(new CLayoutParameterBool("Keys fade out", &doKeysFadeOut));
AddLayoutParameter(new CLayoutParameterFloat("Keys fade out speed", &keysFadeOutSpeedParameter));
}
void CPianoKeyboard::SetKeysFadeOut(bool doKeysFadeOut)
{
this->doKeysFadeOut = doKeysFadeOut;
}
void CPianoKeyboard::SetKeysFadeOutSpeed(float speed)
{
this->keysFadeOutSpeed = speed;
this->keysFadeOutSpeedOneMinus = 1.0f - this->keysFadeOutSpeed;
this->keysFadeOutSpeedParameter = speed * 10.0f;
}
void CPianoKeyboard::LayoutParameterChanged(CLayoutParameter *layoutParameter)
{
this->keysFadeOutSpeed = keysFadeOutSpeedParameter / 10.0f;
this->keysFadeOutSpeedOneMinus = 1.0f - this->keysFadeOutSpeed;
}
CPianoKey::CPianoKey(u8 keyNote, u8 keyOctave, const char *keyName, double x, double y, double sizeX, double sizeY, bool isBlackKey)
{
this->keyNote = keyNote; this->keyOctave = keyOctave, this->x = x; this->y = y; this->sizeX = sizeX; this->sizeY = sizeY; this->isBlackKey = isBlackKey;
strcpy(this->keyName, keyName);
if (!isBlackKey)
{
r = g = b = a = 1.0f;
cr = cg = cb = ca = 1.0f;
}
else
{
r = g = b = 0; a = 1.0f;
cr = cg = cb = 0; ca = 1.0f;
}
// LOGD("CPianoKey: %d %s: %6.3f %6.3f %6.3f %6.3f", keyNote, keyName, x, y, sizeX, sizeY);
}
void CPianoKeyboard::InitKeys()
{
char *keyName = SYS_GetCharBuf();
double fOctaveStep = 1 / (double)numOctaves;
keyWhiteWidth = fOctaveStep * 1.0/7.0;
keyBlackOffset = keyWhiteWidth * (3.0f/4.0f);
keyBlackWidth = keyWhiteWidth * (2.0f/4.0f);
keyBlackHeight = (3.0f/5.0f);
CPianoKey *key = NULL;
int keyNum = 0;
for (int octaveNum = 0; octaveNum < numOctaves; octaveNum++)
{
double octaveOffset = fOctaveStep * (double)octaveNum;
for (int keyNumInOctave = 0; keyNumInOctave < 7; keyNumInOctave++)
{
sprintf(keyName, "%c-%d", pianoKeyboardKeyNames[keyNumInOctave], octaveNum);
key = new CPianoKey(keyNum, octaveNum, keyName,
keyWhiteWidth * (double)keyNumInOctave + octaveOffset,
0.0f,
keyWhiteWidth,
1.0f, false);
keyNum++;
pianoKeys.push_back(key);
pianoWhiteKeys.push_back(key);
if (keyNumInOctave == 0
|| keyNumInOctave == 1
|| keyNumInOctave == 3
|| keyNumInOctave == 4
|| keyNumInOctave == 5)
{
sprintf(keyName, "%c#%d", pianoKeyboardKeyNames[keyNumInOctave], octaveNum);
key = new CPianoKey(keyNum, octaveNum, keyName,
keyBlackOffset + keyWhiteWidth * (double)keyNumInOctave + octaveOffset,
0.0f,
keyBlackWidth,
keyBlackHeight, true);
keyNum++;
pianoKeys.push_back(key);
pianoBlackKeys.push_back(key);
}
}
}
SYS_ReleaseCharBuf(keyName);
LOGD("InitKeys done");
}
void CPianoKeyboard::Render()
{
// LOGD("CPianoKeyboard::Render");
for (std::vector<CPianoKey *>::iterator it = pianoWhiteKeys.begin(); it != pianoWhiteKeys.end(); it++)
{
CPianoKey *key = *it;
BlitFilledRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1,
key->sizeX * this->sizeX, key->sizeY * this->sizeY,
key->cr, key->cg, key->cb, key->ca);
// border
BlitRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1,
key->sizeX * this->sizeX, key->sizeY * this->sizeY,
0, 0, 0, 1);
}
for (std::vector<CPianoKey *>::iterator it = pianoBlackKeys.begin(); it != pianoBlackKeys.end(); it++)
{
CPianoKey *key = *it;
BlitFilledRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1,
key->sizeX * this->sizeX, key->sizeY * this->sizeY,
key->cr, key->cg, key->cb, key->ca);
BlitRectangle(this->posX + key->x * this->sizeX, this->posY + key->y * this->sizeY, -1,
key->sizeX * this->sizeX, key->sizeY * this->sizeY,
0, 0, 0, 1);
}
}
void CPianoKeyboard::DoLogic()
{
// LOGD("CPianoKeyboard::DoLogic");
if (doKeysFadeOut)
{
for (std::vector<CPianoKey *>::iterator it = pianoKeys.begin(); it != pianoKeys.end(); it++)
{
CPianoKey *key = *it;
key->cr = key->cr * keysFadeOutSpeedOneMinus + key->r * keysFadeOutSpeed;
key->cg = key->cg * keysFadeOutSpeedOneMinus + key->g * keysFadeOutSpeed;
key->cb = key->cb * keysFadeOutSpeedOneMinus + key->b * keysFadeOutSpeed;
key->ca = key->ca * keysFadeOutSpeedOneMinus + key->a * keysFadeOutSpeed;
}
}
}
bool CPianoKeyboard::DoTap(float x, float y)
{
LOGG("CPianoKeyboard::DoTap: x=%f y=%f posX=%f posY=%f sizeX=%f sizeY=%f", x, y, posX, posY, sizeX, sizeY);
// this->pressedNote = GetPressedNote(x, y);
//
// if (pressedNote != NOTE_NONE)
// {
// if (callback != NULL)
// callback->PianoKeyboardNotePressed(pressedNote + editNoteOctave*12); //this->selectedInstrument,
// }
// LOGG("pressed note=%d", pressedNote);
// if (pressedNote != NOTE_NONE)
// return true;
return false;
}
u8 CPianoKeyboard::GetPressedNote(float x, float y)
{
return -1;
}
bool CPianoKeyboard::DoDoubleTap(float x, float y)
{
return this->DoTap(x, y);
}
bool CPianoKeyboard::DoFinishTap(float x, float y)
{
if (IsInsideNonVisible(x, y))
return true;
return false;
}
bool CPianoKeyboard::DoFinishDoubleTap(float x, float y)
{
return this->DoFinishTap(x, y);
}
bool CPianoKeyboard::DoMove(float x, float y, float distX, float distY, float diffX, float diffY)
{
LOGG("CPianoKeyboard::DoMove");
// if (x < SCREEN_WIDTH-menuButtonSizeX)
// {
// u8 bPressedNote = this->GetPressedNote(x, y);
// LOGG("bPressedNote=%d", bPressedNote);
//
// if (bPressedNote != this->pressedNote)
// {
// this->pressedNote = bPressedNote;
//
// if (bPressedNote != NOTE_NONE)
// {
// if (callback != NULL)
// callback->PianoKeyboardNotePressed(bPressedNote + editNoteOctave*12); //this->selectedInstrument,
// }
// LOGG("pressed note=%d", pressedNote);
// }
//
// if (pressedNote != NOTE_NONE)
// {
// return true;
// }
// }
return false; //this->DoTap(x, y);
}
bool CPianoKeyboard::FinishMove(float x, float y, float distX, float distY, float accelerationX, float accelerationY)
{
// if (x < SCREEN_WIDTH-menuButtonSizeX)
// return this->DoFinishTap(x, y);
return false;
}
bool CPianoKeyboard::KeyDown(u32 keyCode, bool isShift, bool isAlt, bool isControl, bool isSuper)
{
LOGD("CPianoKeyboard::KeyDown: keyCode=%x", keyCode);
// TODO: make via callback
if (keyCode == '[')
{
if (currentOctave > 0)
currentOctave--;
return true;
}
else if (keyCode == ']')
{
if (currentOctave < numOctaves-2)
currentOctave++;
return true;
}
else if (this->callback != NULL)
{
// scan for note key code
for (std::list<CPianoNoteKeyCode *>::iterator it = notesKeyCodes.begin(); it != notesKeyCodes.end(); it++)
{
CPianoNoteKeyCode *noteKeyCode = *it;
if (keyCode == noteKeyCode->keyCode)
{
this->callback->PianoKeyboardNotePressed(this, noteKeyCode->keyNote + currentOctave*12);
return true;
}
}
}
return false;
}
bool CPianoKeyboard::KeyUp(u32 keyCode, bool isShift, bool isAlt, bool isControl, bool isSuper)
{
LOGD("CPianoKeyboard::KeyUp: keyCode=%x", keyCode);
if (this->callback != NULL)
{
// scan for note key code
for (std::list<CPianoNoteKeyCode *>::iterator it = notesKeyCodes.begin(); it != notesKeyCodes.end(); it++)
{
CPianoNoteKeyCode *noteKeyCode = *it;
if (keyCode == noteKeyCode->keyCode)
{
this->callback->PianoKeyboardNoteReleased(this, noteKeyCode->keyNote + currentOctave*12);
return true;
}
}
}
return false;
}
void CPianoKeyboard::AddDefaultKeyCodes()
{
// 0 = C-0
notesKeyCodes.push_back(new CPianoNoteKeyCode('z', 0)); // C-0
notesKeyCodes.push_back(new CPianoNoteKeyCode('s', 1));
notesKeyCodes.push_back(new CPianoNoteKeyCode('x', 2));
notesKeyCodes.push_back(new CPianoNoteKeyCode('d', 3));
notesKeyCodes.push_back(new CPianoNoteKeyCode('c', 4));
notesKeyCodes.push_back(new CPianoNoteKeyCode('v', 5));
notesKeyCodes.push_back(new CPianoNoteKeyCode('g', 6));
notesKeyCodes.push_back(new CPianoNoteKeyCode('b', 7));
notesKeyCodes.push_back(new CPianoNoteKeyCode('h', 8));
notesKeyCodes.push_back(new CPianoNoteKeyCode('n', 9));
notesKeyCodes.push_back(new CPianoNoteKeyCode('j', 10));
notesKeyCodes.push_back(new CPianoNoteKeyCode('m', 11));
notesKeyCodes.push_back(new CPianoNoteKeyCode(',', 12)); // C-1
notesKeyCodes.push_back(new CPianoNoteKeyCode('l', 13));
notesKeyCodes.push_back(new CPianoNoteKeyCode('.', 14));
notesKeyCodes.push_back(new CPianoNoteKeyCode(';', 15));
notesKeyCodes.push_back(new CPianoNoteKeyCode('/', 16));
notesKeyCodes.push_back(new CPianoNoteKeyCode('q', 12)); // C-1
notesKeyCodes.push_back(new CPianoNoteKeyCode('2', 13));
notesKeyCodes.push_back(new CPianoNoteKeyCode('w', 14));
notesKeyCodes.push_back(new CPianoNoteKeyCode('3', 15));
notesKeyCodes.push_back(new CPianoNoteKeyCode('e', 16));
notesKeyCodes.push_back(new CPianoNoteKeyCode('r', 17));
notesKeyCodes.push_back(new CPianoNoteKeyCode('5', 18));
notesKeyCodes.push_back(new CPianoNoteKeyCode('t', 19));
notesKeyCodes.push_back(new CPianoNoteKeyCode('6', 20));
notesKeyCodes.push_back(new CPianoNoteKeyCode('y', 21));
notesKeyCodes.push_back(new CPianoNoteKeyCode('7', 22));
notesKeyCodes.push_back(new CPianoNoteKeyCode('u', 23));
notesKeyCodes.push_back(new CPianoNoteKeyCode('i', 24));
notesKeyCodes.push_back(new CPianoNoteKeyCode('9', 25));
notesKeyCodes.push_back(new CPianoNoteKeyCode('o', 26));
notesKeyCodes.push_back(new CPianoNoteKeyCode('0', 27));
notesKeyCodes.push_back(new CPianoNoteKeyCode('p', 28));
}
CPianoKeyboard::~CPianoKeyboard()
{
while(!pianoKeys.empty())
{
CPianoKey *key = pianoKeys.back();
pianoKeys.pop_back();
delete key;
}
while(!notesKeyCodes.empty())
{
CPianoNoteKeyCode *keyCode = notesKeyCodes.back();
notesKeyCodes.pop_back();
delete keyCode;
}
}
| 28.278894
| 153
| 0.687517
|
slajerek
|
760412626f88fb941d8e6b4255045abda9a3697f
| 1,340
|
hpp
|
C++
|
src/entity/sprite/Sprite.hpp
|
JulienTD/pacman
|
71e92b367b4c57bba065c18faa67570842bdd67f
|
[
"MIT"
] | null | null | null |
src/entity/sprite/Sprite.hpp
|
JulienTD/pacman
|
71e92b367b4c57bba065c18faa67570842bdd67f
|
[
"MIT"
] | null | null | null |
src/entity/sprite/Sprite.hpp
|
JulienTD/pacman
|
71e92b367b4c57bba065c18faa67570842bdd67f
|
[
"MIT"
] | null | null | null |
#ifndef SPRITE_HPP_
#define SPRITE_HPP_
#include <string>
#include <SDL2/SDL.h>
#include <SDL2/SDL_pixels.h>
#include <SDL2/SDL_image.h>
#include "window/Window.hpp"
#include "entity/Entity.hpp"
class Sprite : public Entity {
public:
Sprite(std::string id, std::string spritePath, Window *window, int x, int y, int width, int height);
~Sprite();
void setMaxStateNbr(int stateNbr);
void setXStateGap(int xGap);
void setYStateGap(int yGap);
void setSpriteX(int spriteX);
void setSpriteY(int spriteY);
void setSpriteHeight(int spriteHeight);
void setSpriteWidth(int spriteWidth);
void setXAnimation(bool xAnimation);
void setYAnimation(bool yAnimation);
void setTickRate(int tickRate);
void setTickStep(int tickStep);
void render(Window *window);
protected:
private:
SDL_Surface *_image;
SDL_Texture *_texture;
int _width;
int _height;
int _stateNbr;
int _maxStateNbr;
int _xStateGap;
int _yStateGap;
int _spriteX;
int _spriteY;
int _spriteWidth;
int _spriteHeight;
bool _xAnimation;
bool _yAnimation;
int _currentTick;
int _tickRate;
int _tickStep;
};
#endif /* !SPRITE_HPP_ */
| 26.8
| 108
| 0.629851
|
JulienTD
|
76053454382ed3308b268d1d7609151207f9f737
| 7,804
|
cpp
|
C++
|
arangod/IResearch/IResearchRocksDBRecoveryHelper.cpp
|
LLcat1217/arangodb
|
67c51272915699e0a489e1f8d9da786f4226221a
|
[
"Apache-2.0"
] | null | null | null |
arangod/IResearch/IResearchRocksDBRecoveryHelper.cpp
|
LLcat1217/arangodb
|
67c51272915699e0a489e1f8d9da786f4226221a
|
[
"Apache-2.0"
] | null | null | null |
arangod/IResearch/IResearchRocksDBRecoveryHelper.cpp
|
LLcat1217/arangodb
|
67c51272915699e0a489e1f8d9da786f4226221a
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Daniel Larkin-York
////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <rocksdb/db.h>
#include <velocypack/Builder.h>
#include <velocypack/Slice.h>
#include "IResearch/IResearchRocksDBRecoveryHelper.h"
#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/Exceptions.h"
#include "Basics/Result.h"
#include "Basics/StaticStrings.h"
#include "Basics/debugging.h"
#include "Basics/error.h"
#include "Basics/voc-errors.h"
#include "IResearch/IResearchCommon.h"
#include "IResearch/IResearchLink.h"
#include "IResearch/IResearchLinkHelper.h"
#include "IResearch/IResearchRocksDBLink.h"
#include "Indexes/Index.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include "RestServer/DatabaseFeature.h"
#include "RocksDBEngine/RocksDBColumnFamilyManager.h"
#include "RocksDBEngine/RocksDBEngine.h"
#include "RocksDBEngine/RocksDBKey.h"
#include "RocksDBEngine/RocksDBLogValue.h"
#include "RocksDBEngine/RocksDBTypes.h"
#include "RocksDBEngine/RocksDBValue.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "Transaction/StandaloneContext.h"
#include "Utils/SingleCollectionTransaction.h"
#include "VocBase/AccessMode.h"
#include "VocBase/LogicalCollection.h"
#include "VocBase/vocbase.h"
#include "Basics/DownCast.h"
namespace arangodb::transaction {
class Context;
}
namespace {
std::shared_ptr<arangodb::LogicalCollection> lookupCollection(
arangodb::DatabaseFeature& db, arangodb::RocksDBEngine& engine,
uint64_t objectId) {
auto pair = engine.mapObjectToCollection(objectId);
auto vocbase = db.useDatabase(pair.first);
return vocbase ? vocbase->lookupCollection(pair.second) : nullptr;
}
std::vector<std::shared_ptr<arangodb::Index>> lookupLinks(
arangodb::LogicalCollection& coll) {
auto indexes = coll.getIndexes();
// filter out non iresearch links
const auto it = std::remove_if(
indexes.begin(), indexes.end(),
[](std::shared_ptr<arangodb::Index> const& idx) {
return idx->type() !=
arangodb::Index::IndexType::TRI_IDX_TYPE_IRESEARCH_LINK;
});
indexes.erase(it, indexes.end());
return indexes;
}
} // namespace
namespace arangodb {
namespace iresearch {
IResearchRocksDBRecoveryHelper::IResearchRocksDBRecoveryHelper(
ArangodServer& server)
: _server(server) {}
void IResearchRocksDBRecoveryHelper::prepare() {
_dbFeature = &_server.getFeature<DatabaseFeature>();
_engine =
&_server.getFeature<EngineSelectorFeature>().engine<RocksDBEngine>();
_documentCF = RocksDBColumnFamilyManager::get(
RocksDBColumnFamilyManager::Family::Documents)
->GetID();
}
void IResearchRocksDBRecoveryHelper::PutCF(uint32_t column_family_id,
const rocksdb::Slice& key,
const rocksdb::Slice& value,
rocksdb::SequenceNumber /*tick*/) {
if (column_family_id != _documentCF) {
return;
}
auto coll =
lookupCollection(*_dbFeature, *_engine, RocksDBKey::objectId(key));
if (coll == nullptr) {
return;
}
auto const links = lookupLinks(*coll);
if (links.empty()) {
return;
}
auto docId = RocksDBKey::documentId(key);
auto doc = RocksDBValue::data(value);
transaction::StandaloneContext ctx(coll->vocbase());
SingleCollectionTransaction trx(std::shared_ptr<transaction::Context>(
std::shared_ptr<transaction::Context>(),
&ctx), // aliasing ctor
*coll, arangodb::AccessMode::Type::WRITE);
Result res = trx.begin();
if (res.fail()) {
THROW_ARANGO_EXCEPTION(res);
}
for (std::shared_ptr<arangodb::Index> const& link : links) {
IndexId indexId(coll->vocbase().id(), coll->id(), link->id());
// optimization: avoid insertion of recovered documents twice,
// first insertion done during index creation
if (!link || _recoveredIndexes.find(indexId) != _recoveredIndexes.end()) {
continue; // index was already populated when it was created
}
basics::downCast<IResearchRocksDBLink>(*link).insert(trx, nullptr, docId,
doc, {}, false);
}
res = trx.commit();
if (res.fail()) {
THROW_ARANGO_EXCEPTION(res);
}
}
// common implementation for DeleteCF / SingleDeleteCF
void IResearchRocksDBRecoveryHelper::handleDeleteCF(
uint32_t column_family_id, const rocksdb::Slice& key,
rocksdb::SequenceNumber /*tick*/) {
if (column_family_id != _documentCF) {
return;
}
auto coll =
lookupCollection(*_dbFeature, *_engine, RocksDBKey::objectId(key));
if (coll == nullptr) {
return;
}
auto const links = lookupLinks(*coll);
if (links.empty()) {
return;
}
auto docId = RocksDBKey::documentId(key);
transaction::StandaloneContext ctx(coll->vocbase());
SingleCollectionTransaction trx(std::shared_ptr<transaction::Context>(
std::shared_ptr<transaction::Context>(),
&ctx), // aliasing ctor
*coll, arangodb::AccessMode::Type::WRITE);
Result res = trx.begin();
if (res.fail()) {
THROW_ARANGO_EXCEPTION(res);
}
for (std::shared_ptr<arangodb::Index> const& link : links) {
IResearchLink& impl = basics::downCast<IResearchRocksDBLink>(*link);
impl.remove(trx, docId);
}
res = trx.commit();
if (res.fail()) {
THROW_ARANGO_EXCEPTION(res);
}
}
void IResearchRocksDBRecoveryHelper::LogData(const rocksdb::Slice& blob,
rocksdb::SequenceNumber tick) {
RocksDBLogType const type = RocksDBLogValue::type(blob);
switch (type) {
case RocksDBLogType::IndexCreate: {
// Intentional NOOP. Index is committed upon creation.
// So if this marker was written - index was persisted already.
} break;
case RocksDBLogType::CollectionTruncate: {
TRI_ASSERT(_dbFeature);
TRI_ASSERT(_engine);
uint64_t objectId = RocksDBLogValue::objectId(blob);
auto coll = lookupCollection(*_dbFeature, *_engine, objectId);
if (coll != nullptr) {
auto const links = lookupLinks(*coll);
for (auto const& link : links) {
link->afterTruncate(tick, nullptr);
}
}
break;
}
default:
break; // shut up the compiler
}
}
} // namespace iresearch
} // namespace arangodb
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
| 30.724409
| 80
| 0.631599
|
LLcat1217
|
7606ed3bc233b9ed7f32bc613a8838b4e6ef0824
| 9,151
|
cc
|
C++
|
pigasus/software/tools/u2boat/u2boat.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
pigasus/software/tools/u2boat/u2boat.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
pigasus/software/tools/u2boat/u2boat.cc
|
zhipengzhaocmu/fpga2022_artifact
|
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
//--------------------------------------------------------------------------
// Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved.
// Copyright (C) 2002-2013 Sourcefire, Inc.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
// u2boat.cc author Ryan Jordan <ryan.jordan@sourcefire.com>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <pcap.h>
#include <unistd.h>
#include <cctype>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include "../u2spewfoo/u2_common.h"
#define FAILURE (-1)
#define SUCCESS 0
#define PCAP_MAGIC_NUMBER 0xa1b2c3d4
#define PCAP_TIMEZONE 0
#define PCAP_SIGFIGS 0
#define PCAP_SNAPLEN 65535
#define ETHERNET 1
#define PCAP_LINKTYPE ETHERNET
#define MAX_U2RECORD_DATA_LENGTH 65536
static int GetRecord(FILE* input, u2record* rec);
static int PcapInitOutput(FILE* output);
static int PcapConversion(u2record* rec, FILE* output);
static int ConvertLog(FILE* input, FILE* output, const char* format)
{
u2record tmp_record;
/* Determine conversion function */
int (* ConvertRecord)(u2record*, FILE*) = nullptr;
/* This will become an if/else series once more formats are supported.
* Callbacks are used so that this comparison only needs to happen once. */
if (strncasecmp(format, "pcap", 4) == 0)
{
ConvertRecord = PcapConversion;
}
if (ConvertRecord == nullptr)
{
fprintf(stderr, "Error setting conversion routine, aborting...\n");
return FAILURE;
}
/* Initialize the record's data pointer */
tmp_record.data = (uint8_t*)malloc(MAX_U2RECORD_DATA_LENGTH * sizeof(uint8_t));
if (tmp_record.data == nullptr)
{
fprintf(stderr, "Error allocating memory, aborting...\n");
return FAILURE;
}
/* Run through input file and convert records */
while ( !(feof(input) || ferror(input) || ferror(output)) )
{
if (GetRecord(input, &tmp_record) == FAILURE)
{
break;
}
if (ConvertRecord(&tmp_record, output) == FAILURE)
{
break;
}
}
if (tmp_record.data != nullptr)
{
free(tmp_record.data);
tmp_record.data = nullptr;
}
if (ferror(input))
{
fprintf(stderr, "Error reading input file, aborting...\n");
return FAILURE;
}
if (ferror(output))
{
fprintf(stderr, "Error reading output file, aborting...\n");
return FAILURE;
}
return SUCCESS;
}
/* Create and write the pcap file's global header */
static int PcapInitOutput(FILE* output)
{
size_t ret;
struct pcap_file_header hdr;
hdr.magic = PCAP_MAGIC_NUMBER;
hdr.version_major = PCAP_VERSION_MAJOR;
hdr.version_minor = PCAP_VERSION_MINOR;
hdr.thiszone = PCAP_TIMEZONE;
hdr.sigfigs = PCAP_SIGFIGS;
hdr.snaplen = PCAP_SNAPLEN;
hdr.linktype = PCAP_LINKTYPE;
ret = fwrite( (void*)&hdr, sizeof(struct pcap_file_header), 1, output);
if (ret < 1)
{
fprintf(stderr, "Error: Unable to write pcap file header\n");
return FAILURE;
}
return SUCCESS;
}
/* Convert a unified2 packet record to pcap format, then dump */
static int PcapConversion(u2record* rec, FILE* output)
{
Serial_Unified2Packet packet;
struct pcap_pkthdr pcap_hdr;
uint32_t* field;
uint8_t* pcap_data;
static int packet_found = 0;
/* Ignore IDS Events. We are only interested in Packets. */
if (rec->type != UNIFIED2_PACKET)
{
return SUCCESS;
}
/* Initialize the pcap file if this is the first packet */
if (!packet_found)
{
if (PcapInitOutput(output) == FAILURE)
{
return FAILURE;
}
packet_found = 1;
}
/* Fill out the Serial_Unified2Packet */
memcpy(&packet, rec->data, sizeof(Serial_Unified2Packet));
/* Unified 2 records are always stored in network order.
* Convert all fields except packet data to host order */
field = (uint32_t*)&packet;
while (field < (uint32_t*)packet.packet_data)
{
*field = ntohl(*field);
field++;
}
/* Create a pcap packet header */
pcap_hdr.ts.tv_sec = packet.packet_second;
pcap_hdr.ts.tv_usec = packet.packet_microsecond;
pcap_hdr.caplen = packet.packet_length;
pcap_hdr.len = packet.packet_length;
/* Write to the pcap file */
pcap_data = rec->data + sizeof(Serial_Unified2Packet) - 4;
pcap_dump( (uint8_t*)output, &pcap_hdr, (uint8_t*)pcap_data);
return SUCCESS;
}
/* Retrieve a single unified2 record from input file */
static int GetRecord(FILE* input, u2record* rec)
{
uint32_t items_read;
static uint32_t buffer_size = MAX_U2RECORD_DATA_LENGTH;
uint8_t* tmp;
if (!input || !rec)
return FAILURE;
items_read = fread(rec, sizeof(uint32_t), 2, input);
if (items_read != 2)
{
if ( !feof(input) ) /* Not really an error if at EOF */
{
fprintf(stderr, "Error: incomplete record.\n");
}
return FAILURE;
}
/* Type and Length are stored in network order */
rec->type = ntohl(rec->type);
rec->length = ntohl(rec->length);
/* Read in the data portion of the record */
if (rec->length > buffer_size)
{
tmp = (uint8_t*)malloc(rec->length * sizeof(uint8_t));
if (tmp == nullptr)
{
fprintf(stderr, "Error: memory allocation failed.\n");
return FAILURE;
}
else
{
if (rec->data != nullptr)
{
free(rec->data);
}
rec->data = tmp;
buffer_size = rec->length;
}
}
items_read = fread(rec->data, sizeof(uint8_t), rec->length, input);
if (items_read != rec->length)
{
fprintf(stderr, "Error: incomplete record. %u of %u bytes read.\n",
items_read, rec->length);
return FAILURE;
}
return SUCCESS;
}
int main(int argc, char* argv[])
{
char* input_filename = nullptr;
char* output_filename = nullptr;
const char* output_type = nullptr;
FILE* input_file = nullptr;
FILE* output_file = nullptr;
int c, errnum;
opterr = 0;
/* Use Getopt to parse options */
while ((c = getopt (argc, argv, "t:")) != -1)
{
switch (c)
{
case 't':
output_type = optarg;
break;
case '?':
if (optopt == 't')
fprintf(stderr,
"Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf(stderr, "Unknown option -%c.\n", optopt);
return FAILURE;
default:
abort();
}
}
/* At this point, there should be two filenames remaining. */
if (optind != (argc - 2))
{
fprintf(stderr, "Usage: u2boat [-t type] <infile> <outfile>\n");
return FAILURE;
}
input_filename = argv[optind];
output_filename = argv[optind+1];
/* Check inputs */
if (input_filename == nullptr)
{
fprintf(stderr, "Error: Input filename must be specified.\n");
return FAILURE;
}
if (output_type == nullptr)
{
fprintf(stdout, "Defaulting to pcap output.\n");
output_type = "pcap";
}
if (strcasecmp(output_type, "pcap"))
{
fprintf(stderr, "Invalid output type. Valid types are: pcap\n");
return FAILURE;
}
if (output_filename == nullptr)
{
fprintf(stderr, "Error: Output filename must be specified.\n");
return FAILURE;
}
/* Open the files */
if ((input_file = fopen(input_filename, "r")) == nullptr)
{
fprintf(stderr, "Unable to open file: %s\n", input_filename);
return FAILURE;
}
if ((output_file = fopen(output_filename, "w")) == nullptr)
{
fclose(input_file);
fprintf(stderr, "Unable to open/create file: %s\n", output_filename);
return FAILURE;
}
ConvertLog(input_file, output_file, output_type);
if (fclose(input_file) != 0)
{
errnum = errno;
fprintf(stderr, "Error closing input: %s\n", strerror(errnum));
}
if (fclose(output_file) != 0)
{
errnum = errno;
fprintf(stderr, "Error closing output: %s\n", strerror(errnum));
}
return 0;
}
| 27.89939
| 83
| 0.602666
|
zhipengzhaocmu
|
7608a5f1d9ac50567702b78a115c3600c1abc70f
| 4,916
|
cpp
|
C++
|
test-suite/generated-src/jni/NativeInterfaceEncapsulator.cpp
|
iRobotCorporation/djinni
|
50ab071b855beab4e65af1772823dc2080b450b8
|
[
"Apache-2.0"
] | 1
|
2016-03-04T20:23:31.000Z
|
2016-03-04T20:23:31.000Z
|
test-suite/generated-src/jni/NativeInterfaceEncapsulator.cpp
|
iRobotCorporation/djinni
|
50ab071b855beab4e65af1772823dc2080b450b8
|
[
"Apache-2.0"
] | null | null | null |
test-suite/generated-src/jni/NativeInterfaceEncapsulator.cpp
|
iRobotCorporation/djinni
|
50ab071b855beab4e65af1772823dc2080b450b8
|
[
"Apache-2.0"
] | null | null | null |
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from interface_inheritance.djinni
#include "NativeInterfaceEncapsulator.hpp" // my header
#include "NativeBaseCppInterfaceInheritance.hpp"
#include "NativeBaseObjcJavaInterfaceInheritance.hpp"
#include "NativeSubObjcJavaInterfaceInheritance.hpp"
namespace djinni_generated {
NativeInterfaceEncapsulator::NativeInterfaceEncapsulator() : ::djinni::JniInterface<::testsuite::InterfaceEncapsulator, NativeInterfaceEncapsulator>("com/dropbox/djinni/test/InterfaceEncapsulator$CppProxy") {}
NativeInterfaceEncapsulator::~NativeInterfaceEncapsulator() = default;
CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_nativeDestroy(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
delete reinterpret_cast<::djinni::CppProxyHandle<::testsuite::InterfaceEncapsulator>*>(nativeRef);
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1setCppObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_object)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
ref->set_cpp_object(::djinni_generated::NativeBaseCppInterfaceInheritance::toCpp(jniEnv, j_object));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1getCppObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->get_cpp_object();
return ::djinni::release(::djinni_generated::NativeBaseCppInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1subCppAsBaseCpp(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->sub_cpp_as_base_cpp();
return ::djinni::release(::djinni_generated::NativeBaseCppInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1setObjcJavaObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_object)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
ref->set_objc_java_object(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::toCpp(jniEnv, j_object));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1getObjcJavaObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->get_objc_java_object();
return ::djinni::release(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1castBaseArgToSub(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_subAsBase)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->cast_base_arg_to_sub(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::toCpp(jniEnv, j_subAsBase));
return ::djinni::release(::djinni_generated::NativeSubObjcJavaInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_create(JNIEnv* jniEnv, jobject /*this*/)
{
try {
DJINNI_FUNCTION_PROLOGUE0(jniEnv);
auto r = ::testsuite::InterfaceEncapsulator::create();
return ::djinni::release(::djinni_generated::NativeInterfaceEncapsulator::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
} // namespace djinni_generated
| 53.434783
| 209
| 0.778885
|
iRobotCorporation
|
760a33560dd67baa90060d7973adde8257a61375
| 837
|
hpp
|
C++
|
PolyEngine/Editor/Src/Controls/IControlBase.hpp
|
PiotrMoscicki/PolyEngine
|
573c453e9d1ae0a351ad14410595ff844e3b4620
|
[
"MIT"
] | 65
|
2017-04-04T20:33:44.000Z
|
2019-12-02T23:06:58.000Z
|
PolyEngine/Editor/Src/Controls/IControlBase.hpp
|
PiotrMoscicki/PolyEngine
|
573c453e9d1ae0a351ad14410595ff844e3b4620
|
[
"MIT"
] | 46
|
2017-04-21T12:26:38.000Z
|
2019-12-15T05:31:47.000Z
|
PolyEngine/Editor/Src/Controls/IControlBase.hpp
|
PiotrMoscicki/PolyEngine
|
573c453e9d1ae0a351ad14410595ff844e3b4620
|
[
"MIT"
] | 51
|
2017-04-12T10:53:32.000Z
|
2019-11-20T13:05:54.000Z
|
#pragma once
#include <QtWidgets/qwidget.h>
#include <QtCore/qtimer.h>
#include <RTTI/RTTI.hpp>
#include <Utils/Logger.hpp>
using namespace Poly;
// This is base class for all controls for core types such as int, string or vector.
// @see Poly::RTTI::eCorePropertyType
class IControlBase
{
public:
// Assigns given object to control and updates this control.
virtual void SetObject(void* ptr) = 0;
// Name of assigned property.
virtual void SetName(String name) = 0;
// Tool tip for this control.
virtual void SetToolTip(String type) = 0;
// If set to true then control will not permit changing its content.
virtual void SetDisableEdit(bool disable) = 0;
// Resets this control to initial state;
virtual void Reset() = 0;
// Call this to update control state from assigned object.
virtual void UpdateControl() = 0;
};
| 26.15625
| 84
| 0.734767
|
PiotrMoscicki
|
760be1fbba299668e2b3974b11ff6c5d131f3464
| 21,384
|
cpp
|
C++
|
src/CQPropertyViewTree.cpp
|
SammyEnigma/CQPropertyView
|
4dd64a266929b754a68839243daf0aeb80331185
|
[
"MIT"
] | 8
|
2018-05-07T13:06:53.000Z
|
2022-03-08T05:25:06.000Z
|
src/CQPropertyViewTree.cpp
|
SammyEnigma/CQPropertyView
|
4dd64a266929b754a68839243daf0aeb80331185
|
[
"MIT"
] | 2
|
2021-06-18T06:08:37.000Z
|
2022-03-12T11:45:17.000Z
|
src/CQPropertyViewTree.cpp
|
SammyEnigma/CQPropertyView
|
4dd64a266929b754a68839243daf0aeb80331185
|
[
"MIT"
] | 4
|
2019-04-01T13:13:59.000Z
|
2022-01-20T12:14:44.000Z
|
#include <CQPropertyViewTree.h>
#include <CQPropertyViewFilter.h>
#include <CQPropertyViewModel.h>
#include <CQPropertyViewDelegate.h>
#include <CQPropertyViewItem.h>
#include <CQHeaderView.h>
#include <QApplication>
#include <QHeaderView>
#include <QMouseEvent>
#include <QClipboard>
#include <QMenu>
#include <set>
#include <iostream>
CQPropertyViewTree::
CQPropertyViewTree(QWidget *parent) :
QTreeView(parent), model_(new CQPropertyViewModel)
{
init();
modelAllocated_ = true;
}
CQPropertyViewTree::
CQPropertyViewTree(QWidget *parent, CQPropertyViewModel *model) :
QTreeView(parent), model_(model)
{
init();
}
CQPropertyViewTree::
~CQPropertyViewTree()
{
if (modelAllocated_)
delete model_;
delete filter_;
}
void
CQPropertyViewTree::
init()
{
setObjectName("propertyView");
//--
filter_ = new CQPropertyViewFilter(this);
if (model_) {
connect(model_, SIGNAL(valueChanged(QObject *, const QString &)),
this, SIGNAL(valueChanged(QObject *, const QString &)));
connect(model_, SIGNAL(valueChanged(QObject *, const QString &)),
this, SLOT(redraw()));
model_->setTree(this);
filter_->setSourceModel(model_);
setModel(filter_);
}
//--
setHeader(new CQHeaderView(this));
header()->setStretchLastSection(true);
//header()->setSectionResizeMode(QHeaderView::Interactive);
//header()->setSectionResizeMode(QHeaderView::ResizeToContents);
//--
setSelectionMode(ExtendedSelection);
setUniformRowHeights(true);
setAlternatingRowColors(true);
setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
//--
// Set Item Delegate
delegate_ = new CQPropertyViewDelegate(this);
setItemDelegate(delegate_);
connect(delegate_, SIGNAL(closeEditor(QWidget*, QAbstractItemDelegate::EndEditHint)),
this, SLOT(closeEditorSlot(QWidget*, QAbstractItemDelegate::EndEditHint)));
//--
// handle click (for bool check box)
connect(this, SIGNAL(clicked(const QModelIndex &)),
this, SLOT(itemClickedSlot(const QModelIndex &)));
//---
// handle selection
auto *sm = this->selectionModel();
if (sm)
connect(sm, SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(itemSelectionSlot()));
//---
// add menu
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(customContextMenuSlot(const QPoint&)));
}
void
CQPropertyViewTree::
setPropertyModel(CQPropertyViewModel *model)
{
// disconnect current model
if (model_) {
disconnect(model_, SIGNAL(valueChanged(QObject *, const QString &)),
this, SIGNAL(valueChanged(QObject *, const QString &)));
disconnect(model_, SIGNAL(valueChanged(QObject *, const QString &)),
this, SLOT(redraw()));
model_->setTree(nullptr);
}
//---
model_ = model;
//---
// connect new model
if (model_) {
connect(model_, SIGNAL(valueChanged(QObject *, const QString &)),
this, SIGNAL(valueChanged(QObject *, const QString &)));
connect(model_, SIGNAL(valueChanged(QObject *, const QString &)),
this, SLOT(redraw()));
model_->setTree(this);
filter_->setSourceModel(model_);
setModel(filter_);
}
}
void
CQPropertyViewTree::
setMouseHighlight(bool b)
{
mouseHighlight_ = b;
setMouseTracking(mouseHighlight_);
}
void
CQPropertyViewTree::
setFilter(const QString &filter)
{
filter_->setFilter(filter);
}
void
CQPropertyViewTree::
modelResetSlot()
{
//std::cerr << "model reset" << std::endl;
}
void
CQPropertyViewTree::
redraw()
{
viewport()->update();
}
void
CQPropertyViewTree::
clear()
{
model_->clear();
}
void
CQPropertyViewTree::
addProperty(const QString &path, QObject *obj, const QString &name, const QString &alias)
{
model_->addProperty(path, obj, name, alias);
}
bool
CQPropertyViewTree::
setProperty(QObject *object, const QString &path, const QVariant &value)
{
bool rc = model_->setProperty(object, path, value);
redraw();
return rc;
}
bool
CQPropertyViewTree::
getProperty(const QObject *object, const QString &path, QVariant &value) const
{
return model_->getProperty(object, path, value);
}
void
CQPropertyViewTree::
selectObject(const QObject *obj)
{
auto *root = model_->root();
for (int i = 0; i < model_->numItemChildren(root); ++i) {
auto *item = model_->itemChild(root, i);
if (selectObject(item, obj))
return;
}
}
bool
CQPropertyViewTree::
selectObject(CQPropertyViewItem *item, const QObject *obj)
{
auto *obj1 = item->object();
if (obj1 == obj) {
if (item->parent()) {
selectItem(item->parent(), true);
return true;
}
}
for (int i = 0; i < model_->numItemChildren(item); ++i) {
auto *item1 = model_->itemChild(item, i);
if (selectObject(item1, obj))
return true;
}
return false;
}
void
CQPropertyViewTree::
deselectAllObjects()
{
auto *sm = this->selectionModel();
sm->clear();
}
bool
CQPropertyViewTree::
setCurrentProperty(QObject *object, const QString &path)
{
auto *item = model_->propertyItem(object, path);
if (! item)
return false;
auto ind = indexFromItem(item, 0, /*map*/true);
if (! ind.isValid())
return false;
setCurrentIndex(ind);
return true;
}
void
CQPropertyViewTree::
resizeColumns()
{
resizeColumnToContents(0);
resizeColumnToContents(1);
header()->setStretchLastSection(false);
header()->setStretchLastSection(true);
}
void
CQPropertyViewTree::
expandAll()
{
auto *root = model_->root();
expandAll(root);
}
void
CQPropertyViewTree::
expandAll(CQPropertyViewItem *item)
{
expandItemTree(item);
for (int i = 0; i < model_->numItemChildren(item); ++i) {
auto *item1 = model_->itemChild(item, i);
expandAll(item1);
}
}
void
CQPropertyViewTree::
collapseAll()
{
auto *root = model_->root();
collapseAll(root);
}
void
CQPropertyViewTree::
collapseAll(CQPropertyViewItem *item)
{
collapseItemTree(item);
for (int i = 0; i < model_->numItemChildren(item); ++i) {
auto *item1 = model_->itemChild(item, i);
collapseAll(item1);
}
}
void
CQPropertyViewTree::
expandSelected()
{
auto indices = this->selectedIndexes();
for (int i = 0; i < indices.length(); ++i) {
auto *item = getModelItem(indices[i]);
expandItemTree(item);
}
resizeColumns();
for (int i = 0; i < indices.length(); ++i) {
auto *item = getModelItem(indices[i]);
scrollToItem(item);
}
}
void
CQPropertyViewTree::
getSelectedObjects(Objs &objs)
{
auto indices = this->selectedIndexes();
for (int i = 0; i < indices.length(); ++i) {
auto *item = getModelItem(indices[i]);
QObject *obj;
QString path;
getItemData(item, obj, path);
objs.push_back(obj);
}
}
//---
bool
CQPropertyViewTree::
isShowHidden() const
{
return model_->isShowHidden();
}
void
CQPropertyViewTree::
setShowHidden(bool b)
{
if (model_ && b != model_->isShowHidden()) {
saveState();
model_->setShowHidden(b);
model_->reset();
restoreState();
}
}
//---
void
CQPropertyViewTree::
saveState()
{
assert(model_);
stateData_.expandPaths.clear();
auto ind = indexAt(QPoint(0, 0));
stateData_.topItem.clear();
itemPath(ind, stateData_.topItem);
//std::cerr << "Top : "; printPath(stateData_.topItem);
stateData_.topIndex = QModelIndex();
saveState1(QModelIndex(), stateData_, 0);
}
void
CQPropertyViewTree::
saveState1(const QModelIndex &parent, StateData &stateData, int depth)
{
auto *filterModel = this->filterModel();
int nr = filterModel->rowCount(parent);
for (int r = 0; r < nr; ++r) {
auto ind = filterModel->index(r, 0, parent);
if (! filterModel->hasChildren(ind))
continue;
if (isExpanded(ind)) {
ItemPath path;
itemPath(ind, path);
stateData.expandPaths[depth].push_back(path);
//std::cerr << "Save : "; printPath(path);
}
saveState1(ind, stateData, depth + 1);
}
}
void
CQPropertyViewTree::
restoreState()
{
assert(model_);
restoreState1(QModelIndex(), stateData_, 0);
redraw();
if (stateData_.topIndex.isValid()) {
#if 0
ItemPath topItem;
auto ind1 = indexAt(QPoint(0, 0));
itemPath(ind1, topItem);
std::cerr << "Top : "; printPath(topItem);
auto rect = visualRect(stateData_.topIndex);
int dy = rect.top();
std::cerr << "DY : " << dy << "\n";
#endif
scrollTo(stateData_.topIndex, QAbstractItemView::EnsureVisible);
#if 0
rect = visualRect(stateData_.topIndex);
dy = rect.top();
std::cerr << "DY : " << dy << "\n";
topItem.clear();
ind1 = indexAt(QPoint(0, 0));
itemPath(ind1, topItem);
std::cerr << "Top : "; printPath(topItem);
#endif
scrollTo(stateData_.topIndex, QAbstractItemView::PositionAtTop);
#if 0
rect = visualRect(stateData_.topIndex);
dy = rect.top();
std::cerr << "DY : " << dy << "\n";
topItem.clear();
ind1 = indexAt(QPoint(0, 0));
itemPath(ind1, topItem);
std::cerr << "Top : "; printPath(topItem);
#endif
}
}
void
CQPropertyViewTree::
restoreState1(const QModelIndex &parent, StateData &stateData, int depth)
{
auto pd = stateData.expandPaths.find(depth);
//---
auto itemMatch = [&](const ItemPath &path1, const ItemPath &path2) {
int np = path1.length();
if (path2.length() != np)
return false;
for (int i = 0; i < np; ++i) {
if (path1[i] != path2[i])
return false;
}
return true;
};
auto hasPath = [&](const ItemPath &path) {
auto &itemPaths = (*pd).second;
for (const auto &path1 : itemPaths) {
if (itemMatch(path, path1))
return true;
}
return false;
};
//---
auto *filterModel = this->filterModel();
int nr = filterModel->rowCount(parent);
for (int r = 0; r < nr; ++r) {
auto ind = filterModel->index(r, 0, parent);
ItemPath path;
itemPath(ind, path);
if (itemMatch(stateData_.topItem, path))
stateData.topIndex = ind;
if (! filterModel->hasChildren(ind))
continue;
if (pd != stateData.expandPaths.end()) {
if (hasPath(path)) {
setExpanded(ind, true);
//std::cerr << "Restore : "; printPath(path);
}
}
restoreState1(ind, stateData, depth + 1);
}
}
void
CQPropertyViewTree::
itemPath(const QModelIndex &ind, ItemPath &path) const
{
auto *filterModel = this->filterModel();
if (ind.parent().isValid())
itemPath(ind.parent(), path);
auto str = filterModel->data(ind, Qt::DisplayRole).toString();
path.push_back(str);
}
#if 0
void
CQPropertyViewTree::
printPath(const ItemPath &path) const
{
std::cerr << path.join("|").toStdString() << "\n";
}
#endif
//---
void
CQPropertyViewTree::
autoUpdateSlot(bool b)
{
if (! model_)
return;
if (b)
updateDirtySlot();
model_->setAutoUpdate(b);
}
void
CQPropertyViewTree::
updateDirtySlot()
{
if (! model_)
return;
emit startUpdate();
model_->updateDirty();
emit endUpdate();
}
//---
void
CQPropertyViewTree::
search(const QString &text)
{
auto searchStr = text;
if (searchStr.length() && searchStr[searchStr.length() - 1] != '*')
searchStr += "*";
if (searchStr.length() && searchStr[0] != '*')
searchStr = "*" + searchStr;
QRegExp regexp(searchStr, Qt::CaseSensitive, QRegExp::Wildcard);
auto *root = model_->root();
// get matching items
Items items;
for (int i = 0; i < model_->numItemChildren(root); ++i) {
auto *item = model_->itemChild(root, i);
searchItemTree(item, regexp, items);
}
// select matching items
auto *sm = this->selectionModel();
sm->clear();
for (uint i = 0; i < items.size(); ++i) {
auto *item = items[i];
selectItem(item, true);
}
//---
// ensure selection expanded
for (uint i = 0; i < items.size(); ++i) {
auto *item = items[i];
expandItemTree(item);
}
//---
// make item visible
resizeColumns();
for (uint i = 0; i < items.size(); ++i) {
auto *item = items[i];
scrollToItem(item);
}
}
void
CQPropertyViewTree::
searchItemTree(CQPropertyViewItem *item, const QRegExp ®exp, Items &items)
{
auto itemText = item->aliasName();
if (regexp.exactMatch(itemText))
items.push_back(item);
int n = model_->numItemChildren(item);
for (int i = 0; i < n; ++i) {
auto *item1 = model_->itemChild(item, i);
searchItemTree(item1, regexp, items);
}
}
void
CQPropertyViewTree::
expandItemTree(CQPropertyViewItem *item)
{
while (item) {
expandItem(item);
item = item->parent();
}
}
void
CQPropertyViewTree::
collapseItemTree(CQPropertyViewItem *item)
{
while (item) {
collapseItem(item);
item = item->parent();
}
}
void
CQPropertyViewTree::
itemClickedSlot(const QModelIndex &index)
{
auto *item = getModelItem(index);
if (item && index.column() == 1) {
if (item->click()) {
update(index);
}
}
//---
QObject *obj;
QString path;
getItemData(item, obj, path);
emit itemClicked(obj, path);
}
void
CQPropertyViewTree::
itemSelectionSlot()
{
// filter model indices
auto indices = this->selectedIndexes();
if (indices.empty()) return;
auto ind = indices[0];
assert(ind.model() == filter_);
auto *item = getModelItem(ind);
QObject *obj;
QString path;
getItemData(item, obj, path);
emit itemSelected(obj, path);
}
CQPropertyViewItem *
CQPropertyViewTree::
getModelItem(const QModelIndex &ind, bool map) const
{
if (map) {
bool ok;
auto *item = model_->item(ind, ok);
if (! item)
return nullptr;
assert(! ok);
auto ind1 = filter_->mapToSource(ind);
auto *item1 = model_->item(ind1);
return item1;
}
else {
auto *item = model_->item(ind);
return item;
}
}
void
CQPropertyViewTree::
getItemData(CQPropertyViewItem *item, QObject* &obj, QString &path)
{
path = item->path("/");
//---
// use object from first branch child
auto *item1 = item;
int n = model_->numItemChildren(item1);
while (n > 0) {
item1 = model_->itemChild(item1, 0);
n = model_->numItemChildren(item1);
}
obj = item1->object();
}
void
CQPropertyViewTree::
customContextMenuSlot(const QPoint &pos)
{
// Map point to global from the viewport to account for the header.
menuPos_ = viewport()->mapToGlobal(pos);
menuItem_ = getModelItem(indexAt(pos));
if (isItemMenu()) {
if (menuItem_) {
QObject *obj;
QString path;
getItemData(menuItem_, obj, path);
if (obj) {
showContextMenu(obj, menuPos_);
return;
}
}
}
//---
auto *menu = new QMenu;
//---
addMenuItems(menu);
//---
menu->exec(menuPos_);
delete menu;
}
void
CQPropertyViewTree::
addMenuItems(QMenu *menu)
{
addStandardMenuItems(menu);
}
void
CQPropertyViewTree::
addStandardMenuItems(QMenu *menu)
{
auto addAction = [&](const QString &text, const char *slotName) {
auto *action = new QAction(text, menu);
connect(action, SIGNAL(triggered()), this, slotName);
menu->addAction(action);
return action;
};
auto addCheckAction = [&](const QString &text, bool checked, const char *slotName) {
auto *action = new QAction(text, menu);
action->setCheckable(true);
action->setChecked(checked);
connect(action, SIGNAL(triggered(bool)), this, slotName);
menu->addAction(action);
return action;
};
//---
(void) addAction("Expand All" , SLOT(expandAll()));
(void) addAction("Collapse All", SLOT(collapseAll()));
//---
menu->addSeparator();
(void) addCheckAction("Show Hidden", isShowHidden(), SLOT(setShowHidden(bool)));
//---
auto *copyAction = addAction("Copy", SLOT(copySlot()));
copyAction->setShortcut(QKeySequence::Copy);
//---
if (model()) {
menu->addSeparator();
(void) addCheckAction("Auto Update", model_->isAutoUpdate(), SLOT(autoUpdateSlot(bool)));
if (! model_->isAutoUpdate())
(void) addAction("Update Dirty", SLOT(updateDirtySlot()));
}
//---
menu->addSeparator();
(void) addAction("Print" , SLOT(printSlot()));
(void) addAction("Print Changed", SLOT(printChangedSlot()));
}
void
CQPropertyViewTree::
showContextMenu(QObject *obj, const QPoint &globalPos)
{
emit menuExec(obj, globalPos);
}
void
CQPropertyViewTree::
mouseMoveEvent(QMouseEvent *me)
{
if (! isMouseHighlight())
return;
auto ind = indexAt(me->pos());
if (ind.isValid()) {
auto *item = getModelItem(ind);
if (item) {
if (! isMouseInd(ind)) {
setMouseInd(ind);
redraw();
}
return;
}
}
if (! isMouseInd(QModelIndex())) {
unsetMouseInd();
redraw();
}
}
void
CQPropertyViewTree::
leaveEvent(QEvent *)
{
if (! isMouseHighlight()) return;
unsetMouseInd();
redraw();
}
void
CQPropertyViewTree::
keyPressEvent(QKeyEvent *ke)
{
if (ke->matches(QKeySequence::Copy)) {
auto p = QCursor::pos();
copyAt(p, /*html*/false);
}
else if (ke->key() == Qt::Key_Escape) {
closeCurrentEditor();
}
else
QTreeView::keyPressEvent(ke);
}
void
CQPropertyViewTree::
showEvent(QShowEvent *)
{
if (! shown_) {
if (isResizeOnShow())
resizeColumns();
shown_ = true;
}
}
void
CQPropertyViewTree::
resizeEvent(QResizeEvent *e)
{
QTreeView::resizeEvent(e);
}
void
CQPropertyViewTree::
scrollToItem(CQPropertyViewItem *item)
{
auto ind = indexFromItem(item, 0, /*map*/true);
if (ind.isValid())
scrollTo(ind);
}
void
CQPropertyViewTree::
selectItem(CQPropertyViewItem *item, bool selected)
{
auto *sm = this->selectionModel();
auto ind = indexFromItem(item, 0, /*map*/true);
if (ind.isValid()) {
if (selected) {
sm->select(ind, QItemSelectionModel::Select);
}
else {
//sm->select(ind, QItemSelectionModel::Deselect);
}
}
}
void
CQPropertyViewTree::
expandItem(CQPropertyViewItem *item)
{
auto ind = indexFromItem(item, 0, /*map*/true);
if (ind.isValid())
setExpanded(ind, true);
}
void
CQPropertyViewTree::
collapseItem(CQPropertyViewItem *item)
{
auto ind = indexFromItem(item, 0, /*map*/true);
if (ind.isValid())
setExpanded(ind, false);
}
void
CQPropertyViewTree::
editItem(CQPropertyViewItem *item)
{
auto ind = indexFromItem(item, 1, /*map*/true);
if (ind.isValid())
edit(ind);
}
void
CQPropertyViewTree::
copySlot() const
{
copyAt(menuPos_, /*html*/false);
}
void
CQPropertyViewTree::
copyAt(const QPoint &p, bool html) const
{
auto ind = indexAt(viewport()->mapFromGlobal(p));
if (ind.isValid()) {
auto *item = getModelItem(ind);
if (! item) return;
QString value;
if (ind.column() == 0)
value = item->nameTip(html);
else if (ind.column() == 1)
value = item->valueTip(html);
else
return;
auto *clipboard = QApplication::clipboard();
clipboard->setText(value, QClipboard::Clipboard);
clipboard->setText(value, QClipboard::Selection);
}
}
void
CQPropertyViewTree::
printSlot() const
{
auto indices = this->selectionModel()->selectedRows();
for (int i = 0; i < indices.length(); ++i) {
auto *item = getModelItem(indices[i]);
auto path = item->path(".", /*alias*/true);
std::cerr << path.toStdString() << "=" << item->dataStr().toStdString() << "\n";
}
}
void
CQPropertyViewTree::
printChangedSlot() const
{
CQPropertyViewModel::NameValues nameValues;
model_->getChangedNameValues(nameValues, /*tcl*/false);
for (const auto &nv : nameValues)
std::cerr << nv.first.toStdString() << "=" << nv.second.toString().toStdString() << "\n";
}
void
CQPropertyViewTree::
closeEditorSlot()
{
closeCurrentEditor();
}
void
CQPropertyViewTree::
closeCurrentEditor()
{
auto *editor = delegate_->getEditor();
if (! editor) return;
if (! delegate_->isEditing())
return;
delegate_->setModelData(editor, model(), delegate_->getEditorIndex());
// turn off edit triggers so we don't start a new editor
auto triggers = editTriggers();
setEditTriggers(QAbstractItemView::NoEditTriggers);
// close editor
QAbstractItemView::closeEditor(editor, QAbstractItemDelegate::NoHint);
// restore edit triggers
setEditTriggers(triggers);
//setSelectedIndex(delegate_->getEditorIndex().row());
delegate_->setEditing(false);
}
void
CQPropertyViewTree::
closeEditorSlot(QWidget *, QAbstractItemDelegate::EndEditHint)
{
delegate_->setEditing(false);
}
QModelIndex
CQPropertyViewTree::
indexFromItem(CQPropertyViewItem *item, int column, bool map) const
{
auto ind = model_->indexFromItem(item, column);
if (! ind.isValid())
return QModelIndex();
if (map) {
auto *filterModel = this->filterModel();
return filterModel->mapFromSource(ind);
}
return ind;
}
void
CQPropertyViewTree::
setMouseInd(const QModelIndex &i)
{
assert(i.isValid());
hasMouseInd_ = true;
mouseInd_ = i;
}
void
CQPropertyViewTree::
unsetMouseInd()
{
hasMouseInd_ = false;
mouseInd_ = QModelIndex();
}
bool
CQPropertyViewTree::
isMouseInd(const QModelIndex &i)
{
if (! isMouseHighlight())
return false;
if (i.isValid()) {
if (! hasMouseInd_)
return false;
assert(i.model() == mouseInd_.model());
if (mouseInd_.parent() != i.parent())
return false;
return (mouseInd_.row() == i.row());
}
else {
return ! hasMouseInd_;
}
}
| 17.6
| 93
| 0.648803
|
SammyEnigma
|
76169e6048a4751df05e23b45ca86658151d7cd1
| 755
|
cpp
|
C++
|
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
|
cnm06/Competitive-Programming
|
94242ae458570d503b8218f37624b88cc5020d23
|
[
"MIT"
] | 994
|
2017-02-28T06:13:47.000Z
|
2022-03-31T10:49:00.000Z
|
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
|
Quadrified/Competitive-Programming
|
bccb69952cc5260fb3647b3301ddac1023dacac8
|
[
"MIT"
] | 16
|
2018-01-01T02:59:55.000Z
|
2021-11-22T12:49:16.000Z
|
Competitions/Codeforces/Codeforces Round #352 (Div. 2)/Summer Camp.cpp
|
Quadrified/Competitive-Programming
|
bccb69952cc5260fb3647b3301ddac1023dacac8
|
[
"MIT"
] | 325
|
2017-06-15T03:32:43.000Z
|
2022-03-28T22:43:42.000Z
|
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
long long int n, temp;
int main()
{
cin>>n;
if(n<10 && n>0)
{
cout<<n<<endl;
}
else if(n>9 && n<190)
{
n=n-9;
temp=n%2;
n=9+n/2;
if(temp==0)
{
cout<<n%10<<endl;
}
else
{
n++;
cout<<n/10<<endl;
}
}
else
{
n=n-189;
temp=n%3;
n=99+n/3;
if(temp==0)
{
cout<<n%10<<endl;
}
else if(temp==1)
{
n++;
cout<<n/100<<endl;
}
else
{
n++;
n=n/10;
cout<<n%10<<endl;
}
}
return 0;
}
| 14.803922
| 30
| 0.316556
|
cnm06
|
761761409dd0e995e32457cf0293e50204fb6b1a
| 443
|
hpp
|
C++
|
src/Qt5Network/QLocalServer.hpp
|
dafrito/luacxx
|
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
|
[
"MIT"
] | 128
|
2015-01-07T19:47:09.000Z
|
2022-01-22T19:42:14.000Z
|
src/Qt5Network/QLocalServer.hpp
|
dafrito/luacxx
|
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
|
[
"MIT"
] | null | null | null |
src/Qt5Network/QLocalServer.hpp
|
dafrito/luacxx
|
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
|
[
"MIT"
] | 24
|
2015-01-07T19:47:10.000Z
|
2022-01-25T17:42:37.000Z
|
#ifndef luacxx_QLocalServer_INCLUDED
#define luacxx_QLocalServer_INCLUDED
#include "../stack.hpp"
#include "../enum.hpp"
#include <QLocalServer>
#include "../Qt5Core/QObject.hpp"
// http://qt-project.org/doc/qt-5/qlocalserver.html#details
LUA_METATABLE_INHERIT(QLocalServer, QObject)
LUA_METATABLE_ENUM(QLocalServer::SocketOption)
extern "C" int luaopen_Qt5Network_QLocalServer(lua_State* const);
#endif // luacxx_QLocalServer_INCLUDED
| 23.315789
| 65
| 0.801354
|
dafrito
|
7621daf177cc86bd608edb512ae2a03fd7b72d28
| 6,164
|
cpp
|
C++
|
Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp
|
antoniospg/cgal
|
2891c22fc7f64f680ac7e144407afe49f6425cb9
|
[
"CC0-1.0"
] | 2
|
2020-12-12T09:30:07.000Z
|
2021-01-04T05:00:23.000Z
|
Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp
|
antoniospg/cgal
|
2891c22fc7f64f680ac7e144407afe49f6425cb9
|
[
"CC0-1.0"
] | 17
|
2018-01-10T13:32:24.000Z
|
2021-07-30T12:23:20.000Z
|
Mesh_3/archive/applications/identify_identical_points_in_OFF_files.cpp
|
antoniospg/cgal
|
2891c22fc7f64f680ac7e144407afe49f6425cb9
|
[
"CC0-1.0"
] | 1
|
2019-02-21T15:26:25.000Z
|
2019-02-21T15:26:25.000Z
|
// Copyright (c) 2007 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : Laurent Rineau
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <stack>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <boost/format.hpp>
using std::cout;
using std::cin;
using std::endl;
int main()
{
std::string header;
cin >> header;
if(header != "OFF")
{
std::cerr << "header is \"" << header << "\"\nshould be \"OFF\".\n";
return 1;
}
cout << header << endl;
unsigned int n_vertices;
unsigned int n_facets;
std::string dummy;
cin >> n_vertices;
cin >> n_facets;
getline(cin, dummy);
// Vector that maps from old vertex index to new vertex index,
// as some (old) vertices may have identical point coordinates.
std::vector<int> new_index(n_vertices);
typedef boost::tuple<double, double, double> Point;
// Vector that stores the points coordinates (in a Point).
std::vector<Point> points(n_vertices);
// Map that retains the mapping from the point coordinates (in a Point)
// to the nex index.
typedef std::map<Point, int> Renumber;
Renumber renumber;
unsigned int index = 0;
for(unsigned int i = 0; i < n_vertices; ++i)
{
cin >> boost::get<0>(points[index])
>> boost::get<1>(points[index]) >> boost::get<2>(points[index]);
Renumber::const_iterator it = renumber.find(points[index]);
if( it == renumber.end() )
{
renumber[points[index]] = index;
new_index[i] = index;
++index;
}
else
{
new_index[i] = it->second;
}
}
cout << index << " " << n_facets << dummy << endl;
for(unsigned int i = 0; i < index; ++i)
{
cout << boost::get<0>(points[i]) << " "
<< boost::get<1>(points[i]) << " "
<< boost::get<2>(points[i]) << "\n";
}
// Vector that stores each facet.
typedef std::vector<boost::tuple<int, int, int> > Facets;
Facets facets;
// For each (oriented) edge, that map stores a vector of adjacent facets,
// with a boolean that tells if the edge is in the opposite orientation,
// in the facet.
// Edges are stores in the direction from the smallest index to the
// greatest.
typedef std::pair<int, int> Edge;
typedef std::map<Edge, std::vector<std::pair<int, bool> > > Edges_map;
Edges_map edges;
// "nested function" opposite, that returns the edge, in the opposite
// direction.
struct {
Edge operator()(Edge e) const {
return std::make_pair(e.second, e.first);
};
} opposite;
for(unsigned int i_facet = 0; i_facet < n_facets; ++i_facet)
{
// Read a facet, then reindex its vertices.
int i, j, k;
cin >> dummy >> i >> j >> k;
if( dummy != "3" )
{
std::cerr << "In facet #" << i_facet << ", expected \"3\", found \""
<< dummy << "\"!\n";
return 1;
}
i = new_index[i];
j = new_index[j];
k = new_index[k];
facets.push_back(boost::make_tuple(i, j, k));
// Create the three edges of the facet.
Edge e[3];
e[0] = std::make_pair(i, j);
e[1] = std::make_pair(j, k);
e[2] = std::make_pair(k, i);
for(int i_edge = 0; i_edge < 3; ++i_edge)
{
if( e[i_edge].first < e[i_edge].second )
edges[e[i_edge]].push_back(std::make_pair(i_facet, false));
else
edges[opposite(e[i_edge])].push_back(std::make_pair(i_facet, true));
}
}
// Map that stores all already passed facet, and retains the orientation
// of the facet. "true" means that the facet needs to be reoriented.
std::map<int, bool> oriented_set;
// Stack of facets indices to be handled.
std::stack<int> stack;
int seed_facet_candidate = 0;
while (oriented_set.size() != n_facets) {
// find a facet index that is not yet in 'oriented_set'.
while( oriented_set.find(seed_facet_candidate) != oriented_set.end() )
++seed_facet_candidate;
std::cerr << "Need seed facet: " << seed_facet_candidate << "\n";
// push it in oriented set
oriented_set[seed_facet_candidate] = false;
stack.push(seed_facet_candidate);
while(! stack.empty() ) {
const int f = stack.top();
stack.pop();
const int i = boost::get<0>(facets[f]);
const int j = boost::get<1>(facets[f]);
const int k = boost::get<2>(facets[f]);
Edge e[3];
e[0] = std::make_pair(i, j);
e[1] = std::make_pair(j, k);
e[2] = std::make_pair(k, i);
for(int ih = 0 ; ih < 3 ; ++ih)
{
bool f_orient = false;
if(e[ih].first > e[ih].second) {
f_orient = true;
e[ih] = opposite(e[ih]);
}
Edges_map::iterator edge_it = edges.find(e[ih]);
if(edge_it->second.size() == 2) { // regular edge
int fn = edge_it->second[0].first;
bool fn_orient = edge_it->second[0].second;
if(fn == f)
{
fn = edge_it->second[1].first;
fn_orient = edge_it->second[1].second;
}
if (oriented_set.find(fn) == oriented_set.end())
{
if(f_orient == fn_orient)
oriented_set[fn] = ! oriented_set[f];
else
oriented_set[fn] = oriented_set[f];
stack.push(fn);
}
} // end "if the edge is regular"
else {
std::cerr << boost::format("Irregular edge: (%1%,%2%)"
", %3% facets.\n")
% e[ih].first % e[ih].second
% edge_it->second.size();
}
} // end "for each neighbor of f"
} // end "stack non empty"
} // end "oriented_set not full"
for(unsigned int i_facet = 0; i_facet < n_facets; ++i_facet)
{
const int i = boost::get<0>(facets[i_facet]);
const int j = boost::get<1>(facets[i_facet]);
const int k = boost::get<2>(facets[i_facet]);
if(oriented_set[i_facet])
cout << "3 " << j << " " << i << " " << k << "\n";
else
cout << "3 " << i << " " << j << " " << k << "\n";
}
}
| 29.352381
| 76
| 0.571058
|
antoniospg
|
76231a822c50524b2f87ef378d5e7334ef090703
| 2,378
|
hpp
|
C++
|
blast/include/objtools/format/ftable_formatter.hpp
|
mycolab/ncbi-blast
|
e59746cec78044d2bf6d65de644717c42f80b098
|
[
"Apache-2.0"
] | 31
|
2016-12-09T04:56:59.000Z
|
2021-12-31T17:19:10.000Z
|
blast/include/objtools/format/ftable_formatter.hpp
|
mycolab/ncbi-blast
|
e59746cec78044d2bf6d65de644717c42f80b098
|
[
"Apache-2.0"
] | 6
|
2017-03-10T17:25:13.000Z
|
2021-09-22T15:49:49.000Z
|
blast/include/objtools/format/ftable_formatter.hpp
|
mycolab/ncbi-blast
|
e59746cec78044d2bf6d65de644717c42f80b098
|
[
"Apache-2.0"
] | 20
|
2015-01-04T02:15:17.000Z
|
2021-12-03T02:31:43.000Z
|
#ifndef OBJTOOLS_FORMAT___FTABLE_FORMATTER__HPP
#define OBJTOOLS_FORMAT___FTABLE_FORMATTER__HPP
/* $Id: ftable_formatter.hpp 103491 2007-05-04 17:18:18Z kazimird $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aaron Ucko, NCBI
* Mati Shomrat
*
* File Description:
* 5-Column feature table formatting
*/
#include <corelib/ncbistd.hpp>
#include <objtools/format/item_formatter.hpp>
#include <objtools/format/items/feature_item.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
class CSeq_loc;
class NCBI_FORMAT_EXPORT CFtableFormatter : public CFlatItemFormatter
{
public:
CFtableFormatter(void);
void FormatReference(const CReferenceItem& keys, IFlatTextOStream& text_os);
void FormatFeatHeader(const CFeatHeaderItem& fh, IFlatTextOStream& text_os);
void FormatFeature(const CFeatureItemBase& feat, IFlatTextOStream& text_os);
private:
void x_FormatLocation(const CSeq_loc& loc, const string& key,
CBioseqContext& ctx, list<string>& l);
void x_FormatQuals(const CFlatFeature::TQuals& quals, CBioseqContext& ctx,
list<string>& l);
};
END_SCOPE(objects)
END_NCBI_SCOPE
#endif /* OBJTOOLS_FORMAT___FTABLE_FORMATTER__HPP */
| 34.463768
| 80
| 0.707317
|
mycolab
|
7626c7483fb2ea7749e070c7818a48b71e7fa0c9
| 46
|
cpp
|
C++
|
tests/src/experimental/tests_Optional.cpp
|
Mike-Bal/mart-common
|
0b52654c6f756e8e86689e56d24849c97079229c
|
[
"MIT"
] | 1
|
2021-07-16T14:19:50.000Z
|
2021-07-16T14:19:50.000Z
|
tests/src/experimental/tests_Optional.cpp
|
Mike-Bal/mart-common
|
0b52654c6f756e8e86689e56d24849c97079229c
|
[
"MIT"
] | 1
|
2018-06-05T11:03:30.000Z
|
2018-06-05T11:03:30.000Z
|
tests/src/experimental/tests_Optional.cpp
|
tum-ei-rcs/mart-common
|
6f8f18ac23401eb294d96db490fbdf78bf9b316c
|
[
"MIT"
] | null | null | null |
#include <mart-common/experimental/Optional.h>
| 46
| 46
| 0.826087
|
Mike-Bal
|
762a0dc66e72d07d2707b64b32450fe35bb7e0c6
| 2,276
|
cpp
|
C++
|
tc 160+/OptimalList.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 3
|
2015-05-25T06:24:37.000Z
|
2016-09-10T07:58:00.000Z
|
tc 160+/OptimalList.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | null | null | null |
tc 160+/OptimalList.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 5
|
2015-05-25T06:24:40.000Z
|
2021-08-19T19:22:29.000Z
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
const int di[] = { -1, 0, 1, 0 };
const int dj[] = { 0, 1, 0, -1 };
string dir = "NESW";
int getDir(char c) {
return dir.find(c);
}
class OptimalList {
public:
string optimize(string inst) {
int i = 0;
int j = 0;
for (int k=0; k<(int)inst.size(); ++k) {
int d = getDir(inst[k]);
i += di[d];
j += dj[d];
}
int d1;
if (i >= 0)
d1 = 2;
else
d1 = 0;
int d2;
if (j >= 0)
d2 = 1;
else
d2 = 3;
if (dir[d1] > dir[d2])
return string(abs(j), dir[d2]) + string(abs(i), dir[d1]);
else
return string(abs(i), dir[d1]) + string(abs(j), dir[d2]);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arg0 = "NENENNWWWWWS"; string Arg1 = "NNNWWW"; verify_case(0, Arg1, optimize(Arg0)); }
void test_case_1() { string Arg0 = "NNEESSWW"; string Arg1 = ""; verify_case(1, Arg1, optimize(Arg0)); }
void test_case_2() { string Arg0 = "NEWSNWESWESSEWSENSEWSEWESEWWEWEEWESSSWWWWWW"; string Arg1 = "SSSSSSSSWWW"; verify_case(2, Arg1, optimize(Arg0)); }
void test_case_3() { string Arg0 = "NENENE"; string Arg1 = "EEENNN"; verify_case(3, Arg1, optimize(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
OptimalList ___test;
___test.run_test(-1);
}
// END CUT HERE
| 29.558442
| 315
| 0.566784
|
ibudiselic
|
762abd73654bedd41bbb03db5ede2cb40c955af2
| 475
|
cpp
|
C++
|
PassingCars/C++/PassingCars.cpp
|
ArturMarekNowak/Random-Algorithms-Repository
|
bda0e18bed68d3ab1b61b445e693a5c3c03a1179
|
[
"MIT"
] | 1
|
2022-02-12T14:57:48.000Z
|
2022-02-12T14:57:48.000Z
|
PassingCars/C++/PassingCars.cpp
|
ArturMarekNowak/Random-Algorithms-Repository
|
bda0e18bed68d3ab1b61b445e693a5c3c03a1179
|
[
"MIT"
] | null | null | null |
PassingCars/C++/PassingCars.cpp
|
ArturMarekNowak/Random-Algorithms-Repository
|
bda0e18bed68d3ab1b61b445e693a5c3c03a1179
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
int passingCars(std::vector<int> & someVec)
{
if(someVec.size() == 1)
return 0;
int counter = 0, result = 0;
for(int i = someVec.size() - 1; i >= 0; i--)
if(someVec[i] == 1)
counter++;
else if(someVec[i] == 0)
{
result += counter;
if(result > 1000000000)
return -1;
}
return result;
}
int main()
{
std::vector<int> vecOne = {0, 1, 0, 1, 1};
std::cout << passingCars(vecOne) << std::endl;
return 0;
}
| 15.322581
| 47
| 0.574737
|
ArturMarekNowak
|
762ae0e3ad471639a76e787ed602828358d9d040
| 5,668
|
cpp
|
C++
|
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/Audio/Chorus/chorusmodel.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
//
// chorusmodel.cpp
// MDStudio
//
// Created by Daniel Cliche on 2017-05-08.
// Copyright © 2017-2020 Daniel Cliche. All rights reserved.
//
#include "chorusmodel.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdio.h>
#include <string.h>
#define GRAPH_SAMPLE_RATE 44100
#define ROUND(n) ((int)((float)(n) + 0.5))
#define BSZ 8192 // must be about 1/5 of a second at given sample rate
#define MODF(n, i, f) ((i) = (int)(n), (f) = (n) - (float)(i))
using namespace MDStudio;
#define NUM_MIX_MODES 7
// ---------------------------------------------------------------------------------------------------------------------
ChorusModel::ChorusModel() {
_paramWidth = 0.8f;
_paramDelay = 0.2f;
_paramMixMode = 0;
_sweepSamples = 0;
_delaySamples = 22;
_lfoPhase = 0.0f;
setRate(0.2f);
setWidth(0.5f);
_fp = 0;
_sweep = 0.0;
setMixMode(kMixStereoWetOnly);
_wet = 0.0f;
// allocate the buffer
_buf = new GraphSampleType[BSZ];
memset(_buf, 0, sizeof(GraphSampleType) * BSZ);
}
// ---------------------------------------------------------------------------------------------------------------------
ChorusModel::~ChorusModel() {
if (_buf) delete[] _buf;
}
// ---------------------------------------------------------------------------------------------------------------------
void ChorusModel::setRate(float rate) {
_paramSweepRate = rate;
_lfoDeltaPhase = 2 * M_PI * rate / GRAPH_SAMPLE_RATE;
// map into param onto desired sweep range with log curve
_sweepRate = pow(10.0, (double)_paramSweepRate);
_sweepRate -= 1.0;
_sweepRate *= 1.1f;
_sweepRate += 0.1f;
// finish setup
setSweep();
}
// ---------------------------------------------------------------------------------------------------------------------
// Maps 0.0-1.0 input to calculated width in samples from 0ms to 50ms
void ChorusModel::setWidth(float v) {
_paramWidth = v;
// map so that we can spec between 0ms and 50ms
_sweepSamples = ROUND(v * 0.05 * GRAPH_SAMPLE_RATE);
// finish setup
setSweep();
}
// ---------------------------------------------------------------------------------------------------------------------
// Expects input from 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0
void ChorusModel::setDelay(float v) {
_paramDelay = v;
// make onto desired values applying log curve
double delay = pow(10.0, (double)v * 2.0) / 1000.0; // map logarithmically and convert to seconds
_delaySamples = ROUND(delay * GRAPH_SAMPLE_RATE);
// finish setup
setSweep();
}
// ---------------------------------------------------------------------------------------------------------------------
// Sets up sweep based on rate, depth, and delay as they're all interrelated
// Assumes _sweepRate, _sweepSamples, and _delaySamples have all been set by
// setRate, setWidth, and setDelay
void ChorusModel::setSweep() {
// calc min and max sweep now
_minSweepSamples = _delaySamples;
_maxSweepSamples = _delaySamples + _sweepSamples;
// set intial sweep pointer to midrange
_sweep = (_minSweepSamples + _maxSweepSamples) / 2;
}
// ---------------------------------------------------------------------------------------------------------------------
void ChorusModel::setMixMode(int mixMode) {
_paramMixMode = mixMode;
switch (mixMode) {
case kMixMono:
default:
_mixLeftWet = _mixRightWet = 1.0;
_mixLeftDry = _mixRightDry = 1.0f;
break;
case kMixWetOnly:
_mixLeftWet = _mixRightWet = 1.0f;
_mixLeftDry = _mixRightDry = 0.0;
break;
case kMixWetLeft:
_mixLeftWet = 1.0f;
_mixLeftDry = 0.0f;
_mixRightWet = 0.0f;
_mixRightDry = 1.0f;
break;
case kMixWetRight:
_mixLeftWet = 0.0f;
_mixLeftDry = 1.0f;
_mixRightWet = 1.0f;
_mixRightDry = 0.0f;
break;
case kMixStereoWetOnly:
_mixLeftWet = 1.0f;
_mixLeftDry = 0.0f;
_mixRightWet = -1.0f;
_mixRightDry = 0.0f;
break;
}
}
// ---------------------------------------------------------------------------------------------------------------------
void ChorusModel::setWet(float v) { _wet = v; }
// ---------------------------------------------------------------------------------------------------------------------
int ChorusModel::renderInput(UInt32 inNumberFrames, GraphSampleType* ioData[2], UInt32 stride) {
float* io1 = ioData[0];
float* io2 = ioData[1];
for (int i = 0; i < inNumberFrames; ++i) {
// assemble mono input value and store it in circle queue
float inval = (*io1 + *io2) / 2.0f;
_buf[_fp] = inval;
_fp = (_fp + 1) & (BSZ - 1);
// build the two emptying pointers and do linear interpolation
int ep1, ep2;
float w1, w2;
float ep = _fp - _sweep;
MODF(ep, ep1, w2);
ep1 &= (BSZ - 1);
ep2 = ep1 + 1;
ep2 &= (BSZ - 1);
w1 = 1.0 - w2;
GraphSampleType outval = _buf[ep1] * w1 + _buf[ep2] * w2;
// develop output mix
*io1 = (float)(_mixLeftDry * *io1 + _mixLeftWet * _wet * outval);
*io2 = (float)(_mixRightDry * *io2 + _mixRightWet * _wet * outval);
_sweep = _minSweepSamples + _sweepSamples * (sinf(_lfoPhase) + 1.0f) / 2.0f;
_lfoPhase += _lfoDeltaPhase;
_lfoPhase = fmod(_lfoPhase, 2 * M_PI);
io1 += stride;
io2 += stride;
}
return 0;
}
| 31.314917
| 120
| 0.481475
|
dcliche
|
762b2d51877e601a10f55acb64f4fd2c81f7dd2d
| 14,190
|
cc
|
C++
|
src/HR2Scheduler.cc
|
harsha-simhadri/sbsched
|
8d12a010727ea415d5e4a23d389740d57c68278c
|
[
"MIT"
] | 1
|
2020-09-30T14:47:02.000Z
|
2020-09-30T14:47:02.000Z
|
src/HR2Scheduler.cc
|
harsha-simhadri/sbsched
|
8d12a010727ea415d5e4a23d389740d57c68278c
|
[
"MIT"
] | null | null | null |
src/HR2Scheduler.cc
|
harsha-simhadri/sbsched
|
8d12a010727ea415d5e4a23d389740d57c68278c
|
[
"MIT"
] | null | null | null |
// This code is part of the project "Experimental Analysis of Space-Bounded
// Schedulers", presented at Symposium on Parallelism in Algorithms and
// Architectures, 2014.
// Copyright (c) 2014 Harsha Vardhan Simhadri, Guy Blelloch, Phillip Gibbons,
// Jeremy Fineman, Aapo Kyrola.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights (to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "HR2Scheduler.hh"
#include <assert.h>
HR2Scheduler::Cluster::Cluster (const lluint size, const int block_size,
int num_children, int sibling_id,
Cluster * parent, Cluster ** children)
: _size (size),
_block_size (block_size),
_occupied(0),
_num_children(num_children),
_sibling_id(sibling_id),
_parent(parent),
_locked_thread_id (-1) {
_children = new Cluster* [_num_children];
if (children!=NULL)
for (int i=0; i<_num_children; ++i)
_children[i]=children[i];
}
HR2Scheduler::Cluster*
HR2Scheduler::Cluster::create_tree( Cluster * root,
Cluster ** leaf_array,
int num_levels, uint * fan_outs,
lluint * sizes, uint * block_sizes,
int bucket_version) {
static int leaf_counter=0;
Cluster * ret;
if (root == NULL) { // Create the root (RAM) node
ret = new Cluster (1<<((sizeof(lluint)*4)-1) -1, block_sizes[0],
fan_outs[0], 0);
if (bucket_version==0)
ret->_buckets = new Buckets<HR2Job*> (num_levels,0,*block_sizes,sizes,*fan_outs,SIGMA);
else if (bucket_version==1)
ret->_buckets = new TopDistrBuckets<HR2Job*> (num_levels,0,*block_sizes,sizes,*fan_outs,SIGMA);
else
exit(-1);
leaf_counter = 0;
for (int i=0; i<fan_outs[0]; ++i) {
ret->_children[i] = create_tree (ret, leaf_array,
num_levels-1, fan_outs+1,
sizes+1, block_sizes+1,bucket_version);
ret->_children[i]->_sibling_id = i;
}
} else if (num_levels>0) {
ret = new Cluster (sizes[0], block_sizes[0],
fan_outs[0], -1, root);
if (bucket_version==0)
ret->_buckets = new Buckets<HR2Job*> (num_levels,*sizes,*block_sizes,sizes,*fan_outs,SIGMA);
else if (bucket_version==1)
ret->_buckets = new TopDistrBuckets<HR2Job*> (num_levels,*sizes,*block_sizes,sizes,*fan_outs,SIGMA);
else
exit(-1);
for (int i=0; i<fan_outs[0]; ++i) {
ret->_children[i] = create_tree (ret, leaf_array,
num_levels-1, fan_outs+1,
sizes+1, block_sizes+1,bucket_version);
ret->_children[i]->_sibling_id = i;
}
} else {
ret = new Cluster (0, 1, 1, -1, root); // L0 cache/register
leaf_array[leaf_counter++] = ret;
}
return ret;
}
void
HR2Scheduler::print_tree( Cluster * root,
int num_levels, int total_levels) {
if (total_levels == -1) total_levels=num_levels;
if (num_levels > 0) {
for (int i=0; i<total_levels-num_levels; ++i)
std::cout<<"\t\t";
std::cout<<"Occ:"<<root->_occupied<<" | ";
if (root->is_locked())
std::cout<<"L | ";
else
std::cout<<"U | ";
for (int i=0; i<root->_buckets->_num_levels; ++i)
std::cout<<root->_buckets->_queues[i]->size()<<",";
std::cout<<std::endl;
for (int i=0; i<root->_num_children; ++i)
print_tree (root->_children[i], num_levels-1, total_levels);
}
}
void
HR2Scheduler::print_job (HR2Job* sized_job) {
std::cout<<" Job: "<<sized_job->get_id()
<<", Str: "<<sized_job->strand_id()
<<", Pin: "<<sized_job->get_pin_cluster()
<<", Pin_Cl_Sz: "<<((HR2Scheduler::Cluster*)sized_job->get_pin_cluster())->_size
<<", Pin_Cl_Occ: "<<((HR2Scheduler::Cluster*)sized_job->get_pin_cluster())->_occupied
<<std::endl
<<", Task_Size: "<<sized_job->size(1)
<<", Strand_Size: "<<sized_job->strand_size(1)
<<", cont_job? "<<sized_job->is_cont_job()
<<", maximal_job: "<<sized_job->is_maximal()
<<std::endl;
}
HR2Scheduler::HR2Scheduler (int num_threads, int num_levels,
int * fan_outs, lluint * sizes,
int * block_sizes, int bucket_version)
: Scheduler (num_threads) {
_type = 0;
std::cout<<_type<<std::endl;
_tree = new TreeOfCaches;
_tree->_num_levels=num_levels;
_tree->_fan_outs=new uint[_tree->_num_levels];
_tree->_sizes=new lluint[_tree->_num_levels];
_tree->_block_sizes=new uint[_tree->_num_levels];
_tree->_num_leaves=1;
for (int i=0; i<_tree->_num_levels; ++i) {
_tree->_fan_outs[i] = fan_outs[i];
_tree->_sizes[i] = sizes[i];
_tree->_block_sizes[i] = block_sizes[i];
_tree->_num_leaves*=fan_outs[i];
}
_tree->_leaf_array = new Cluster* [_tree->_num_leaves];
_tree->_root = _tree->_root->create_tree (NULL, _tree->_leaf_array, _tree->_num_levels,
_tree->_fan_outs, _tree->_sizes, _tree->_block_sizes,bucket_version);
_tree->_num_locks_held = new int [_tree->_num_leaves];
_tree->_locked_clusters = new Cluster** [_tree->_num_leaves];
for (int i=0; i<_tree->_num_leaves; ++i) {
_tree->_num_locks_held[i] = 0;
_tree->_locked_clusters[i] = new Cluster*[_tree->_num_levels+1+8]; // +8 is to pad each list
for (int j=0; j<_tree->_num_levels+1; ++j)
_tree->_locked_clusters[i][j] = NULL;
}
}
HR2Scheduler::~HR2Scheduler() {
for (int i=0; i<_tree->_num_leaves; ++i) delete _tree->_locked_clusters[i];
delete _tree->_fan_outs;
delete _tree->_sizes;
delete _tree->_block_sizes;
delete _tree->_num_locks_held;
delete _tree->_locked_clusters;
// Delete the cluster tree too
}
// Basic sanity check on locks held by a thread
void
HR2Scheduler::check_lock_consistency (int thread_id) {
for (int i=0; i<_tree->_num_levels+1; ++i) {
if (i<_tree->_num_locks_held[thread_id])
assert (_tree->_locked_clusters[thread_id][i] != NULL);
else
assert (_tree->_locked_clusters[thread_id][i] == NULL);
if (i != _tree->_num_levels+1)
if (_tree->_locked_clusters[thread_id][i] != NULL)
assert (_tree->_locked_clusters[thread_id][i]
!= _tree->_locked_clusters[thread_id][i+1]);
}
}
// Lock up 'node', and add that lock to the locked up node list
void
HR2Scheduler::lock (Cluster* node, int thread_id) {
// std::cout<<"Lock, thr: "<<thread_id<<" "<<node<<std::endl;
if (node->_num_children > 1) {
node->lock();
assert(node->_locked_thread_id == -1);
node->_locked_thread_id = thread_id;
_tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]] = node;
++_tree->_num_locks_held[thread_id];
}
}
bool
HR2Scheduler::has_lock (Cluster* node, int thread_id) {
// std::cerr<<__func__<<": Not currently operational"<<std::endl;
return (node->_num_children==1 || node->_locked_thread_id == thread_id);
}
void
HR2Scheduler::print_locks (int thread_id) {
std::cout<<"Thread "<<thread_id<<" has "<<_tree->_num_locks_held[thread_id]
<<" locks: ";
for (int i=0; i<_tree->_num_locks_held[thread_id]; ++i) {
std::cout<<" '"<<_tree->_locked_clusters[thread_id][i];
}
std::cout<<std::endl;
}
// Check if the node is the last in the list of locked nodes,
void
HR2Scheduler::unlock (Cluster* node, int thread_id) {
//std::cout<<"Unlock, thr: "<<thread_id<<" "<<node<<std::endl;
if (node->_num_children > 1) {
--_tree->_num_locks_held[thread_id];
_tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]] = NULL;
assert(node->_locked_thread_id == thread_id);
node->_locked_thread_id = -1;
node->unlock();
}
}
// Release all locks held by thread in the inverse order they were obtained
void
HR2Scheduler::release_locks (int thread_id) {
while (_tree->_num_locks_held[thread_id] > 0)
unlock (_tree->_locked_clusters[thread_id][_tree->_num_locks_held[thread_id]-1], thread_id);
}
/* Should be called only by a thread holding a lock on the current cluster */
void
HR2Scheduler::pin (HR2Job *job, Cluster *cluster) {
assert (cluster->_occupied <= cluster->_size);
job->pin_to_cluster (cluster, job->size(cluster->_block_size));
}
void
HR2Scheduler::add (Job* uncast_job, int thread_id) {
HR2Job* job = (HR2Job*)uncast_job;
Cluster *root = _tree->_root;
/* Job added by an agent other than the threads */
if (thread_id == _num_threads) {
root->lock ();
pin (job, root);
root->_occupied+=job->size(root->_block_size);
root->_buckets->add_job_to_bucket (job, 0);
root->unlock ();
return;
}
/* If root has no active job, set it here */
if (job->get_pin_cluster() == NULL) {
for (Cluster *cur = _tree->_leaf_array[thread_id];cur->_parent!=NULL;cur = cur->_parent)
lock (cur, thread_id);
pin (job, root);
root->_occupied+=job->size(root->_block_size);
release_locks (thread_id);
}
/* Add job to the approporiate queue */
int child_id=0;
for (Cluster * cur = _tree->_leaf_array[thread_id];;cur = cur->_parent ) {
if (job->get_pin_cluster() == cur) {
cur->_buckets->add_job_to_bucket (job, child_id);
return;
}
child_id = cur->_sibling_id;
}
assert (false);exit(-1);
}
void
HR2Scheduler::add_multiple (int num_jobs, Job** uncast_jobs, int thread_id) {
HR2Job* job = (HR2Job*)uncast_jobs[0];
Cluster *root = _tree->_root;
/* Job added by an agent other than the threads */
if (thread_id == _num_threads) {
root->lock ();
for (int i=0; i<num_jobs; ++i) {
job = (HR2Job*)uncast_jobs[i];
pin (job, root);
root->_occupied+=job->size(root->_block_size);
root->_buckets->add_job_to_bucket (job, 0);
}
root->unlock ();
return;
}
/* If root has no active job, set it here */
if (job->get_pin_cluster() == NULL) {
for (Cluster *cur = _tree->_leaf_array[thread_id];cur->_parent!=NULL;cur = cur->_parent)
lock (cur, thread_id);
for (int i=0; i<num_jobs; ++i) {
job = (HR2Job*)uncast_jobs[i];
pin (job, root);
root->_occupied+=job->size(root->_block_size);
}
release_locks (thread_id);
}
/* Add job to the approporiate queue */
int child_id=0;
for (Cluster * cur = _tree->_leaf_array[thread_id];;cur = cur->_parent ) {
if (job->get_pin_cluster() == cur) {
for (int i=0; i<num_jobs; ++i) {
job = (HR2Job*)uncast_jobs[i];
cur->_buckets->add_job_to_bucket (job, child_id);
}
return;
}
child_id = cur->_sibling_id;
}
assert (false);exit(-1);
}
void
HR2Scheduler::done (Job *uncast_job, int thread_id, bool deactivate) {
HR2Job * job = (HR2Job*)uncast_job;
Cluster * cur = _tree->_leaf_array[thread_id];
Cluster * pin = (Cluster*) job->get_pin_cluster();
/* Update occupied size */
for ( ; cur!=pin; cur=cur->_parent) {
lluint strand_size = job->strand_size(cur->_block_size);
lock (cur,thread_id);
cur->_occupied -= (strand_size>(int)(MU*(cur->_size)) ? (int)(MU*(cur->_size)) : strand_size);
}
/* If the done task started a pin, clean up the allocation */
if (deactivate) { // Strand joins and end its task
if (job->is_maximal()) {
lock (cur, thread_id);
cur->_occupied -= job->size(cur->_block_size);
}
}
release_locks (thread_id);
/* Last job done in the system */
if (job->parent_fork()==NULL && deactivate) {
//print_tree (_tree->_root, _tree->_num_levels, _tree->_num_levels);
//std::cout<<"Finished root task at thread: "<<thread_id<<std::endl;
}
}
bool
HR2Scheduler::fit_job (HR2Job *job, int thread_id, int height, int bucket_level) {
Cluster *leaf=_tree->_leaf_array[thread_id];
Cluster *cur=leaf;
for (int i=0; i<height-bucket_level; ++i) {
lock (cur, thread_id);
if (cur->_occupied > (1-MU)*(double)cur->_size) {
release_locks (thread_id);
return false;
}
cur=cur->_parent;
}
lluint task_size = job->size (cur->_block_size);
assert (task_size <= SIGMA*(cur->_size) || cur->_parent == NULL);
if (bucket_level > 0) {
assert (!job->is_cont_job());
lock (cur, thread_id);
if (task_size > cur->_size-cur->_occupied) {
release_locks (thread_id);
return false;
} else {
pin (job, cur);
assert (job->is_maximal());
cur->_occupied += task_size;
}
} else {
assert (job->get_pin_cluster() == cur);
}
for (Cluster *iter=leaf; iter!=cur ; iter=iter->_parent) {
lluint strand_size = ((HR2Job*)job)->strand_size (iter->_block_size);
assert (has_lock (iter, thread_id));
assert (iter->_occupied <= (1-MU)*iter->_size);
iter->_occupied += (strand_size<(int)(MU*iter->_size) ? strand_size : (int)(MU*iter->_size));
}
release_locks(thread_id);
return true;
}
Job*
HR2Scheduler::get (int thread_id) {
HR2Job * job = NULL;
int height=1; int child_id=_tree->_leaf_array[thread_id]->_sibling_id;
for ( Cluster *cur=_tree->_leaf_array[thread_id]->_parent;
cur!=NULL; cur=cur->_parent,++height) {
int level = cur->_buckets->get_job_from_bucket(&job, 0, child_id);
while (level !=-1) {
if (fit_job (job, thread_id, height, level)==true) {
release_locks(thread_id);
return job;
} else {
cur->_buckets->return_to_queue (job, level, child_id);
}
level = cur->_buckets->get_job_from_bucket(&job, 1+level, child_id);
}
if ( cur->_occupied > (int)((1-MU)* cur->_size) )
return NULL;
child_id = cur->_sibling_id;
}
return NULL;
}
bool
HR2Scheduler::more (int thread_id) {
std::cerr<<__func__<<" has been deprecated"<<std::endl;
exit (-1);
}
| 31.744966
| 106
| 0.657717
|
harsha-simhadri
|
762d09dad5ba121135195bebd503ada89e9d4a39
| 144
|
hpp
|
C++
|
star.rg/include/tileDB.hpp
|
masscry/badbaby
|
f0b2e793081491ed7598d3170725fe4b48ae1fff
|
[
"MIT"
] | null | null | null |
star.rg/include/tileDB.hpp
|
masscry/badbaby
|
f0b2e793081491ed7598d3170725fe4b48ae1fff
|
[
"MIT"
] | null | null | null |
star.rg/include/tileDB.hpp
|
masscry/badbaby
|
f0b2e793081491ed7598d3170725fe4b48ae1fff
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef TILE_DATABASE_HEADER
#define TILE_DATABASE_HEADER
extern const tileInfo_t tileID[];
#endif // TILE_DATABASE_HEADER
| 10.285714
| 33
| 0.791667
|
masscry
|
7631c1aa955429bb64b7372f54adb09b33ab2d4e
| 3,619
|
cpp
|
C++
|
core123/ut/ut_simd_threefry.cpp
|
fennm/fs123
|
559b97659352620ce16030824f9acd26f590f4e1
|
[
"BSD-3-Clause"
] | 22
|
2019-04-10T18:05:35.000Z
|
2021-12-30T12:26:39.000Z
|
core123/ut/ut_simd_threefry.cpp
|
fennm/fs123
|
559b97659352620ce16030824f9acd26f590f4e1
|
[
"BSD-3-Clause"
] | 13
|
2019-04-09T00:19:29.000Z
|
2021-11-04T15:57:13.000Z
|
core123/ut/ut_simd_threefry.cpp
|
fennm/fs123
|
559b97659352620ce16030824f9acd26f590f4e1
|
[
"BSD-3-Clause"
] | 4
|
2019-04-07T16:33:44.000Z
|
2020-07-02T02:58:51.000Z
|
#if defined(__ICC)
#include <stdio.h>
int main(int, char **){
printf(__FILE__ " Icc (through version 18) doesn't fully support gcc's 'vector' extensions.");
return 0;
}
#else
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wpsabi" // see comments in simd_threefry.hpp
#include <core123/simd_threefry.hpp>
#include <core123/streamutils.hpp>
#include <core123/timeit.hpp>
#include <numeric>
#include <iostream>
#include <chrono>
using core123::threefry;
using core123::insbe;
using core123::timeit;
using namespace std::chrono;
static constexpr unsigned ROUNDS = 12;
int main(int, char **){
using vcbrng = threefry<4, uint64_tx8, ROUNDS>;
vcbrng::domain_type ctr;
using eltype = vcbrng::domain_type::value_type;
ctr[0] = eltype{00,01,02,03,04,05,06,07};
ctr[1] = eltype{10,11,12,13,14,15,16,17};
if(ctr.size()>2){
ctr[2] = eltype{20,21,22,23,24,25,26,27};
ctr[3] = eltype{30,31,32,33,34,35,36,37};
}
{
vcbrng tf;
auto r = tf(ctr);
std::cout << "Vector threefry: sizeof(range_type): " << sizeof(vcbrng::range_type) << "\n";
std::cout << std::hex;
switch(r.size()){
case 4:
std::cout << r[0][0] << " " << r[1][0] << " " << r[2][0] << " " << r[3][0] << "\n";
std::cout << r[0][1] << " " << r[1][1] << " " << r[2][1] << " " << r[3][1] << "\n";
std::cout << r[0][2] << " " << r[1][2] << " " << r[2][2] << " " << r[3][2] << "\n";
std::cout << r[0][3] << " " << r[1][3] << " " << r[2][3] << " " << r[3][3] << "\n";
break;
case 2:
throw "Nope. Not done yet";
std::cout << r[0][0] << " " << r[1][0] << "\n";
std::cout << r[0][1] << " " << r[1][1] << "\n";
std::cout << r[0][2] << " " << r[1][2] << "\n";
std::cout << r[0][3] << " " << r[1][3] << "\n";
break;
}
tf.setkey(r); // Don't allow the optimizer to exploit zero-valued keys.
ctr = r; // set the key and counter to "random" values
static const int LOOP = 2;
static const int millis = 2000;
eltype sum = {};
auto result = timeit(milliseconds(millis),
[&ctr, &sum, tf](){
eltype incr = {1, 1, 1, 1, 1, 1, 1, 1};
for(int i=0; i<LOOP; ++i){
ctr[0] += incr;
auto rv = tf(ctr);
sum = std::accumulate(rv.begin(), rv.end(), sum); // i.e., sum += r[0] + r[1] + .. + r[N-1];
}
});
// Print the sum, so the optimizer can't elide the whole thing!
std::cout << "sum = " << sum[0] << " " << sum[1] << " " << sum[2] << " " << sum[3] << " " << sum[4] << " " << sum[5] << " " << sum[6] << " " << sum[7] << "\n";
float ns_per_byte = 1.e9*result.sec_per_iter()/LOOP/sizeof(vcbrng::range_type);
printf("8-way simd threefry: %lld calls in about %d ms. %.2f ns per call. %.3f ns per byte.\n",
LOOP*result.count, millis,
1.e9*result.sec_per_iter()/LOOP, ns_per_byte);
static const float GHz = 3.7;
printf("at %.1fGHz that's %.2f cpb or %.1f bytes per cycle\n", GHz, ns_per_byte * GHz, 1./(ns_per_byte * GHz));
}
std::cout << "Scalar threefry:\n";
{
using cbrng = threefry<4, uint64_t, ROUNDS>;
cbrng::range_type r;
cbrng tf;
r = tf({00, 10, 20, 30});
std::cout << insbe(r) << "\n";
r = tf({01, 11, 21, 31});
std::cout << insbe(r) << "\n";
r = tf({02, 12, 22, 32});
std::cout << insbe(r) << "\n";
r = tf({03, 13, 23, 33});
std::cout << insbe(r) << "\n";
}
return 0;
}
#endif // not __ICC
| 36.555556
| 163
| 0.498757
|
fennm
|
7632d97bf2358fb269500f0dc8461a4d5a7f9069
| 244
|
cpp
|
C++
|
Index.cpp
|
Robert-xiaoqiang/MiniSQL-TeamLanTianLiuShe
|
9dcad804615412e85de31797c0a0afb84135918f
|
[
"MIT"
] | 2
|
2018-07-29T03:08:45.000Z
|
2019-06-08T15:41:24.000Z
|
Index.cpp
|
Robert-xiaoqiang/MiniSQL-TeamLanTianLiuShe
|
9dcad804615412e85de31797c0a0afb84135918f
|
[
"MIT"
] | null | null | null |
Index.cpp
|
Robert-xiaoqiang/MiniSQL-TeamLanTianLiuShe
|
9dcad804615412e85de31797c0a0afb84135918f
|
[
"MIT"
] | 1
|
2019-05-24T05:08:06.000Z
|
2019-05-24T05:08:06.000Z
|
#include "Index.h"
Index::Index(std::string new_name, std::string new_table_name, std::string new_attr_name, attr_type new_type):
name(new_name), table_name(new_table_name), attr_name(new_attr_name), type(new_type)
{
}
Index::~Index()
{
}
| 18.769231
| 110
| 0.745902
|
Robert-xiaoqiang
|
76391c5d2e93b899fb7a50edf3fecfa8d866424c
| 1,462
|
cxx
|
C++
|
doctype/solarmail.cxx
|
re-Isearch/re-Isearch
|
f2a2012c1814b0940a6004b6186a5e6896c1135a
|
[
"BSD-4-Clause-UC",
"Apache-2.0"
] | 2
|
2022-02-05T17:48:29.000Z
|
2022-02-06T15:25:04.000Z
|
doctype/solarmail.cxx
|
re-Isearch/re-Isearch
|
f2a2012c1814b0940a6004b6186a5e6896c1135a
|
[
"BSD-4-Clause-UC",
"Apache-2.0"
] | null | null | null |
doctype/solarmail.cxx
|
re-Isearch/re-Isearch
|
f2a2012c1814b0940a6004b6186a5e6896c1135a
|
[
"BSD-4-Clause-UC",
"Apache-2.0"
] | 1
|
2022-03-30T20:14:00.000Z
|
2022-03-30T20:14:00.000Z
|
static const char RCS_Id[]="$Id: solarmail.cxx,v 1.1 2007/05/15 15:47:29 edz Exp $";
/* ########################################################################
Usenet News Folder Doctype
Basis Systeme netzwerk
Brecherspitzstr. 8
D-81541 Munich, Germany
File: sunfolder.cxx
Description: Class SOLARMAIL - Sun Solaris 2.x Mailfolder Document Type
Version: $Revision: 1.1 $
Created: Sun Dec 24 23:11:21 MET 1995
Author: Edward C. Zimmermann <edz@nonmonotonic.net>
Modified: Sun Dec 24 23:11:22 MET 1995
Last maintained by: Edward C. Zimmermann <edz@nonmonotonic.net>
(c) Copyright 1995
Basis Systeme netzwerk, Munich
########################################################################
Note: This is really just an alias for mailfolder....
####################################################################### */
#include "solarmail.hxx"
SOLARMAIL::SOLARMAIL (PIDBOBJ DbParent): MAILFOLDER::MAILFOLDER (DbParent)
{
}
void SOLARMAIL::ParseRecords (const RECORD& FileRecord)
{
#if BSN_EXTENSIONS
RECORD Record (FileRecord); // Easy way
#else
/* CNIDR must do it the hard way! (see above ) */
RECORD Record;
STRING s;
FileRecord.GetPath(&s);
Record.SetPath( s );
FileRecord.GetFileName(&s);
Record.SetFileName( s );
FileRecord.GetDocumentType(&s);
#endif
Record.SetDocumentType ("MAILFOLDER");
MAILFOLDER::ParseRecords (Record);
}
SOLARMAIL::~SOLARMAIL ()
{
}
| 26.107143
| 84
| 0.589603
|
re-Isearch
|
763e5b8db9c5b5d782ba03570f8a664a402f751e
| 4,163
|
hpp
|
C++
|
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
|
TakahiroNISHIOKA/scenario_simulator_v2
|
949a46a64a26d17413c2586577e1f3a5ba41161e
|
[
"Apache-2.0"
] | null | null | null |
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
|
TakahiroNISHIOKA/scenario_simulator_v2
|
949a46a64a26d17413c2586577e1f3a5ba41161e
|
[
"Apache-2.0"
] | null | null | null |
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/execution_timer.hpp
|
TakahiroNISHIOKA/scenario_simulator_v2
|
949a46a64a26d17413c2586577e1f3a5ba41161e
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2015-2020 Tier IV, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_
#define OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_
#include <chrono>
#include <cmath>
#include <functional>
#include <unordered_map>
namespace openscenario_interpreter
{
inline namespace utility
{
template <typename Clock = std::chrono::system_clock>
class ExecutionTimer
{
class Statistics
{
std::int64_t ns_max = 0;
std::int64_t ns_min = std::numeric_limits<std::int64_t>::max();
std::int64_t ns_sum = 0;
std::int64_t ns_square_sum = 0;
int count = 0;
public:
template <typename Duration>
auto add(Duration diff) -> void
{
std::int64_t diff_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(diff).count();
count++;
ns_max = std::max(ns_max, diff_ns);
ns_min = std::min(ns_max, diff_ns);
ns_sum += diff_ns;
ns_square_sum += std::pow(diff_ns, 2);
}
template <typename T>
auto max() const
{
return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_max));
}
template <typename T>
auto min() const
{
return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_min));
}
template <typename T>
auto mean() const
{
return std::chrono::duration_cast<T>(std::chrono::nanoseconds(ns_sum / count));
}
template <typename T>
auto standardDeviation() const
{
std::int64_t mean_of_square = ns_square_sum / count;
std::int64_t square_of_mean = std::pow(ns_sum / count, 2);
std::int64_t var = mean_of_square - square_of_mean;
double standard_deviation = std::sqrt(var);
return std::chrono::duration_cast<T>(
std::chrono::nanoseconds(static_cast<std::int64_t>(standard_deviation)));
}
friend auto operator<<(std::ostream & os, const Statistics & statistics) -> std::ostream &
{
using namespace std::chrono;
return os << "mean = " << statistics.template mean<milliseconds>().count() << " ms, "
<< "max = " << statistics.template max<milliseconds>().count() << " ms, "
<< "standard deviation = "
<< statistics.template standardDeviation<milliseconds>().count() / 1000.0 << " ms";
}
};
std::unordered_map<std::string, Statistics> statistics_map;
public:
template <typename Thunk, typename... Ts>
auto invoke(const std::string & tag, Thunk && thunk) -> typename std::enable_if<
std::is_same<typename std::result_of<Thunk()>::type, void>::value,
typename Clock::duration>::type
{
const auto begin = Clock::now();
thunk();
const auto end = Clock::now();
statistics_map[tag].add(end - begin);
return end - begin;
}
template <typename Thunk, typename... Ts>
auto invoke(const std::string & tag, Thunk && thunk) -> typename std::enable_if<
std::is_same<typename std::result_of<Thunk()>::type, bool>::value,
typename Clock::duration>::type
{
const auto begin = Clock::now();
const auto result = thunk();
const auto end = Clock::now();
if (result) {
statistics_map[tag].add(end - begin);
}
return end - begin;
}
auto clear() { statistics_map.clear(); }
auto getStatistics(const std::string & tag) -> const auto & { return statistics_map[tag]; }
auto begin() const { return statistics_map.begin(); }
auto end() const { return statistics_map.end(); }
};
} // namespace utility
} // namespace openscenario_interpreter
#endif // OPENSCENARIO_INTERPRETER__UTILITY__EXECUTION_TIMER_HPP_
| 29.111888
| 99
| 0.664425
|
TakahiroNISHIOKA
|
76427c417c94cb5460cf6ef17f43fbcd44277d62
| 293
|
hpp
|
C++
|
src/resources/resource.hpp
|
ifamakes/sidhe-cpp
|
ce660872fa0c9eba7d41357ab330410a397f59eb
|
[
"CC0-1.0"
] | null | null | null |
src/resources/resource.hpp
|
ifamakes/sidhe-cpp
|
ce660872fa0c9eba7d41357ab330410a397f59eb
|
[
"CC0-1.0"
] | null | null | null |
src/resources/resource.hpp
|
ifamakes/sidhe-cpp
|
ce660872fa0c9eba7d41357ab330410a397f59eb
|
[
"CC0-1.0"
] | null | null | null |
#pragma once
#include <iostream>
#include <string>
struct Resource {
virtual ~Resource() = default;
virtual void print() const = 0;
};
struct File : Resource {
std::string_view filename;
virtual void print() const override {
std::cout << __PRETTY_FUNCTION__ << std::endl;
};
};
| 19.533333
| 50
| 0.675768
|
ifamakes
|
76442cf857d809354d445c7ecfb216a91d327ab3
| 15,115
|
cpp
|
C++
|
src/server.cpp
|
Subsentient/nexus
|
719cca618afe8729522607ed35e9415d76582347
|
[
"Unlicense"
] | 2
|
2016-03-17T21:25:51.000Z
|
2021-09-02T13:20:23.000Z
|
src/server.cpp
|
Subsentient/nexus
|
719cca618afe8729522607ed35e9415d76582347
|
[
"Unlicense"
] | 1
|
2018-03-04T18:55:48.000Z
|
2018-03-07T00:19:37.000Z
|
src/server.cpp
|
Subsentient/nexus
|
719cca618afe8729522607ed35e9415d76582347
|
[
"Unlicense"
] | 2
|
2016-03-19T00:31:27.000Z
|
2017-01-09T23:41:32.000Z
|
/*NEXUS IRC session BNC, by Subsentient. This software is public domain.*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#ifdef WIN
#include <winsock2.h>
#else
#include <fcntl.h>
#endif
#include <list>
#include <string>
#include "server.h"
#include "netcore.h"
#include "config.h"
#include "nexus.h"
#include "state.h"
#include "scrollback.h"
#include "irc.h"
#include "substrings/substrings.h"
/**This file has our IRC pseudo-server that we run ourselves and its interaction with clients.**/
//Globals
std::list<struct ClientListStruct> ClientListCore;
struct ClientListStruct *CurrentClient, *PreviousClient;
//Prototypes
namespace Server
{
static void SendChannelNamesList(const class ChannelList *const Channel, struct ClientListStruct *Client);
static void SendChannelRejoin(const class ChannelList *const Channel, const int ClientDescriptor);
static void SendIRCWelcome(const int ClientDescriptor);
}
//Functions
struct ClientListStruct *Server::ClientList::Lookup(const int Descriptor)
{
std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin();
for (; Iter != ClientListCore.end(); ++Iter)
{
if (Iter->Descriptor == Descriptor)
{
return &*Iter; //Not used to doing this kind of weird shit. That'd seem really stupid and redundant in C, where Iter would be a pointer.
}
}
return NULL;
}
struct ClientListStruct *Server::ClientList::Add(const struct ClientListStruct *const InStruct)
{
ClientListCore.push_front(*InStruct);
return &*ClientListCore.begin();
}
void Server::ClientList::Shutdown(void)
{
ClientListCore.clear();
PreviousClient = NULL;
CurrentClient = NULL;
}
bool Server::ClientList::Del(const int Descriptor)
{
std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin();
for (; Iter != ClientListCore.end(); ++Iter)
{
if (Iter->Descriptor == Descriptor)
{
if (&*Iter == CurrentClient) CurrentClient = reinterpret_cast<struct ClientListStruct*>(-1);
if (&*Iter == PreviousClient) PreviousClient = reinterpret_cast<struct ClientListStruct*>(-1);
ClientListCore.erase(Iter);
return true;
}
}
return false;
}
bool Server::ForwardToAll(const char *const InStream)
{ //This function sends the provided text stream to all clients. Very simple.
std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin();
for (; Iter != ClientListCore.end(); ++Iter)
{
Iter->SendLine(InStream);
}
return true;
}
bool Server::NukeClient(const int Descriptor)
{ //Close the descriptor, remove from select() tracking, and purge him from our minds.
struct ClientListStruct *Client = Server::ClientList::Lookup(Descriptor);
if (!Client) return false;
Net::Close(Client->Descriptor);
NEXUS::DescriptorSet_Del(Client->Descriptor);
Server::ClientList::Del(Client->Descriptor);
return true;
}
void Server::SendQuit(const int Descriptor, const char *const Reason)
{ //Tells all clients or just one client to quit
std::list<struct ClientListStruct>::iterator Iter = ClientListCore.begin();
char OutBuf[2048];
for (; Iter != ClientListCore.end(); ++Iter)
{
//If not on "everyone" mode we check if the descriptor matches.
if (Descriptor != -1 && Descriptor != Iter->Descriptor) continue;
if (Reason)
{
snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s QUIT :%s\r\n", IRCConfig.Nick, Iter->Ident, Iter->IP, Reason);
}
else
{
snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s QUIT :Disconnected from NEXUS.\r\n", IRCConfig.Nick, Iter->Ident, Iter->IP);
}
try
{
Net::Write(Iter->Descriptor, OutBuf, strlen(OutBuf));
}
catch (...) {}
}
}
static void Server::SendIRCWelcome(const int ClientDescriptor)
{
char OutBuf[2048];
struct ClientListStruct *Client = Server::ClientList::Lookup(ClientDescriptor);
std::map<std::string, ChannelList>::iterator Iter = ChannelListCore.begin();
const int ClientCount = ClientListCore.size();
if (!Client) return;
//First thing we send is our greeting, telling them they're connected OK.
snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 001 %s :NEXUS is forwarding you to server %s:%hu\r\n",
IRCConfig.Nick, IRCConfig.Server, IRCConfig.PortNum); //Putting IRCConfig.Nick here is the same as sending a NICK command.
Client->SendLine(OutBuf);
//Tell them to join all channels we are already in.
for (; Iter != ChannelListCore.end(); ++Iter)
{
Server::SendChannelRejoin(&Iter->second, Client->Descriptor);
}
//Count clients for our next cool little trick.
/**Send a MOTD.**/
//Send the beginning.
snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 375 %s :Welcome to NEXUS " NEXUS_VERSION
". You are being forwarded to \"%s:%hu\".\r\n", IRCConfig.Nick, IRCConfig.Server, IRCConfig.PortNum);
Client->SendLine(OutBuf);
//For dumb bots that connect, make it abundantly clear what their nick should be.
snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s NICK :%s\r\n", Client->OriginalNick, Client->Ident, Client->IP, IRCConfig.Nick);
Client->SendLine(OutBuf);
//Send the middle.
snprintf(OutBuf, sizeof OutBuf,
":" NEXUS_FAKEHOST " 372 %s :There are currently %d other instances connected to this NEXUS server.\r\n",
IRCConfig.Nick, ClientCount - 1);
Client->SendLine(OutBuf);
//Send the end.
snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 376 %s :End of MOTD.\r\n", IRCConfig.Nick);
Client->SendLine(OutBuf);
//Send all scrollback.
Scrollback::SendAllToClient(Client);
}
static void Server::SendChannelNamesList(const class ChannelList *const Channel, struct ClientListStruct *Client)
{
char OutBuf[2048];
unsigned Ticker = 1;
std::map<std::string, struct UserStruct> &UserListRef = Channel->GetUserList();
std::map<std::string, struct UserStruct>::iterator Iter = UserListRef.begin();
SendBegin:
std::string OutString = std::string(":" NEXUS_FAKEHOST " 353 ") + IRCConfig.Nick + " = " + Channel->GetChannelName() + " :";
for (Ticker = 1; Iter != UserListRef.end(); ++Iter, ++Ticker)
{
const struct UserStruct *Worker = &Iter->second;
//Reconstitute the mode flag for this user.
const char Sym = State::UserModes_Get_Mode2Symbol(Worker->Modes);
if (Sym)
{
OutString += Sym;
}
OutString += Worker->Nick;
std::map<std::string, struct UserStruct>::iterator TempIter = Iter;
++TempIter;
if (Ticker == 20 || TempIter == UserListRef.end())
{
OutString += "\r\n";
Client->SendLine(OutString.c_str());
if (TempIter != UserListRef.end())
{
goto SendBegin;
}
}
else
{
OutString += " ";
}
}
snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 366 %s %s :End of /NAMES list.\r\n", IRCConfig.Nick, Channel->GetChannelName());
Client->SendLine(OutBuf);
}
static void Server::SendChannelRejoin(const class ChannelList *const Channel, const int ClientDescriptor)
{ //Sends the list of channels we are in to the client specified.
char OutBuf[2048];
struct ClientListStruct *Client = Server::ClientList::Lookup(ClientDescriptor);
if (!Client) return;
//Send the join command.
snprintf(OutBuf, sizeof OutBuf, ":%s!%s@%s JOIN %s\r\n", IRCConfig.Nick, Client->Ident, Client->IP, Channel->GetChannelName());
Client->SendLine(OutBuf);
//Send the topic and the setter of the topic.
if (*Channel->GetTopic() && *Channel->GetWhoSetTopic() && Channel->GetWhenSetTopic() != 0)
{
snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 332 %s %s :%s\r\n", IRCConfig.Nick, Channel->GetChannelName(), Channel->GetTopic());
Client->SendLine(OutBuf);
snprintf(OutBuf, sizeof OutBuf, ":" NEXUS_FAKEHOST " 333 %s %s %s %u\r\n", IRCConfig.Nick,
Channel->GetChannelName(), Channel->GetWhoSetTopic(), Channel->GetWhenSetTopic());
Client->SendLine(OutBuf);
}
//Send list of users.
Server::SendChannelNamesList(Channel, Client);
}
struct ClientListStruct *Server::AcceptLoop(void)
{
struct ClientListStruct TempClient;
char InBuf[2048];
struct ClientListStruct *Client = NULL;
bool UserProvided = false, NickProvided = false;
bool PasswordProvided = false;
if (!Net::AcceptClient(&TempClient.Descriptor, TempClient.IP, sizeof TempClient.IP))
{ //No client.
return NULL;
}
///Apparently there is a client.
Client = Server::ClientList::Add(&TempClient); //Store their information.
/**Continuously try to read their replies until we get them.**/
while (!UserProvided || !NickProvided)
{ //Wait for their greeting.
const bool NetReadReturn = Net::Read(Client->Descriptor, InBuf, sizeof InBuf, true);
if (!NetReadReturn)
{
Server::NukeClient(Client->Descriptor);
return NULL;
}
//Does it start with USER?
if (!strncmp(InBuf, "USER", sizeof "USER" - 1) || !strncmp(InBuf, "user", sizeof "user" - 1))
{ //This information is needed to fool the IRC clients.
const char *TWorker = InBuf + sizeof "USER";
unsigned Inc = 0;
//If we want a password, WE WANT A PASSWORD. You're supposed to send PASS first, dunce!
if (*NEXUSConfig.ServerPassword && !PasswordProvided)
{
Server::NukeClient(Client->Descriptor);
return NULL;
}
while (*TWorker == ' ' || *TWorker == ':') ++TWorker;
for (; TWorker[Inc] != ' ' && TWorker[Inc] != '\0' && Inc < sizeof Client->Ident - 1; ++Inc)
{ //Copy in the ident they sent us.
Client->Ident[Inc] = TWorker[Inc];
}
Client->Ident[Inc] = '\0';
UserProvided = true;
}
else if (!strncmp(InBuf, "NICK", sizeof "NICK" - 1) || !strncmp(InBuf, "nick", sizeof "nick" - 1))
{
const char *TWorker = InBuf + sizeof "nick";
//If we want a password, WE WANT A PASSWORD.
if (*NEXUSConfig.ServerPassword && !PasswordProvided)
{
Net::Close(Client->Descriptor);
return NULL;
}
while (*TWorker == ' ' || *TWorker == ':') ++TWorker;
strncpy(Client->OriginalNick, TWorker, sizeof Client->OriginalNick - 1); //Copy in their chosen nick.
Client->OriginalNick[sizeof Client->OriginalNick - 1] = '\0';
NickProvided = true;
}
else if (!strncmp(InBuf, "PASS", sizeof "PASS" - 1))
{
const char *TW = InBuf + sizeof "PASS";
if (!*NEXUSConfig.ServerPassword)
{ //We don't NEED a password. Just ignore this.
continue;
}
while (*TW == ' ') ++TW;
if (!strcmp(TW, NEXUSConfig.ServerPassword)) PasswordProvided = true;
else
{ //Wrong password.
Net::Close(Client->Descriptor);
return NULL;
}
}
continue;
}
//Time to welcome them.
Server::SendIRCWelcome(Client->Descriptor);
//Return the client we found.
return Client;
}
enum ServerMessageType Server::GetMessageType(const char *InStream_)
{ //Another function torn out of aqu4bot.
const char *InStream = InStream_;
char Command[32];
unsigned Inc = 0;
for (; InStream[Inc] != ' ' && InStream[Inc] != '\0' && Inc < sizeof Command - 1; ++Inc)
{ /*Copy in the command.*/
Command[Inc] = toupper(InStream[Inc]);
}
Command[Inc] = '\0';
/*Time for the comparison.*/
if (!strcmp(Command, "PRIVMSG")) return SERVERMSG_PRIVMSG;
else if (!strcmp(Command, "NOTICE")) return SERVERMSG_NOTICE;
else if (!strcmp(Command, "MODE")) return SERVERMSG_MODE;
else if (!strcmp(Command, "JOIN")) return SERVERMSG_JOIN;
else if (!strcmp(Command, "PART")) return SERVERMSG_PART;
else if (!strcmp(Command, "PING")) return SERVERMSG_PING;
else if (!strcmp(Command, "PONG")) return SERVERMSG_PONG;
else if (!strcmp(Command, "NICK")) return SERVERMSG_NICK;
else if (!strcmp(Command, "QUIT")) return SERVERMSG_QUIT;
else if (!strcmp(Command, "KICK")) return SERVERMSG_KICK;
else if (!strcmp(Command, "KILL")) return SERVERMSG_KILL;
else if (!strcmp(Command, "INVITE")) return SERVERMSG_INVITE;
else if (!strcmp(Command, "TOPIC")) return SERVERMSG_TOPIC;
else if (!strcmp(Command, "NAMES")) return SERVERMSG_NAMES;
else if (!strcmp(Command, "WHO")) return SERVERMSG_WHO;
else return SERVERMSG_UNKNOWN;
}
bool ClientListStruct::Ping()
{
std::string Out = "PING :" NEXUS_FAKEHOST "\r\n";
bool RetVal = false;
#ifdef WIN
u_long Value = 1;
ioctlsocket(this->Descriptor, FIONBIO, &Value);
#else
fcntl(this->Descriptor, F_SETFL, O_NONBLOCK); //Set nonblocking. Necessary for our single-threaded model.
#endif //WIN
try
{
Net::Write(this->Descriptor, Out.c_str(), Out.length());
}
catch (Net::Errors::Any)
{
goto End;
}
RetVal = true;
this->PingSentTime = time(NULL);
this->WaitingForPing = true;
End:
#ifdef WIN
Value = 0;
ioctlsocket(this->Descriptor, FIONBIO, &Value);
#else
fcntl(this->Descriptor, F_SETFL, 0);
#endif //WIN
return RetVal;
}
bool ClientListStruct::CompletePing(void)
{
if (!this->WaitingForPing) return false;
this->WaitingForPing = false;
this->PingRecvTime = time(NULL);
return true;
}
ClientListStruct::ClientListStruct(const int InDescriptor, const char *IP, const char *OriginalNick, const char *Ident)
: WaitingForPing(false), PingSentTime(0), PingRecvTime(time(NULL)), Descriptor(InDescriptor)
{ //PingRecvTime is initialized with a real time so that the server doesn't send pings instantly.
SubStrings.Copy(this->IP, IP, sizeof this->IP);
SubStrings.Copy(this->OriginalNick, OriginalNick, sizeof this->OriginalNick);
SubStrings.Copy(this->Ident, Ident, sizeof this->Ident);
}
ClientListStruct::ClientListStruct(void)
: WaitingForPing(false), PingSentTime(0), PingRecvTime(time(NULL)), Descriptor(0)
{
}
void ClientListStruct::SendNxCtlPrivmsg(const char *const String)
{
std::string Out = std::string(":" CONTROL_NICKNAME "!NEXUS@NEXUS PRIVMSG ") + IRCConfig.Nick + " :" + String;
if (!SubStrings.EndsWith("\r\n", Out.c_str()))
{ //SendLine() does the same thing, but we're aiming for consistency and safety.
Out += "\r\n";
}
this->SendLine(Out.c_str());
}
void ClientListStruct::SendLine(const char *const String)
{
std::string Out = String;
if (!SubStrings.EndsWith("\r\n", Out.c_str()))
{
Out += "\r\n";
}
this->WriteQueue.push(Out);
}
bool ClientListStruct::FlushSendBuffer(void)
{
if (this->WriteQueue.empty()) return false;
while (!this->WriteQueue.empty())
{
if (!this->WriteQueue_Pop()) return false;
}
return true;
}
bool ClientListStruct::WriteQueue_Pop(void)
{
if (this->WriteQueue.empty()) return false;
bool RetVal = false;
std::string Out = this->WriteQueue.front();
#ifdef WIN
u_long Value = 1;
ioctlsocket(this->Descriptor, FIONBIO, &Value);
#else
fcntl(this->Descriptor, F_SETFL, O_NONBLOCK); //Set nonblocking. Necessary for our single-threaded model.
#endif //WIN
try
{
Net::Write(this->Descriptor, Out.c_str(), Out.length());
}
catch (Net::Errors::BlockingError Err)
{
if (Err.BytesSentBeforeBlocking > 0)
{
std::string &Str = this->WriteQueue.front();
std::string New = Str;
Str = New.c_str() + Err.BytesSentBeforeBlocking;
}
goto End;
}
catch (Net::Errors::Any)
{ //We will probably get Net::Errors::BlockingError.
goto End;
}
RetVal = true;
this->WriteQueue.pop();
End:
#ifdef WIN
Value = 0;
ioctlsocket(this->Descriptor, FIONBIO, &Value);
#else
fcntl(this->Descriptor, F_SETFL, 0);
#endif //WIN
return RetVal;
}
| 27.836096
| 139
| 0.691631
|
Subsentient
|
764d3fec3b50869b29975839adf3de55ea856e79
| 3,491
|
cpp
|
C++
|
dp0.cpp
|
lordblendi/cpp-deklarativ-programozas-hf
|
85d875d9eb35f1dcc0275439f8284993b556143f
|
[
"MIT"
] | null | null | null |
dp0.cpp
|
lordblendi/cpp-deklarativ-programozas-hf
|
85d875d9eb35f1dcc0275439f8284993b556143f
|
[
"MIT"
] | null | null | null |
dp0.cpp
|
lordblendi/cpp-deklarativ-programozas-hf
|
85d875d9eb35f1dcc0275439f8284993b556143f
|
[
"MIT"
] | null | null | null |
//segédfgv length_help(L,N) = N+L hossza, N-ben tárolom az addigi elemek számát
int length_help(list l, int n){
if(nil == l) return n;
return length_help(tl(l), n+1);
}
//length(L) = L lista hossza
int list_length(list l){
return length_help(l, 0);
}
//insert_nth(L,N,E) L lista olyan másolata, amelyben az L lista n-edik és N+1-edik eleme közé be van szúrva az E elem (a lista számozása 0-tól kezdõdik)
list insert_nth(list l, int n, int e){
if(n==0) return cons(e, l);
return cons(hd(l), insert_nth(tl(l), n-1, e));
}
//number_to_base(n, b, l) az n számot visszaadja az l listában b számrendszerben
list number_to_base(int n, int b, list l){
if(n<b) return cons(n, l);
return number_to_base((n-n%b)/b, b, cons(n%b, l));
}
//number_to_base_ten(l,alap,szorzo,szam, i) az l listát visszadja számként 10-es számrendszerben. b a számrender, amiben a szám van, i hanyadik elemnél tartok, szorzo az aktuális szorzó (=hatványai az alapnak), szam pedig hogy mennyi az aktuális összeg
int number_to_base_ten(list l, int alap, int szorzo, int szam, int i){
if(i < 0) return szam;
return szam + number_to_base_ten(l, alap, szorzo*alap, nth(l, i)* szorzo, i-1);
}
//nth(l,n) visszadja az l lista n-edik elemét. a számozás 0-tól kezdõdik
int nth(list l, int n){
if(n==0) return hd(l);
return nth(tl(l), n-1);
}
//split(l,r,n) r-ben visszaad minden második számot az l listából. n értékétõl függõen ez lehetnek páros vagy páratlan sorszámú elem
list split(list l, list r, int n){
if(n > 1) return split(l, cons(nth(l,n),r),n-2);
return cons(nth(l,n), r);
}
//paratlan(l) visszaadja az L lista páratlan helyiértéken álló elemeit -> megfelelõ n értékkel meghívja a splitet
list paratlan(list l){
if((list_length(l) % 2) == 0) return split(l, nil, list_length(l)-2);
return split(l, nil, list_length(l)-1);
}
//paros(l) visszaadja az L lista páros helyiértéken álló elemeit -> megfelelõ n értékkel meghívja a splitet
list paros(list l){
if((list_length(l) % 2) == 0) return split(l, nil, list_length(l)-1);
return split(l, nil, list_length(l)-2);
}
//páratlan listába a páros lista elemeit megfordítva beleszúrjuk
list beszur(list paratlan, list paros){
return beszur_help(paratlan, paros, list_length(paros)-1, 1);
}
//beszur_help(paratlan, paros, n, i) segédfgv a beszúrhoz, beszúrja a paratlan lista minden 2. elemének a paros listát visszafelé. n és i tartják számon, hogy melyik listában hanyadik elemnél tartok
list beszur_help(list paratlan, list paros, int n, int i){
if(n < 0) return paratlan;
return beszur_help(insert_nth(paratlan, i, nth(paros,n)), paros, n-1, i+2);
}
/* osszekevert(S, A) == SK, ha SK az S szám A alapú összekevert
változata (S>0, A>1 egész számok).
Egy S szám A alapú összekevertjét úgy kapjuk meg, hogy az S számot felírjuk
az A alapú számrendszerben, a számjegyeit egy listával ábrázoljuk, a
listát a fentiek szerint átrendezzük, majd a kapott lista elemeit
egy A alapú szám jegyeinek tekintve elõállítjuk a keresett értéket.
ha a lista hossza <4, akkor felesleges cserélgetnünk, mert csak 1 párosodik szám van, és felesleges cserélgetni
*/
int osszekevert(const int S, const int A) {
if(list_length(number_to_base(S,A,nil))<4) return S;
return number_to_base_ten(beszur(paratlan(number_to_base(S,A,nil)), paros(number_to_base(S,A,nil))) , A,1,0,list_length(beszur(paratlan(number_to_base(S,A,nil)), paros(number_to_base(S,A,nil))))-1);
}
| 43.6375
| 254
| 0.708393
|
lordblendi
|
764f988d3b8a1339b595365a3abbb9929fee84b1
| 1,955
|
inl
|
C++
|
RTCLI.AOT/Internal/Managed.inl
|
Team-RTCLI/RTCLI.Runtime
|
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
|
[
"MIT"
] | 19
|
2020-10-21T02:54:39.000Z
|
2022-03-31T02:55:48.000Z
|
RTCLI.AOT/Internal/Managed.inl
|
Team-RTCLI/RTCLI.Runtime
|
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
|
[
"MIT"
] | null | null | null |
RTCLI.AOT/Internal/Managed.inl
|
Team-RTCLI/RTCLI.Runtime
|
3e888dca4401d7eb9b78aaf02d23b1281d8f0c2a
|
[
"MIT"
] | null | null | null |
namespace RTCLI
{
namespace System
{
// ******************* Managed<T> *************************//
template<typename T>
RTCLI_FORCEINLINE Managed<T>::operator const T&() const RTCLI_NOEXCEPT
{
if(!object)
{
return null;
}
return *static_cast<const T*>(object);
}
template<typename T>
RTCLI_FORCEINLINE Managed<T>::operator T&() RTCLI_NOEXCEPT
{
if(!object)
{
return null;
}
return *static_cast<T*>(object);
}
template<typename T>
RTCLI_FORCEINLINE Managed<T>::Managed() RTCLI_NOEXCEPT
:object(const_cast<System::Object*>(&RTCLI::nullObject))
{
}
template<typename T>
RTCLI_FORCEINLINE Managed<T>::Managed(nullref_t null) RTCLI_NOEXCEPT
:object(const_cast<System::Object*>(&RTCLI::nullObject))
{
}
template<typename T>
RTCLI_FORCEINLINE Managed<T>::Managed(const System::Object& object_) RTCLI_NOEXCEPT
{
if (object_.isNull()) {
object = const_cast<System::Object*>(&RTCLI::nullObject);
}
else
{
object = const_cast<System::Object*>(&object_);
}
}
template<typename T>
RTCLI_FORCEINLINE T& Managed<T>::Get() RTCLI_NOEXCEPT
{
return *static_cast<T*>(object);
}
template<typename T>
RTCLI_FORCEINLINE const T& Managed<T>::Get() const RTCLI_NOEXCEPT
{
return *static_cast<const T*>(object);
}
template<typename T>
RTCLI_FORCEINLINE Managed<T>& Managed<T>::operator=(const System::Object& object_) RTCLI_NOEXCEPT
{
if(this->object == &object_)
{
return *this;
}
if (object_.isNull()) {
object = const_cast<System::Object*>(&RTCLI::nullObject);
}
else
{
object = const_cast<System::Object*>(&object_);
}
return *this;
}
}
}
| 24.4375
| 101
| 0.557545
|
Team-RTCLI
|
7653a2d7c669c259f2df23c413a6d5a80fe46dde
| 862
|
cpp
|
C++
|
src/core/resumable.cpp
|
Anomander/xi
|
0340675310c41d659762fc3eea48c84ff13b95db
|
[
"MIT"
] | null | null | null |
src/core/resumable.cpp
|
Anomander/xi
|
0340675310c41d659762fc3eea48c84ff13b95db
|
[
"MIT"
] | null | null | null |
src/core/resumable.cpp
|
Anomander/xi
|
0340675310c41d659762fc3eea48c84ff13b95db
|
[
"MIT"
] | null | null | null |
#include "xi/core/resumable.h"
#include "xi/core/abstract_worker.h"
namespace xi {
namespace core {
namespace v2 {
thread_local resumable_stat RESUMABLE_STAT;
}
void resumable::attach_executor(abstract_worker* e) {
_worker = e;
}
void resumable::detach_executor(abstract_worker* e) {
assert(_worker == e);
_worker = nullptr;
}
void resumable::unblock() {
sleep_hook.unlink();
ready_hook.unlink();
_worker->schedule(this);
}
void resumable::block() {
yield(blocked);
}
steady_clock::time_point resumable::wakeup_time() {
return _wakeup_time;
}
void resumable::wakeup_time(steady_clock::time_point when) {
_wakeup_time = when;
}
void resumable::sleep_for(nanoseconds ns) {
assert(_worker != nullptr);
ready_hook.unlink();
_worker->sleep_for(this, ns);
block();
}
}
}
| 18.73913
| 62
| 0.668213
|
Anomander
|
76578b47ce79e8d46b82ba4c2a9ca7a80b451c9b
| 555
|
cpp
|
C++
|
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
|
Horizon-Blue/playground
|
4bd42bfcec60b8e89e127f4784c99f6ba669d359
|
[
"MIT"
] | 2
|
2016-08-31T19:13:24.000Z
|
2017-02-18T18:48:31.000Z
|
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
|
Horizon-Blue/playground
|
4bd42bfcec60b8e89e127f4784c99f6ba669d359
|
[
"MIT"
] | 1
|
2018-12-10T16:32:26.000Z
|
2018-12-27T19:50:48.000Z
|
Solutions-to-OJs/POJ/2000-2999/2719_Faulty_Odometer.cpp
|
Horizon-Blue/playground
|
4bd42bfcec60b8e89e127f4784c99f6ba669d359
|
[
"MIT"
] | null | null | null |
// Xiaoyan Wang 9/8/2016
#include <iostream>
// #include <vector>
using namespace std;
// arry stores 0, 9^1, 9^2 ... 9^8
int arry[] = {1, 9, 81, 729, 6561, 59049, 531441, 4782969, 43046721/*, 387420489*/};
// input range: 1 to 10^10
int main() {
ios::sync_with_stdio(false);
int n;
while(cin >> n && n) {
int result = 0;
int digit;
for(int i = 0, div = 1; i < 10; ++i, div *= 10) {
if((digit = (n % (div * 10)) / div) > 4)
--digit;
result += digit * arry[i];
}
cout << n << ": " << result << "\n";
}
cout << flush;
return 0;
}
| 22.2
| 84
| 0.536937
|
Horizon-Blue
|
765928c98b462e252e72220293d6e1eb924600d4
| 54
|
hpp
|
C++
|
src/boost_geometry_formulas_thomas_inverse.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_geometry_formulas_thomas_inverse.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_geometry_formulas_thomas_inverse.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/geometry/formulas/thomas_inverse.hpp>
| 27
| 53
| 0.833333
|
miathedev
|
7659c3421dbb45aa88d737e948f1bad88733d706
| 4,001
|
cpp
|
C++
|
ycsbWorkloadCBench.cpp
|
pfent/exchangeableTransports
|
a17ddcf99eba16b401df8f0865c1264e11c15c85
|
[
"MIT"
] | 32
|
2018-12-14T16:54:11.000Z
|
2022-02-28T13:07:17.000Z
|
ycsbWorkloadCBench.cpp
|
pfent/exchangeableTransports
|
a17ddcf99eba16b401df8f0865c1264e11c15c85
|
[
"MIT"
] | null | null | null |
ycsbWorkloadCBench.cpp
|
pfent/exchangeableTransports
|
a17ddcf99eba16b401df8f0865c1264e11c15c85
|
[
"MIT"
] | 5
|
2020-05-25T07:05:29.000Z
|
2022-03-05T02:59:38.000Z
|
#include <include/DomainSocketsTransport.h>
#include <include/TcpTransport.h>
#include <include/SharedMemoryTransport.h>
#include "include/RdmaTransport.h"
#include <array>
#include <vector>
#include <thread>
#include "util/bench.h"
#include "util/ycsb.h"
#include "util/Random32.h"
#include "util/doNotOptimize.h"
using namespace l5::transport;
static constexpr uint16_t port = 1234;
static std::string_view ip = "127.0.0.1";
void doRunNoCommunication() {
const auto database = YcsbDatabase();
auto rand = Random32();
const auto lookupKeys = generateZipfLookupKeys(ycsb_tx_count * 10);
std::array<char, ycsb_field_length> data{};
std::cout << "none, ";
bench(ycsb_tx_count * 10, [&] {
for (auto lookupKey : lookupKeys) {
const auto field = rand.next() % ycsb_field_count;
database.lookup(lookupKey, field, data.begin());
DoNotOptimize(data);
}
});
}
template<class Server, class Client>
void doRun(bool isClient, std::string connection) {
struct ReadMessage {
YcsbKey lookupKey;
size_t field;
};
struct ReadResponse {
std::array<char, ycsb_field_length> data;
};
if (isClient) {
auto client = Client();
for (int i = 0;; ++i) {
try {
client.connect(connection);
break;
} catch (...) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
if (i > 1000) throw;
}
}
auto rand = Random32();
const auto lookupKeys = generateZipfLookupKeys(ycsb_tx_count);
auto response = ReadResponse{};
for (const auto lookupKey: lookupKeys) {
const auto field = rand.next() % ycsb_field_count;
const auto message = ReadMessage{lookupKey, field};
client.write(message);
client.read(response);
DoNotOptimize(response);
}
} else { // server
auto server = Server(connection);
const auto database = YcsbDatabase();
server.accept();
bench(ycsb_tx_count, [&] {
for (size_t i = 0; i < ycsb_tx_count; ++i) {
auto message = ReadMessage{};
server.read(message);
auto&[lookupKey, field] = message;
auto response = ReadResponse{};
database.lookup(lookupKey, field, reinterpret_cast<char*>(&response));
server.write(response);
}
});
}
}
int main(int argc, char **argv) {
if (argc < 3) {
std::cout << "Usage: " << argv[0] << " <client / server> <[DS|SHM|TCP|RDMA]> <(IP, optional) 127.0.0.1>" << std::endl;
return -1;
}
const auto isClient = std::string_view(argv[1]) == "client";
const auto transportProtocol = std::string_view(argv[2]);
if (argc >= 3) ip = argv[2];
std::string connectionString;
if (isClient) {
connectionString = std::string(ip) + ":" + std::to_string(port);
} else {
connectionString = std::to_string(port);
}
if (!isClient) std::cout << "connection, transactions, time, msgps, user, system, total\n";
if (!isClient) doRunNoCommunication();
if (transportProtocol == "DS") {
if (!isClient) std::cout << "domainSocket, ";
doRun<DomainSocketsTransportServer, DomainSocketsTransportClient>(isClient, "/tmp/testSocket");
} else if (transportProtocol == "SHM") {
if (!isClient) std::cout << "shared memory, ";
doRun<SharedMemoryTransportServer<>, SharedMemoryTransportClient<>>(isClient, "/tmp/testSocket");
} else if (transportProtocol == "TCP") {
if (!isClient) std::cout << "tcp, ";
doRun<TcpTransportServer, TcpTransportClient>(isClient, connectionString);
} else if (transportProtocol == "RDMA") {
if (!isClient) std::cout << "rdma, ";
doRun<RdmaTransportServer<>, RdmaTransportClient<>>(isClient, connectionString);
}
}
| 34.196581
| 126
| 0.593852
|
pfent
|
766150558a10806e22a6e4d1dc3931ce9f259468
| 7,410
|
cpp
|
C++
|
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
|
cibercitizen1/zmqHelper
|
8fbfe33ddb2642657ed565ffbb157e174035a52d
|
[
"MIT"
] | 5
|
2015-01-02T15:54:39.000Z
|
2021-01-12T18:00:29.000Z
|
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
|
cibercitizen1/zmqHelper
|
8fbfe33ddb2642657ed565ffbb157e174035a52d
|
[
"MIT"
] | null | null | null |
examples/06-multithreaded-ROUTERserver-doneRight/server.cpp
|
cibercitizen1/zmqHelper
|
8fbfe33ddb2642657ed565ffbb157e174035a52d
|
[
"MIT"
] | 2
|
2017-09-01T19:54:50.000Z
|
2017-11-09T14:34:11.000Z
|
// ---------------------------------------------------------------
// server.cpp
//
// multi-threaded router server done right !
//
//
// -> ROUTER socket -> main-thread -> in-proc socket -> delegate to worker
//
/*
* ON MULTITHREADING WITH ZeroMQ
*
* Remember:
*
* Do not use or close sockets except in the thread that created them.
*
* Don't share ZeroMQ sockets between threads.
* ZeroMQ sockets are not threadsafe.
*
* Isolate data privately within its thread and never share data
* in multiple threads. The only exception to this are ZeroMQ contexts,
* which are threadsafe.
*
* Stay away from the classic concurrency mechanisms like as mutexes,
* critical sections, semaphores, etc. These are an anti-pattern
* in ZeroMQ applications.
*
* Create one ZeroMQ context at the start of your process,
* and pass that to all threads that you want to connect via inproc sockets.
*
*
*
* If you need to start more than one proxy in an application,
* for example, you will want to run each in their own thread.
* It is easy to make the error of creating the proxy frontend
* and backend sockets in one thread, and then passing the sockets
* to the proxy in another thread. This may appear to work at first
* but will fail randomly in real use.
*
* Some widely used models, despite being the basis for entire
* industries, are fundamentally broken, and shared state concurrency
* is one of them. Code that wants to scale without limit does it
* like the Internet does, by sending messages and sharing nothing
*
*/
/*
*
* ON CONTEXTS
*
* ZeroMQ applications always start by creating a context,
* and then using that for creating sockets.
* In C, it's the zmq_ctx_new() call.
* You should create and use exactly one context in your process.
* Technically, the context is the container for all sockets
* in a single process, and acts as the transport for inproc sockets,
* which are the fastest way to connect threads in one process.
* If at runtime a process has two contexts,
* these are like separate ZeroMQ instances.
* If that's explicitly what you want, OK, but otherwise remember:
*
* Do one zmq_ctx_new() at the start of your main line code,
* and one zmq_ctx_destroy() at the end.
*/
// ---------------------------------------------------------------
#include <iostream>
#include <future>
#include <thread>
#include <string>
#include <vector>
#include <stdlib.h>
#include "../../zmqHelper.hpp"
// ---------------------------------------------------------------
// ---------------------------------------------------------------
const std::string PORT_NUMBER = "5580";
// ---------------------------------------------------------------
// ---------------------------------------------------------------
template <typename ITERABLE>
void showLines (const std::string & msg, ITERABLE & it) {
std::cout << msg << ": message: |";
for (auto item : it) {
std::cout << item << "|";
}
std::cout << "\n";
}
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// ---------------------------------------------------------------
// ---------------------------------------------------------------
class Worker {
private:
//
//
//
zmq::context_t & sharedContext;
//
// previous version: the thread in constructor creates
// the socket but it is used by the thread in main
//
// zmqHelper::SocketAdaptor< ZMQ_REP > internalRepSocket;
//
//
//
std::thread * theThread = nullptr;
// -------------------------------------------------------------
// -------------------------------------------------------------
void main (){
//
// a new thread executes this
//
//
// the socket is created and use here
//
// remember RAII (resourse adquisition is initialization)
//
zmqHelper::SocketAdaptor< ZMQ_REP > internalRepSocket {sharedContext};
//
//
//
internalRepSocket.connect ("inproc://innerChannel");
//
//
//
std::cout << " ***** worker main " << this
<< " starts **** \n";
//
//
//
std::vector<std::string> lines;
while ( internalRepSocket.receiveText (lines) ) {
std::cout << " ** worker: " << this;
showLines (" got ", lines);
//
// do some work !
//
sleep (1);
//
// reply
//
internalRepSocket.sendText ({"echo of: " + lines[0] + " " + lines[1]});
} // while
} // ()
public:
// -------------------------------------------------------------
// -------------------------------------------------------------
Worker ( zmq::context_t & sharedContext_) :
sharedContext {sharedContext_}
{
//
//
//
theThread = new std::thread (&Worker::main, this);
}
// -------------------------------------------------------------
// -------------------------------------------------------------
~Worker ( ) {
std::cerr << " worker destructor \n";
if (theThread == nullptr) {
return;
}
theThread->join ();
delete (theThread);
theThread = nullptr;
}
};
// ---------------------------------------------------------------
// ---------------------------------------------------------------
int main () {
std::cout << " main stars \n";
//
// create internal socket to talk to workers
//
zmqHelper::SocketAdaptor< ZMQ_DEALER > innerDealerSocket;
innerDealerSocket.bind ("inproc://innerChannel");
//
// 4 workers, you can experience with the
// number of workers, timing run.client
//
Worker wk1 {innerDealerSocket.getContext()};
Worker wk2 {innerDealerSocket.getContext()};
Worker wk3 {innerDealerSocket.getContext()};
Worker wk4 {innerDealerSocket.getContext()};
std::cerr << "main(): workers created\n";
//
// create external socket to talk with clients
//
zmqHelper::SocketAdaptor< ZMQ_ROUTER > outerRouterSocket;
outerRouterSocket.bind ("tcp://*:" + PORT_NUMBER);
//
// for ever ...
//
while (true) {
std::cout << "\n\n while(true): waiting for clients/worker ... \n";
std::vector<std::string> lines;
//
// wait (blocking poll) for data in either of the sockets
//
std::vector< zmqHelper::ZmqSocketType * > list
= { outerRouterSocket.getZmqSocket(), innerDealerSocket.getZmqSocket() };
zmqHelper::ZmqSocketType * who = zmqHelper::waitForDataInSockets ( list );
//
// there is data
//
if ( who == outerRouterSocket.getZmqSocket() ) {
//
// from client
//
if ( outerRouterSocket.receiveText (lines) ) {
std::cout << " server: client -> data -> worker \n";
//
// delegate to worker
//
innerDealerSocket.sendText( lines );
} else {
std::cout << " outer socket: awoken for nothing ?????????????????\n";
}
}
else if ( who == innerDealerSocket.getZmqSocket() ) {
//
// reply from worker
//
if ( innerDealerSocket.receiveText (lines) ) {
std::cout << " server: client <- data <- worker \n";
//
// answer the client
//
outerRouterSocket.sendText( lines );
} else {
std::cout << " inner socket: awoken for nothing ?????????????????\n";
}
} else {
std::cout << " ****** server: error in polling? \n";
}
} // while
} // main ()
| 26.183746
| 82
| 0.518758
|
cibercitizen1
|
766ef3a32b2fe7e6c2ca3a1dda0abc133df01a2a
| 3,639
|
hpp
|
C++
|
Includes/Core/CUDA/CUDAStdArray-Impl.hpp
|
ADMTec/CubbyFlow
|
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
|
[
"MIT"
] | 216
|
2017-01-25T04:34:30.000Z
|
2021-07-15T12:36:06.000Z
|
Includes/Core/CUDA/CUDAStdArray-Impl.hpp
|
ADMTec/CubbyFlow
|
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
|
[
"MIT"
] | 323
|
2017-01-26T13:53:13.000Z
|
2021-07-14T16:03:38.000Z
|
Includes/Core/CUDA/CUDAStdArray-Impl.hpp
|
ADMTec/CubbyFlow
|
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
|
[
"MIT"
] | 33
|
2017-01-25T05:05:49.000Z
|
2021-06-17T17:30:56.000Z
|
// This code is based on Jet framework.
// Copyright (c) 2018 Doyub Kim
// CubbyFlow is voxel-based fluid simulation engine for computer games.
// Copyright (c) 2020 CubbyFlow Team
// Core Part: Chris Ohk, Junwoo Hwang, Jihong Sin, Seungwoo Yoo
// AI Part: Dongheon Cho, Minseo Kim
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#ifndef CUBBYFLOW_CUDA_STD_ARRAY_IMPL_HPP
#define CUBBYFLOW_CUDA_STD_ARRAY_IMPL_HPP
#ifdef CUBBYFLOW_USE_CUDA
namespace CubbyFlow
{
template <typename T, size_t N>
CUDAStdArray<T, N>::CUDAStdArray()
{
Fill(T{});
}
template <typename T, size_t N>
template <typename... Args>
CUDAStdArray<T, N>::CUDAStdArray(ConstReference first, Args... rest)
{
static_assert(
sizeof...(Args) == N - 1,
"Number of arguments should be equal to the size of the vector.");
SetAt(0, first, rest...);
}
template <typename T, size_t N>
CUDAStdArray<T, N>::CUDAStdArray(const std::array<T, N>& other)
{
for (size_t i = 0; i < N; ++i)
{
m_elements[i] = other[i];
}
}
template <typename T, size_t N>
CUDAStdArray<T, N>::CUDAStdArray(const Vector<T, N>& other)
{
for (size_t i = 0; i < N; ++i)
{
m_elements[i] = other[i];
}
}
template <typename T, size_t N>
CUDAStdArray<T, N>::CUDAStdArray(const CUDAStdArray& other)
{
for (size_t i = 0; i < N; ++i)
{
m_elements[i] = other[i];
}
}
template <typename T, size_t N>
CUDAStdArray<T, N>::CUDAStdArray(CUDAStdArray&& other) noexcept
{
for (size_t i = 0; i < N; ++i)
{
m_elements[i] = std::move(other[i]);
}
}
template <typename T, size_t N>
CUDAStdArray<T, N>& CUDAStdArray<T, N>::operator=(const CUDAStdArray& other)
{
for (size_t i = 0; i < N; ++i)
{
m_elements[i] = other[i];
}
return *this;
}
template <typename T, size_t N>
CUDAStdArray<T, N>& CUDAStdArray<T, N>::operator=(CUDAStdArray&& other) noexcept
{
for (size_t i = 0; i < N; ++i)
{
m_elements[i] = std::move(other[i]);
}
return *this;
}
template <typename T, size_t N>
void CUDAStdArray<T, N>::Fill(ConstReference val)
{
for (size_t i = 0; i < N; ++i)
{
m_elements[i] = val;
}
}
template <typename T, size_t N>
CUBBYFLOW_CUDA_HOST Vector<T, N> CUDAStdArray<T, N>::ToVector() const
{
Vector<T, N> vec;
for (size_t i = 0; i < N; ++i)
{
vec[i] = m_elements[i];
}
return vec;
}
template <typename T, size_t N>
typename CUDAStdArray<T, N>::Reference CUDAStdArray<T, N>::operator[](size_t i)
{
return m_elements[i];
}
template <typename T, size_t N>
typename CUDAStdArray<T, N>::ConstReference CUDAStdArray<T, N>::operator[](
size_t i) const
{
return m_elements[i];
}
template <typename T, size_t N>
bool CUDAStdArray<T, N>::operator==(const CUDAStdArray& other) const
{
for (size_t i = 0; i < N; ++i)
{
if (m_elements[i] != other.m_elements[i])
{
return false;
}
}
return true;
}
template <typename T, size_t N>
bool CUDAStdArray<T, N>::operator!=(const CUDAStdArray& other) const
{
return !(*this == other);
}
template <typename T, size_t N>
template <typename... Args>
void CUDAStdArray<T, N>::SetAt(size_t i, ConstReference first, Args... rest)
{
m_elements[i] = first;
SetAt(i + 1, rest...);
}
template <typename T, size_t N>
template <typename... Args>
void CUDAStdArray<T, N>::SetAt(size_t i, ConstReference first)
{
m_elements[i] = first;
}
} // namespace CubbyFlow
#endif
#endif
| 22.054545
| 80
| 0.636439
|
ADMTec
|
767284f4e7d34ff0b4e33313398b849527528b74
| 1,504
|
cpp
|
C++
|
LoveBabbar/12_graph/17_given_sorted_alien_dictionary_find_the_order_of_character.cpp
|
Next-Gen-UI/Code-Dynamics
|
a9b9d5e3f27e870b3e030c75a1060d88292de01c
|
[
"MIT"
] | null | null | null |
LoveBabbar/12_graph/17_given_sorted_alien_dictionary_find_the_order_of_character.cpp
|
Next-Gen-UI/Code-Dynamics
|
a9b9d5e3f27e870b3e030c75a1060d88292de01c
|
[
"MIT"
] | null | null | null |
LoveBabbar/12_graph/17_given_sorted_alien_dictionary_find_the_order_of_character.cpp
|
Next-Gen-UI/Code-Dynamics
|
a9b9d5e3f27e870b3e030c75a1060d88292de01c
|
[
"MIT"
] | null | null | null |
/*
link: https://practice.geeksforgeeks.org/problems/alien-dictionary/1
sol: https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/
video: https://youtu.be/wMMwRK-w0r4
steps:
1. form graph from given words by comparing (as given they are sorted)
2. so form graph such that word from smaller to larger forms edge
3. find topological sort
that's it
*/
// ----------------------------------------------------------------------------------------------------------------------- //
/*
TC: O(N + K) + O(N + K), first for forming graph and second for dfs
Note that there would be K vertices and at-most (N-1) edges in the graph.
*/
void dfs(int curr, string& ans, vector<int>& vis, vector<vector<int>>& g) {
vis[curr] = 1;
for (auto i : g[curr]) {
if (!vis[i]) {
dfs(i, ans, vis, g);
}
}
ans += (curr + 'a');
}
string findOrder(string dict[], int N, int K) {
vector<vector<int>> g(K);
for (int i = 0;i < N - 1;i++) {
string a = dict[i];
string b = dict[i + 1];
for (int j = 0;j < min(a.size(), b.size());j++) {
if (a[j] != b[j]) {
g[a[j] - 'a'].push_back(b[j] - 'a');
break;
}
}
}
vector<int> vis(K, 0);
string ans = "";
for (int i = 0;i < K;i++) {
if (!vis[i]) {
dfs(i, ans, vis, g);
}
}
reverse(ans.begin(), ans.end());
return ans;
}
| 25.066667
| 125
| 0.470745
|
Next-Gen-UI
|
7673c1cf27f096c1ee32b3c97b316fb1166fc777
| 109
|
hpp
|
C++
|
PlanetaMatchMakerServer/source/server/server_constants.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 6
|
2019-08-15T09:48:55.000Z
|
2021-07-25T14:40:59.000Z
|
PlanetaMatchMakerServer/source/server/server_constants.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 43
|
2019-12-25T14:54:52.000Z
|
2022-02-24T17:22:48.000Z
|
PlanetaMatchMakerServer/source/server/server_constants.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 2
|
2020-05-06T20:14:44.000Z
|
2020-06-02T21:21:10.000Z
|
#pragma once
#include "data/data_constants.hpp"
namespace pgl {
constexpr version_type api_version = 0;
}
| 13.625
| 40
| 0.761468
|
InstytutXR
|
767841bcaf8190d65c1cdf5653bd80edfbd31f3a
| 11,933
|
hpp
|
C++
|
sol/function_types.hpp
|
SuperV1234/sol2
|
76b73bdfab4475933c42e715fd98737a4699794a
|
[
"MIT"
] | null | null | null |
sol/function_types.hpp
|
SuperV1234/sol2
|
76b73bdfab4475933c42e715fd98737a4699794a
|
[
"MIT"
] | null | null | null |
sol/function_types.hpp
|
SuperV1234/sol2
|
76b73bdfab4475933c42e715fd98737a4699794a
|
[
"MIT"
] | 1
|
2021-05-02T15:57:13.000Z
|
2021-05-02T15:57:13.000Z
|
// The MIT License (MIT)
// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors
// 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.
#ifndef SOL_FUNCTION_TYPES_HPP
#define SOL_FUNCTION_TYPES_HPP
#include "function_types_core.hpp"
#include "function_types_templated.hpp"
#include "function_types_basic.hpp"
#include "function_types_member.hpp"
#include "function_types_overloaded.hpp"
#include "resolve.hpp"
#include "call.hpp"
namespace sol {
template <typename Sig, typename... Ps>
struct function_arguments {
std::tuple<Ps...> params;
template <typename... Args>
function_arguments(Args&&... args) : params(std::forward<Args>(args)...) {}
};
template <typename Sig = function_sig<>, typename... Args>
function_arguments<Sig, Args...> function_args(Args&&... args) {
return function_arguments<Sig, Args...>(std::forward<Args>(args)...);
}
namespace stack {
template<typename... Sigs>
struct pusher<function_sig<Sigs...>> {
template <typename... Sig, typename Fx, typename... Args>
static void select_convertible(std::false_type, types<Sig...>, lua_State* L, Fx&& fx, Args&&... args) {
typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx;
std::unique_ptr<function_detail::base_function> sptr = std::make_unique<function_detail::functor_function<clean_fx>>(std::forward<Fx>(fx), std::forward<Args>(args)...);
set_fx(L, std::move(sptr));
}
template <typename R, typename... A, typename Fx, typename... Args>
static void select_convertible(std::true_type, types<R(A...)>, lua_State* L, Fx&& fx, Args&&... args) {
using fx_ptr_t = R(*)(A...);
fx_ptr_t fxptr = detail::unwrap(std::forward<Fx>(fx));
select_function(std::true_type(), L, fxptr, std::forward<Args>(args)...);
}
template <typename R, typename... A, typename Fx, typename... Args>
static void select_convertible(types<R(A...)> t, lua_State* L, Fx&& fx, Args&&... args) {
typedef std::decay_t<meta::unwrapped_t<meta::unqualified_t<Fx>>> raw_fx_t;
typedef R(*fx_ptr_t)(A...);
typedef std::is_convertible<raw_fx_t, fx_ptr_t> is_convertible;
select_convertible(is_convertible(), t, L, std::forward<Fx>(fx), std::forward<Args>(args)...);
}
template <typename Fx, typename... Args>
static void select_convertible(types<>, lua_State* L, Fx&& fx, Args&&... args) {
typedef meta::function_signature_t<meta::unwrapped_t<meta::unqualified_t<Fx>>> Sig;
select_convertible(types<Sig>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...);
}
template <typename Fx, typename T, typename... Args>
static void select_reference_member_variable(std::false_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) {
typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx;
std::unique_ptr<function_detail::base_function> sptr = std::make_unique<function_detail::member_variable<meta::unqualified_t<T>, clean_fx>>(std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...);
set_fx(L, std::move(sptr));
}
template <typename Fx, typename T, typename... Args>
static void select_reference_member_variable(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) {
typedef std::decay_t<Fx> dFx;
dFx memfxptr(std::forward<Fx>(fx));
auto userptr = detail::ptr(std::forward<T>(obj), std::forward<Args>(args)...);
lua_CFunction freefunc = &function_detail::upvalue_member_variable<std::decay_t<decltype(*userptr)>, meta::unqualified_t<Fx>>::call;
int upvalues = stack::stack_detail::push_as_upvalues(L, memfxptr);
upvalues += stack::push(L, lightuserdata_value(static_cast<void*>(userptr)));
stack::push(L, c_closure(freefunc, upvalues));
}
template <typename Fx, typename... Args>
static void select_member_variable(std::false_type, lua_State* L, Fx&& fx, Args&&... args) {
select_convertible(types<Sigs...>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...);
}
template <typename Fx, typename T, typename... Args>
static void select_member_variable(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) {
typedef meta::boolean<meta::is_specialization_of<std::reference_wrapper, meta::unqualified_t<T>>::value || std::is_pointer<T>::value> is_reference;
select_reference_member_variable(is_reference(), L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...);
}
template <typename Fx>
static void select_member_variable(std::true_type, lua_State* L, Fx&& fx) {
typedef typename meta::bind_traits<meta::unqualified_t<Fx>>::object_type C;
lua_CFunction freefunc = &function_detail::upvalue_this_member_variable<C, Fx>::call;
int upvalues = stack::stack_detail::push_as_upvalues(L, fx);
stack::push(L, c_closure(freefunc, upvalues));
}
template <typename Fx, typename T, typename... Args>
static void select_reference_member_function(std::false_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) {
typedef std::remove_pointer_t<std::decay_t<Fx>> clean_fx;
std::unique_ptr<function_detail::base_function> sptr = std::make_unique<function_detail::member_function<meta::unwrapped_t<meta::unqualified_t<T>>, clean_fx>>(std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...);
set_fx(L, std::move(sptr));
}
template <typename Fx, typename T, typename... Args>
static void select_reference_member_function(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) {
typedef std::decay_t<Fx> dFx;
dFx memfxptr(std::forward<Fx>(fx));
auto userptr = detail::ptr(std::forward<T>(obj), std::forward<Args>(args)...);
lua_CFunction freefunc = &function_detail::upvalue_member_function<std::decay_t<decltype(*userptr)>, meta::unqualified_t<Fx>>::call;
int upvalues = stack::stack_detail::push_as_upvalues(L, memfxptr);
upvalues += stack::push(L, lightuserdata_value(static_cast<void*>(userptr)));
stack::push(L, c_closure(freefunc, upvalues));
}
template <typename Fx, typename... Args>
static void select_member_function(std::false_type, lua_State* L, Fx&& fx, Args&&... args) {
select_member_variable(std::is_member_object_pointer<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...);
}
template <typename Fx, typename T, typename... Args>
static void select_member_function(std::true_type, lua_State* L, Fx&& fx, T&& obj, Args&&... args) {
typedef meta::boolean<meta::is_specialization_of<std::reference_wrapper, meta::unqualified_t<T>>::value || std::is_pointer<T>::value> is_reference;
select_reference_member_function(is_reference(), L, std::forward<Fx>(fx), std::forward<T>(obj), std::forward<Args>(args)...);
}
template <typename Fx>
static void select_member_function(std::true_type, lua_State* L, Fx&& fx) {
typedef typename meta::bind_traits<meta::unqualified_t<Fx>>::object_type C;
lua_CFunction freefunc = &function_detail::upvalue_this_member_function<C, Fx>::call;
int upvalues = stack::stack_detail::push_as_upvalues(L, fx);
stack::push(L, c_closure(freefunc, upvalues));
}
template <typename Fx, typename... Args>
static void select_function(std::false_type, lua_State* L, Fx&& fx, Args&&... args) {
select_member_function(std::is_member_function_pointer<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...);
}
template <typename Fx, typename... Args>
static void select_function(std::true_type, lua_State* L, Fx&& fx, Args&&... args) {
std::decay_t<Fx> target(std::forward<Fx>(fx), std::forward<Args>(args)...);
lua_CFunction freefunc = &function_detail::upvalue_free_function<Fx>::call;
int upvalues = stack::stack_detail::push_as_upvalues(L, target);
stack::push(L, c_closure(freefunc, upvalues));
}
static void select_function(std::true_type, lua_State* L, lua_CFunction f) {
stack::push(L, f);
}
template <typename Fx, typename... Args>
static void select(lua_State* L, Fx&& fx, Args&&... args) {
select_function(std::is_function<meta::unqualified_t<Fx>>(), L, std::forward<Fx>(fx), std::forward<Args>(args)...);
}
static void set_fx(lua_State* L, std::unique_ptr<function_detail::base_function> luafunc) {
function_detail::base_function* target = luafunc.release();
void* targetdata = static_cast<void*>(target);
lua_CFunction freefunc = function_detail::call;
stack::push(L, userdata_value(targetdata));
function_detail::free_function_cleanup(L);
lua_setmetatable(L, -2);
stack::push(L, c_closure(freefunc, 1));
}
template<typename... Args>
static int push(lua_State* L, Args&&... args) {
// Set will always place one thing (function) on the stack
select(L, std::forward<Args>(args)...);
return 1;
}
};
template<typename T, typename... Args>
struct pusher<function_arguments<T, Args...>> {
template <std::size_t... I, typename FP>
static int push_func(std::index_sequence<I...>, lua_State* L, FP&& fp) {
return stack::push<T>(L, detail::forward_get<I>(fp.params)...);
}
template <typename FP>
static int push(lua_State* L, FP&& fp) {
return push_func(std::make_index_sequence<sizeof...(Args)>(), L, std::forward<FP>(fp));
}
};
template<typename Signature>
struct pusher<std::function<Signature>> {
static int push(lua_State* L, std::function<Signature> fx) {
return pusher<function_sig<Signature>>{}.push(L, std::move(fx));
}
};
template<typename Signature>
struct pusher<Signature, std::enable_if_t<std::is_member_pointer<Signature>::value>> {
template <typename F>
static int push(lua_State* L, F&& f) {
return pusher<function_sig<>>{}.push(L, std::forward<F>(f));
}
};
template<typename Signature>
struct pusher<Signature, std::enable_if_t<meta::all<std::is_function<Signature>, meta::neg<std::is_same<Signature, lua_CFunction>>, meta::neg<std::is_same<Signature, std::remove_pointer_t<lua_CFunction>>>>::value>> {
template <typename F>
static int push(lua_State* L, F&& f) {
return pusher<function_sig<>>{}.push(L, std::forward<F>(f));
}
};
template<typename... Functions>
struct pusher<overload_set<Functions...>> {
static int push(lua_State* L, overload_set<Functions...>&& set) {
pusher<function_sig<>>{}.set_fx(L, std::make_unique<function_detail::overloaded_function<Functions...>>(std::move(set.set)));
return 1;
}
static int push(lua_State* L, const overload_set<Functions...>& set) {
pusher<function_sig<>>{}.set_fx(L, std::make_unique<function_detail::overloaded_function<Functions...>>(set.set));
return 1;
}
};
} // stack
} // sol
#endif // SOL_FUNCTION_TYPES_HPP
| 48.116935
| 237
| 0.684405
|
SuperV1234
|
76809ff92dee2935f5ee84fbd564304130ac376c
| 5,453
|
cc
|
C++
|
test/nosync/ppoll-based-event-loop-test.cc
|
nokia/libNoSync
|
af0f0e5b738feac8c42c357c9dbdf3dc7e541a76
|
[
"BSD-3-Clause"
] | 2
|
2018-04-28T18:29:08.000Z
|
2018-07-03T08:16:34.000Z
|
test/nosync/ppoll-based-event-loop-test.cc
|
nokia/libNoSync
|
af0f0e5b738feac8c42c357c9dbdf3dc7e541a76
|
[
"BSD-3-Clause"
] | null | null | null |
test/nosync/ppoll-based-event-loop-test.cc
|
nokia/libNoSync
|
af0f0e5b738feac8c42c357c9dbdf3dc7e541a76
|
[
"BSD-3-Clause"
] | 1
|
2018-04-27T07:53:16.000Z
|
2018-04-27T07:53:16.000Z
|
// This file is part of libnosync library. See LICENSE file for license details.
#include <algorithm>
#include <chrono>
#include <fcntl.h>
#include <functional>
#include <gtest/gtest.h>
#include <memory>
#include <nosync/ppoll-based-event-loop.h>
#include <nosync/type-utils.h>
#include <system_error>
#include <vector>
namespace ch = std::chrono;
using namespace std::chrono_literals;
using namespace std::string_literals;
using nosync::activity_handle;
using nosync::eclock;
using nosync::fd_watch_mode;
using nosync::make_copy;
using nosync::make_ppoll_based_event_loop;
using std::errc;
using std::function;
using std::make_error_code;
using std::unique_ptr;
using std::vector;
namespace
{
constexpr auto small_time_increment = 1ns;
}
TEST(NosyncPpollBasedEventLoop, TestSimpleTask)
{
auto evloop = make_ppoll_based_event_loop();
auto counter = 0U;
evloop->invoke_at(
evloop->get_etime() + small_time_increment,
[&]() {
++counter;
});
ASSERT_EQ(counter, 0U);
ASSERT_FALSE(evloop->run_iterations());
ASSERT_EQ(counter, 1U);
}
TEST(NosyncPpollBasedEventLoop, TestTasksWithTimeIncrements)
{
constexpr auto task_repetitions = 5U;
auto evloop = make_ppoll_based_event_loop();
const auto start_time = evloop->get_etime();
vector<ch::time_point<eclock>> task_times;
function<void()> task;
task = [&]() {
task_times.push_back(evloop->get_etime());
if (task_times.size() < task_repetitions) {
evloop->invoke_at(evloop->get_etime() + small_time_increment, make_copy(task));
}
};
evloop->invoke_at(evloop->get_etime() + small_time_increment, make_copy(task));
ASSERT_FALSE(evloop->run_iterations());
ASSERT_EQ(task_times.size(), task_repetitions);
auto prev_task_time = start_time;
for (auto task_time : task_times) {
ASSERT_GT(task_time, prev_task_time);
prev_task_time = task_time;
}
}
TEST(NosyncPpollBasedEventLoop, TestTasksNoTimeIncrements)
{
constexpr auto task_repetitions = 5U;
auto evloop = make_ppoll_based_event_loop();
vector<ch::time_point<eclock>> task_times;
for (auto i = 0U; i < task_repetitions; ++i) {
evloop->invoke_at(
evloop->get_etime() + small_time_increment,
[&]() {
task_times.push_back(evloop->get_etime());
});
}
ASSERT_FALSE(evloop->run_iterations());
ASSERT_EQ(task_times.size(), task_repetitions);
for (const auto task_time : task_times) {
ASSERT_EQ(task_time, task_times.front());
}
}
TEST(NosyncPpollBasedEventLoop, TestFdWatch)
{
auto evloop = make_ppoll_based_event_loop();
int pipe_fds_a[2];
ASSERT_EQ(::pipe2(pipe_fds_a, O_CLOEXEC), 0);
unique_ptr<activity_handle> activity_handle_a;
int pipe_fds_b[2];
ASSERT_EQ(::pipe2(pipe_fds_b, O_CLOEXEC), 0);
unique_ptr<activity_handle> activity_handle_b;
auto exec_trace = ""s;
evloop->invoke_at(
evloop->get_etime() + small_time_increment,
[&]() {
exec_trace.push_back('S');
activity_handle_a = evloop->add_watch(
pipe_fds_a[0], fd_watch_mode::input,
[&]() {
exec_trace.push_back('R');
activity_handle_a->disable();
});
activity_handle_b = evloop->add_watch(
pipe_fds_b[0], fd_watch_mode::input,
[&]() {
exec_trace.push_back('r');
activity_handle_b->disable();
});
evloop->invoke_at(
evloop->get_etime() + small_time_increment,
[&]() {
exec_trace.push_back('W');
::write(pipe_fds_a[1], "", 1);
});
});
evloop->invoke_at(
evloop->get_etime(),
[&]() {
exec_trace.push_back('w');
::write(pipe_fds_b[1], "", 1);
});
ASSERT_EQ(exec_trace, ""s);
ASSERT_FALSE(evloop->run_iterations());
ASSERT_EQ(exec_trace, "wSrWR"s);
}
TEST(NosyncPpollBasedEventLoop, TestQuitBetweenTasks)
{
auto evloop = make_ppoll_based_event_loop();
auto exec_trace = ""s;
unique_ptr<activity_handle> activity_handle;
evloop->invoke_at(
evloop->get_etime() + small_time_increment,
[&]() {
exec_trace.push_back('1');
evloop->quit();
});
evloop->invoke_at(
evloop->get_etime() + small_time_increment * 2,
[&]() {
exec_trace.push_back('2');
});
ASSERT_EQ(exec_trace, ""s);
ASSERT_EQ(evloop->run_iterations(), make_error_code(errc::interrupted));
ASSERT_EQ(exec_trace, "1"s);
}
TEST(NosyncPpollBasedEventLoop, TestQuitBetweenWatches)
{
auto evloop = make_ppoll_based_event_loop();
int pipe_fds[2];
ASSERT_EQ(::pipe2(pipe_fds, O_CLOEXEC), 0);
auto exec_trace = ""s;
evloop->add_watch(
pipe_fds[0], fd_watch_mode::input,
[&]() {
exec_trace.push_back('1');
evloop->quit();
});
evloop->add_watch(
pipe_fds[0], fd_watch_mode::input,
[&]() {
exec_trace.push_back('2');
});
::write(pipe_fds[1], "", 1);
ASSERT_EQ(exec_trace, ""s);
ASSERT_EQ(evloop->run_iterations(), make_error_code(errc::interrupted));
ASSERT_EQ(exec_trace, "1"s);
}
| 25.600939
| 91
| 0.615074
|
nokia
|
76821c60e0b5e0d0b79e905cf309fa43dd9dda05
| 2,072
|
cpp
|
C++
|
src/core/CL/CLHelpers.cpp
|
longbowlee/ARMComputeLibrary
|
c772c0b2ecfe76cac5867915fdc296d14bb829a2
|
[
"MIT"
] | 3
|
2017-04-02T08:41:24.000Z
|
2017-10-20T07:56:01.000Z
|
src/core/CL/CLHelpers.cpp
|
loliod/ComputeLibrary
|
871448ee8eff790c4ccc3250008dd71170cc78b2
|
[
"MIT"
] | null | null | null |
src/core/CL/CLHelpers.cpp
|
loliod/ComputeLibrary
|
871448ee8eff790c4ccc3250008dd71170cc78b2
|
[
"MIT"
] | 1
|
2017-12-21T04:13:45.000Z
|
2017-12-21T04:13:45.000Z
|
/*
* Copyright (c) 2016, 2017 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/core/CL/CLHelpers.h"
#include "arm_compute/core/Error.h"
#include "arm_compute/core/Types.h"
namespace arm_compute
{
std::string get_cl_type_from_data_type(const DataType &dt)
{
switch(dt)
{
case DataType::U8:
return "uchar";
case DataType::S8:
return "char";
case DataType::U16:
return "ushort";
case DataType::S16:
return "short";
case DataType::U32:
return "uint";
case DataType::S32:
return "int";
case DataType::U64:
return "ulong";
case DataType::S64:
return "long";
case DataType::F16:
return "half";
case DataType::F32:
return "float";
default:
ARM_COMPUTE_ERROR("Unsupported input data type.");
return "";
}
}
} // namespace arm_compute
| 33.967213
| 81
| 0.662645
|
longbowlee
|
76860c006f96ab42e021eb975a9e686c1500b924
| 719
|
cpp
|
C++
|
src/pass/analyze-usage/conditional.cpp
|
arrow-lang/arrow-legacy
|
5857697b88201c9a6abdd63c1b132741f3451b01
|
[
"MIT"
] | 1
|
2017-05-02T14:13:51.000Z
|
2017-05-02T14:13:51.000Z
|
src/pass/analyze-usage/conditional.cpp
|
arrow-lang/arrow-legacy
|
5857697b88201c9a6abdd63c1b132741f3451b01
|
[
"MIT"
] | null | null | null |
src/pass/analyze-usage/conditional.cpp
|
arrow-lang/arrow-legacy
|
5857697b88201c9a6abdd63c1b132741f3451b01
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2014-2015 Ryan Leckey, All Rights Reserved.
// Distributed under the MIT License
// See accompanying file LICENSE
#include <algorithm>
#include "arrow/pass/analyze-usage.hpp"
#include "arrow/match.hpp"
namespace arrow {
namespace pass {
void AnalyzeUsage::visit_conditional(ast::Conditional& x) {
// Accept the conditiona (always entered)
x.condition->accept(*this);
// Accept the lhs-hand-side (but apply its result as not-definite)
_enter_block(*x.lhs);
x.lhs->accept(*this);
_exit_block(false);
// Accept the rhs-hand-side (but apply its result as not-definite)
_enter_block(*x.rhs);
x.rhs->accept(*this);
_exit_block(false);
}
} // namespace pass
} // namespace arrow
| 23.193548
| 68
| 0.713491
|
arrow-lang
|
768629ebd1783b922f786e0b5e0b29393a08a2a2
| 639
|
cpp
|
C++
|
src/E12.cpp
|
microentropie/IEC60063
|
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
|
[
"MIT"
] | null | null | null |
src/E12.cpp
|
microentropie/IEC60063
|
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
|
[
"MIT"
] | null | null | null |
src/E12.cpp
|
microentropie/IEC60063
|
6b3900d9ed4554209cbb88c044d3d81e17ba47a6
|
[
"MIT"
] | null | null | null |
/*
Author: Stefano Di Paolo
License: MIT, https://en.wikipedia.org/wiki/MIT_License
Date: 2017-12-31
Library: IEC60063 series resistors.
Sources repository: https://github.com/microentropie/
*/
#include "E-series.h"
const char E12Tolerance[] = "10%";
#define E12size 12
static const unsigned short E12[E12size + 1] = { 100, 120, 150, 180, 220, 270, 330, 390, 470, 560, 680, 820, 1000 };
float E12Value(float r)
{
return EserieValue(E12, E12size, r);
}
char *E12FormattedValue(char *buf, int len, float r, char unitTypeChar)
{
return EserieFormattedValue(buf, len, E12, E12size, r, unitTypeChar);
}
| 22.821429
| 117
| 0.682316
|
microentropie
|
768c4c836c3bebef4ea2a3a02cacaf5127d75b51
| 1,503
|
cpp
|
C++
|
HotDays.cpp
|
Drew138/competitive
|
6efdbfed97934ba5a894e2b71d76340d4c769e45
|
[
"MIT"
] | null | null | null |
HotDays.cpp
|
Drew138/competitive
|
6efdbfed97934ba5a894e2b71d76340d4c769e45
|
[
"MIT"
] | null | null | null |
HotDays.cpp
|
Drew138/competitive
|
6efdbfed97934ba5a894e2b71d76340d4c769e45
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define D(x) cout << #x << " = " << x << endl;
#define ios ios_base::sync_with_stdio(0), cin.tie(0);
#define forn(i, n) for (int i = 0; i < (int)n; ++i)
#define all(v) v.begin(), v.end()
#define formap(map) for (const auto &[key, value] : map)
#define ms(ar, val) memset(ar, val, sizeof ar)
typedef long long ll;
typedef long double ld;
using namespace std;
int main()
{
ll numRegions, numChildren, regTemp, maxTemp, penalty, costBus, numBuses, minCase, maxCase, total = 0;
cin >> numRegions >> numChildren;
while (numRegions--)
{
cin >> regTemp >> maxTemp >> penalty >> costBus;
if (maxTemp >= (regTemp + numChildren))
{
total += costBus;
}
else
{
if (regTemp >= maxTemp)
{
total += costBus + (numChildren * penalty);
}
else
{
minCase = costBus + (numChildren * penalty);
if (numChildren % (maxTemp - regTemp))
{
maxCase = min(costBus * ((numChildren / (maxTemp - regTemp)) + 1), costBus * (numChildren / (maxTemp - regTemp)) + penalty * ((numChildren % (maxTemp - regTemp)) + (maxTemp - regTemp)));
}
else
{
maxCase = costBus * ((numChildren / (maxTemp - regTemp)));
}
total += min(maxCase, minCase);
}
}
}
cout << total;
}
| 30.673469
| 206
| 0.496341
|
Drew138
|
768cf7a415fa7f7e2d366091974abdea7db9f3dd
| 1,700
|
cpp
|
C++
|
windows/pw6e.official/CPlusPlus/Chapter10/WheresMyElement/WheresMyElement/MainPage.xaml.cpp
|
nnaabbcc/exercise
|
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
|
[
"MIT"
] | 1
|
2016-11-23T08:18:08.000Z
|
2016-11-23T08:18:08.000Z
|
windows/pw6e.official/CPlusPlus/Chapter10/WheresMyElement/WheresMyElement/MainPage.xaml.cpp
|
nnaabbcc/exercise
|
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
|
[
"MIT"
] | null | null | null |
windows/pw6e.official/CPlusPlus/Chapter10/WheresMyElement/WheresMyElement/MainPage.xaml.cpp
|
nnaabbcc/exercise
|
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
|
[
"MIT"
] | 1
|
2016-11-23T08:17:34.000Z
|
2016-11-23T08:17:34.000Z
|
//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
using namespace WheresMyElement;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
MainPage::MainPage()
{
InitializeComponent();
}
void MainPage::OnTapped(TappedRoutedEventArgs^ args)
{
if (storyboardPaused)
{
storyboard->Resume();
storyboardPaused = false;
return;
}
GeneralTransform^ xform = txtblk->TransformToVisual(contentGrid);
// Draw blue polygon around element
polygon->Points->Clear();
polygon->Points->Append(xform->TransformPoint(Point(0, 0)));
polygon->Points->Append(xform->TransformPoint(Point((float)txtblk->ActualWidth, 0)));
polygon->Points->Append(xform->TransformPoint(Point((float)txtblk->ActualWidth,
(float)txtblk->ActualHeight)));
polygon->Points->Append(xform->TransformPoint(Point(0, (float)txtblk->ActualHeight)));
// Draw red bounding box
RectangleGeometry^ rectangleGeometry = ref new RectangleGeometry();
rectangleGeometry->Rect = xform->TransformBounds(Rect(Point(0, 0), txtblk->DesiredSize));
path->Data = rectangleGeometry;
storyboard->Pause();
storyboardPaused = true;
}
| 31.481481
| 94
| 0.678235
|
nnaabbcc
|
768e2018aa71800fb684786b766ce0df824b538e
| 604
|
cpp
|
C++
|
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
|
BachWV/matu
|
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
|
[
"MIT"
] | null | null | null |
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
|
BachWV/matu
|
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
|
[
"MIT"
] | null | null | null |
allMatuCommit/实现Point类(C++)_qwe123qwe_20210920104346.cpp
|
BachWV/matu
|
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<string>
#include<algorithm>
#include<cstring>
#include<string.h>
#include<math.h>
#include<cmath>
using namespace std;
typedef long long int ll;
class Point{
private :
double x,y;
public:
Point(double a,double b)
{
x=a;y=b;
}
double Distance( Point const & b )
{
double ans=0;
ans = sqrt( pow(x- b.x,2)+ pow(y- b.y,2 ) );
return ans;
}
};
int main()
{
double a,b,c,d;
cin>>a>>b>>c>>d;
Point A(a,b),B(c,d);
cout<<A.Distance(B)<<endl;
return 0;
double x=2.5;
//cout<<pow(x,3)<<endl;
return 0;
}
| 15.1
| 48
| 0.56457
|
BachWV
|
7692b4bc129f3cee9fead0e4559e38bac59cce54
| 6,004
|
cpp
|
C++
|
src/LinearColorCalibrator.cpp
|
alarrosa14/Sendero
|
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
|
[
"MIT"
] | 1
|
2016-07-06T23:22:16.000Z
|
2016-07-06T23:22:16.000Z
|
src/LinearColorCalibrator.cpp
|
alarrosa14/Sendero
|
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
|
[
"MIT"
] | null | null | null |
src/LinearColorCalibrator.cpp
|
alarrosa14/Sendero
|
fb81c43b3f0ef3b8ef8fbbce6fdd2d413b4c9542
|
[
"MIT"
] | null | null | null |
//
// LinearColorCalibrator.cpp
// LEDColorCalibrator
//
// Created by Tomas Laurenzo on 4/20/13.
//
//
#include "LinearColorCalibrator.h"
LinearColorCalibrator::LinearColorCalibrator(){
gammaCorrecting = false;
isCalculated = true;
}
void LinearColorCalibrator::useGamma() {
gammaCorrecting = true;
}
void LinearColorCalibrator::dontUseGamma() {
gammaCorrecting = false;
}
void LinearColorCalibrator::setGamma (float gamma) {
this->gamma = gamma;
}
bool LinearColorCalibrator::calculateCalibration() {
if (pairs.size() < 3) {
isCalculated = false;
return false;
}
ofColor v0 = pairs[pairs.size() - 1].first;
ofColor v1 = pairs[pairs.size() - 2].first;
ofColor v2 = pairs[pairs.size() - 3].first;
ofColor w0 = pairs[pairs.size() - 1].second;
ofColor w1 = pairs[pairs.size() - 2].second;
ofColor w2 = pairs[pairs.size() - 3].second;
double *A;
A = new double[81];
// matrix in COLUMN MAJOR ORDER
// columns 1..3
int i = 0;
A[i++] = v0.r;
A[i++] = v1.r;
A[i++] = v2.r;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.g;
A[i++] = v1.g;
A[i++] = v2.g;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.b;
A[i++] = v1.b;
A[i++] = v2.b;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
//columns 4..6
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.r;
A[i++] = v1.r;
A[i++] = v2.r;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.g;
A[i++] = v1.g;
A[i++] = v2.g;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.b;
A[i++] = v1.b;
A[i++] = v2.b;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
//columns 7..9
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.r;
A[i++] = v1.r;
A[i++] = v2.r;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.g;
A[i++] = v1.g;
A[i++] = v2.g;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = 0;
A[i++] = v0.b;
A[i++] = v1.b;
A[i++] = v2.b;
double *b;
b = new double[9]; // w1, w2, w3
i = 0;
b[i++] = w0[0];
b[i++] = w0[1];
b[i++] = w0[2];
b[i++] = w1[0];
b[i++] = w1[1];
b[i++] = w1[2];
b[i++] = w2[0];
b[i++] = w2[1];
b[i++] = w2[2];
// solving the linear system AX = b
int N = 9; // number of columns of A
int NRHS = 1; // number of columns of b
int LDA = 9; // number of rows of A
int IPIV[9]; // pivot indices
int LDB = 9; // number of rows of b
int INFO = 0;
//INFO = clapack_dgesv((CBLAS_ORDER) 101, N, NRHS, A, LDA, IPIV, b, LDB);
dgesv_(&N, &NRHS, A, &LDA, IPIV, b, &LDB, &INFO);
if (INFO == 0) cout << endl << "dgesv_: OK";
if (INFO < 0) cout << "dgesv_: the element " << INFO << " is invalid";
if (INFO > 0) cout << "dgesv_: the LU decomposition returned 0 ";
cout << endl << endl;
/*
__CLPK_integer is long *
__CLPK_doublereal is double *
dgesv_(__CLPK_integer *n, __CLPK_integer *nrhs, __CLPK_doublereal *a, __CLPK_integer *lda, __CLPK_integer *ipiv,
__CLPK_doublereal *b, __CLPK_integer *ldb, __CLPK_integer *info)
void dgesv_(const int *N, const int *nrhs, double *A, const int *lda, int
*ipiv, double *b, const int *ldb, int *info);
Notice that all parameters are passed by reference. That's the good old Fortran way. The meanings of the parameters are:
N number of columns of A
nrhs number of columns of b, usually 1
lda number of rows (Leading Dimension of A) of A
ipiv pivot indices
ldb number of rows of b
*/
i = 0;
T[0][0] = b[i++];
T[1][0] = b[i++];
T[2][0] = b[i++];
T[0][1] = b[i++];
T[1][1] = b[i++];
T[2][1] = b[i++];
T[0][2] = b[i++];
T[1][2] = b[i++];
T[2][2] = b[i++];
cout << "Transformation matrix: " << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j ++) {
cout << "\t" << T[i][j];
}
cout << endl;
}
cout << endl;
isCalculated = true;
delete[]A;
delete[]b;
}
ofColor LinearColorCalibrator::getCalibratedColor(ofColor color) {
if (!isCalculated) calculateCalibration();
if (!isCalculated) return color;
// calibrated color = T * color
ofColor res;
res = res.black;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
res[i] += color[i] * T[j][i];
}
}
if (gammaCorrecting) {
for (int i = 0; i < 3; i++) {
float f = (int)res[i] / 255.0f;
float r = pow(f, gamma);
int g = r * 255.0f;
int o = f * 255.0f;
res[i] = g;
}
}
return res;
}
float LinearColorCalibrator::getGamma() {
return gamma;
}
void LinearColorCalibrator::addEquivalentPair(ofColor first, ofColor second) {
// we assume lineal, because we are in a hurry and non linear is complicated
// todo: change it to non linear transformation using little CMS
// the idea is, we create a profile for the LEDs and a profile for the monitor and use little CMS to make the
// transformation between them
// pair <first, second> p;
pairs.push_back(pair<ofColor, ofColor>(first, second));
isCalculated = false;
}
void LinearColorCalibrator::reset() {
pairs.clear();
isCalculated = false;
}
| 21.519713
| 124
| 0.463025
|
alarrosa14
|
7693b2d81fb6d9bef245f2341f00fb948e664470
| 5,756
|
cpp
|
C++
|
Source/PraticeActor/CBattlePC.cpp
|
CitrusNyamNyam/Unreal-Portfolio
|
f5a63fbe796e0531604470767207831b5c523b54
|
[
"MIT"
] | 1
|
2018-11-25T10:40:10.000Z
|
2018-11-25T10:40:10.000Z
|
Source/PraticeActor/CBattlePC.cpp
|
CitrusNyamNyam/Unreal-Portfolio
|
f5a63fbe796e0531604470767207831b5c523b54
|
[
"MIT"
] | null | null | null |
Source/PraticeActor/CBattlePC.cpp
|
CitrusNyamNyam/Unreal-Portfolio
|
f5a63fbe796e0531604470767207831b5c523b54
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "CBattlePC.h"
#include "CBattleGM.h"
#include "CPlayer.h"
#include "CAirplane_C130.h"
#include "CFlyingViewer.h"
#include "CResult_Widget.h"
#include "CClientMain_Widget.h"
#include "CWorldMap_Widget.h"
#include "Animation/WidgetAnimation.h"
#include "UserWidget.h"
#include "UnrealNetwork.h"
#include "Engine.h"
ACBattlePC::ACBattlePC()
:bDived(false), bWorldMap(false)
, MapSize(816000.0f,816000.0f,0.0f)
{
static ConstructorHelpers::FObjectFinder<UClass> clientWidget(TEXT("/Game/GameMode/Battle/UMG/WidgetBP_ClientMain.WidgetBP_ClientMain_C"));
if (clientWidget.Object)
TSubClientMainWidget = clientWidget.Object;
static ConstructorHelpers::FObjectFinder<UClass> resultWidget(TEXT("/Game/GameMode/Battle/UMG/WidgetBP_Result.WidgetBP_Result_C"));
if (resultWidget.Object)
TSubResultWidget = resultWidget.Object;
static ConstructorHelpers::FObjectFinder<UClass> worldMapWidget(TEXT("/Game/WorldMap/WidgetBP_WorldMap.WidgetBP_WorldMap_C"));
if (worldMapWidget.Object)
TSubWorldMapWidget = worldMapWidget.Object;
}
void ACBattlePC::BeginPlay()
{
Super::BeginPlay();
TArray<AActor*> outActors;
UGameplayStatics::GetAllActorsWithTag(GetWorld(), FName("C130"), outActors);
if (outActors.Num() > 0)
{
Airplane_C130 = Cast<ACAirplane_C130>(outActors[0]);
}
SetInputMode(FInputModeGameOnly());
bShowMouseCursor = false;
if (!HasAuthority())
{
ClientMainWidget = CreateWidget<UCClientMain_Widget>(GetWorld(), TSubClientMainWidget);
ResultWidget = CreateWidget<UCResult_Widget>(GetWorld(), TSubResultWidget);
if (ClientMainWidget)
{
ClientMainWidget->AddToViewport();
}
}
}
void ACBattlePC::SetupInputComponent()
{
Super::SetupInputComponent();
InputComponent->BindAction("WorldMap", EInputEvent::IE_Pressed, this, &ACBattlePC::OnOpenWorldMap);
}
bool ACBattlePC::GetAirplane()
{
ACFlyingViewer* viewer = Cast<ACFlyingViewer>(GetPawn());
if (viewer)
{
return true;
}
else return false;
}
FVector ACBattlePC::GetPawnDirection()
{
ACFlyingViewer* viewer = Cast<ACFlyingViewer>(GetPawn());
if (viewer)
{
return Airplane_C130->GetActorForwardVector();
}
else
{
return GetPawn()->GetActorForwardVector();
}
return FVector::ZeroVector;
}
void ACBattlePC::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ACBattlePC, NotificationFromServer);
}
void ACBattlePC::OnCharacterDeath()
{
ACBattleGM* gameMode = Cast<ACBattleGM>(UGameplayStatics::GetGameMode(GetWorld()));
if (gameMode)
{
gameMode->OnCharacterDeath(this);
}
}
void ACBattlePC::OnOpenWorldMap()
{
if (WorldMapWidget == NULL)
{
WorldMapWidget = CreateWidget<UCWorldMap_Widget>(GetWorld(), TSubWorldMapWidget);
}
if (WorldMapWidget != NULL)
{
if (!bWorldMap)
{
bWorldMap = true;
WorldMapWidget->AddToViewport();
}
else
{
bWorldMap = false;
WorldMapWidget->RemoveFromParent();
}
}
}
FVector ACBattlePC::GetPawnPosition()
{
if (GetPawn())
{
return GetPawn()->GetActorLocation();
}
return FVector(9999999999,9999999999,0);
}
bool ACBattlePC::ServerRPC_RideInAirplaneC130_Validate(ACAirplane_C130 * airplane)
{
return true;
}
void ACBattlePC::ServerRPC_RideInAirplaneC130_Implementation(ACAirplane_C130 * airplane)
{
if (airplane)
{
GetPawn()->Destroy();
FActorSpawnParameters parameters;
parameters.Owner = this;
parameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
FVector location = airplane->GetActorLocation();
ACFlyingViewer* viewer = GetWorld()->SpawnActor<ACFlyingViewer>(ACFlyingViewer::StaticClass(), location, FRotator::ZeroRotator, parameters);
Possess(viewer);
FAttachmentTransformRules rules(EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, EAttachmentRule::SnapToTarget, true);
viewer->AttachToActor(airplane, rules);
}
}
bool ACBattlePC::ServerRPC_WantToDive_Validate()
{
return true;
}
void ACBattlePC::ServerRPC_WantToDive_Implementation()
{
if (bDived) return;
bDived = true;
FVector location = GetPawn()->GetActorLocation();
location.Z -= 1000.0f;
FActorSpawnParameters parameters;
parameters.Owner = this;
parameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
ACPlayer* player = GetWorld()->SpawnActor<ACPlayer>(ACPlayer::StaticClass(), location, FRotator::ZeroRotator, parameters);
GetPawn()->Destroy();
if (player)
{
player->SetDive(true);
Possess(player);
}
}
void ACBattlePC::ClientRPC_BackToLobby_Implementation()
{
UGameplayStatics::OpenLevel(GetWorld(), FName("Lobby"));
}
void ACBattlePC::ClientRPC_ShowDeathResult_Implementation(int rank)
{
if (ResultWidget)
{
ResultWidget->ResultString = FString(TEXT("that's fine, that can happen.."));
ResultWidget->RankString = FString("#") + FString::FromInt(rank);
ResultWidget->AddToViewport();
FInputModeUIOnly Mode;
Mode.SetWidgetToFocus(ResultWidget->GetCachedWidget());
SetInputMode(Mode);
bShowMouseCursor = true;
}
}
void ACBattlePC::ClientRPC_ShowWinnerResult_Implementation()
{
if (ResultWidget)
{
ResultWidget->ResultString = FString(TEXT("WINNER WINNER CHICKEN DINNER"));
ResultWidget->RankString = FString("#") + FString::FromInt(1);
ResultWidget->AddToViewport();
FInputModeUIOnly Mode;
Mode.SetWidgetToFocus(ResultWidget->GetCachedWidget());
SetInputMode(Mode);
bShowMouseCursor = true;
}
}
void ACBattlePC::ClientRPC_ShowBloodScreenEffect_Implementation()
{
if (ClientMainWidget)
{
if (ClientMainWidget->BloodEffectAnimation)
{
ClientMainWidget->PlayAnimation(ClientMainWidget->BloodEffectAnimation);
}
}
}
| 23.590164
| 142
| 0.761119
|
CitrusNyamNyam
|
7696137c106984a49fa532b5274a6d9255224b6d
| 112
|
hpp
|
C++
|
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
|
mycloudmyworld2019/DA-DAPPS
|
534ace858fb5d852d69a578151929e64e2932f8b
|
[
"MIT"
] | null | null | null |
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
|
mycloudmyworld2019/DA-DAPPS
|
534ace858fb5d852d69a578151929e64e2932f8b
|
[
"MIT"
] | null | null | null |
libraries/chain/include/DA-DAPPS/chain/protocol.hpp
|
mycloudmyworld2019/DA-DAPPS
|
534ace858fb5d852d69a578151929e64e2932f8b
|
[
"MIT"
] | null | null | null |
/**
* @file
* @copyright defined in DA-DAPPS/LICENSE
*/
#pragma once
#include <DA-DAPPSio/chain/block.hpp>
| 16
| 42
| 0.669643
|
mycloudmyworld2019
|
769951a4c9b60f20bdb25e2bf0f6607c12640307
| 877
|
cpp
|
C++
|
v142/main.cpp
|
glensand/visual-studio-compatibility
|
7a7c7953bd4f7b8cf16485e66a90c966c8b1f829
|
[
"MIT"
] | 3
|
2020-07-11T07:12:45.000Z
|
2020-07-13T03:00:40.000Z
|
v142/main.cpp
|
glensand/visual-studio-compatibility
|
7a7c7953bd4f7b8cf16485e66a90c966c8b1f829
|
[
"MIT"
] | null | null | null |
v142/main.cpp
|
glensand/visual-studio-compatibility
|
7a7c7953bd4f7b8cf16485e66a90c966c8b1f829
|
[
"MIT"
] | 1
|
2020-07-11T07:10:33.000Z
|
2020-07-11T07:10:33.000Z
|
#include "v110/export_class_110.h"
#include "v141/export_class_141.h"
#include "v142/derived_class_142.h"
#include "v110_static/class_110.h"
int main()
{
// stack object construction - destruction works well
export_class_110 ec;
// we cannot deallocate memory were allocated in another module
// it seems like wrong dll loading
//const auto vector = ec.getStringList();
//std::vector<std::string> testNotTrivialVector;
//ExportClass::Fill(testNotTrivialVector);
// also memory allocation and deallocation if it were done in single module works
auto* export_110 = export_class_110::create();
export_class_110::destroy(export_110);
auto* export_141 = export_class_141::create();
delete export_141;
ref_counted* d_c = new derived_class_142;
delete d_c;
class_110 static_class;
static_class.do_something();
static_class.add_string("asfsadgdg");
return 0;
}
| 28.290323
| 82
| 0.769669
|
glensand
|
769a742c357a56feffbcb12987512783b6dc1fd0
| 14,624
|
cpp
|
C++
|
src/mods/vr/D3D11Component.cpp
|
fengjixuchui/REFramework
|
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
|
[
"MIT"
] | null | null | null |
src/mods/vr/D3D11Component.cpp
|
fengjixuchui/REFramework
|
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
|
[
"MIT"
] | null | null | null |
src/mods/vr/D3D11Component.cpp
|
fengjixuchui/REFramework
|
131b25ef58064b1c36cdd15072c30f5fbd9a7ad8
|
[
"MIT"
] | null | null | null |
#include <imgui.h>
#include <imgui_internal.h>
#include <openvr.h>
#include "../VR.hpp"
#include "D3D11Component.hpp"
#ifdef VERBOSE_D3D11
#define LOG_VERBOSE(...) spdlog::info(__VA_ARGS__)
#else
#define LOG_VERBOSE
#endif
namespace vrmod {
vr::EVRCompositorError D3D11Component::on_frame(VR* vr) {
if (m_left_eye_tex == nullptr) {
setup();
}
auto& hook = g_framework->get_d3d11_hook();
// get device
auto device = hook->get_device();
// Get the context.
ComPtr<ID3D11DeviceContext> context{};
device->GetImmediateContext(&context);
// get swapchain
auto swapchain = hook->get_swap_chain();
// get back buffer
ComPtr<ID3D11Texture2D> backbuffer{};
swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer));
if (backbuffer == nullptr) {
spdlog::error("[VR] Failed to get back buffer.");
return vr::VRCompositorError_None;
}
auto runtime = vr->get_runtime();
// If m_frame_count is even, we're rendering the left eye.
if (vr->m_render_frame_count % 2 == vr->m_left_eye_interval) {
if (runtime->is_openxr() && runtime->ready()) {
LOG_VERBOSE("Copying left eye");
m_openxr.copy(0, backbuffer.Get());
}
if (runtime->is_openvr()) {
// Copy the back buffer to the left eye texture (m_left_eye_tex0 holds the intermediate frame).
context->CopyResource(m_left_eye_tex.Get(), backbuffer.Get());
vr::Texture_t left_eye{(void*)m_left_eye_tex.Get(), vr::TextureType_DirectX, vr::ColorSpace_Auto};
auto e = vr::VRCompositor()->Submit(vr::Eye_Left, &left_eye, &vr->m_left_bounds);
bool submitted = true;
if (e != vr::VRCompositorError_None) {
spdlog::error("[VR] VRCompositor failed to submit left eye: {}", (int)e);
vr->m_submitted = false;
return e;
}
}
} else {
if (runtime->ready()) {
if (runtime->is_openxr()) {
LOG_VERBOSE("Copying right eye");
m_openxr.copy(1, backbuffer.Get());
}
if (runtime->get_synchronize_stage() == VRRuntime::SynchronizeStage::VERY_LATE || !runtime->got_first_sync) {
runtime->synchronize_frame();
if (!runtime->got_first_poses) {
runtime->update_poses();
}
}
}
if (runtime->is_openxr() && vr->m_openxr->ready()) {
if (runtime->get_synchronize_stage() == VRRuntime::SynchronizeStage::VERY_LATE || !vr->m_openxr->frame_began) {
LOG_VERBOSE("Beginning frame.");
vr->m_openxr->begin_frame();
}
LOG_VERBOSE("Ending frame");
auto result = vr->m_openxr->end_frame();
vr->m_openxr->needs_pose_update = true;
vr->m_submitted = result == XR_SUCCESS;
}
if (runtime->is_openvr()) {
// Copy the back buffer to the right eye texture.
context->CopyResource(m_right_eye_tex.Get(), backbuffer.Get());
vr::Texture_t right_eye{(void*)m_right_eye_tex.Get(), vr::TextureType_DirectX, vr::ColorSpace_Auto};
auto e = vr::VRCompositor()->Submit(vr::Eye_Right, &right_eye, &vr->m_right_bounds);
bool submitted = true;
if (e != vr::VRCompositorError_None) {
spdlog::error("[VR] VRCompositor failed to submit right eye: {}", (int)e);
vr->m_submitted = false;
return e;
}
vr->m_submitted = true;
}
if (runtime->ready()) {
hook->ignore_next_present();
}
}
return vr::VRCompositorError_None;
}
void D3D11Component::on_reset(VR* vr) {
m_left_eye_tex.Reset();
m_right_eye_tex.Reset();
m_left_eye_depthstencil.Reset();
m_right_eye_depthstencil.Reset();
if (vr->get_runtime()->is_openxr() && vr->get_runtime()->loaded) {
if (m_openxr.last_resolution[0] != vr->get_hmd_width() || m_openxr.last_resolution[1] != vr->get_hmd_height()) {
m_openxr.create_swapchains();
}
}
}
void D3D11Component::setup() {
// Get device and swapchain.
auto& hook = g_framework->get_d3d11_hook();
auto device = hook->get_device();
auto swapchain = hook->get_swap_chain();
// Get back buffer.
ComPtr<ID3D11Texture2D> backbuffer{};
swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer));
// Get backbuffer description.
D3D11_TEXTURE2D_DESC backbuffer_desc{};
backbuffer->GetDesc(&backbuffer_desc);
backbuffer_desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
// Create eye textures.
device->CreateTexture2D(&backbuffer_desc, nullptr, &m_left_eye_tex);
device->CreateTexture2D(&backbuffer_desc, nullptr, &m_right_eye_tex);
// copy backbuffer into right eye
// Get the context.
ComPtr<ID3D11DeviceContext> context{};
device->GetImmediateContext(&context);
context->CopyResource(m_right_eye_tex.Get(), backbuffer.Get());
// Make depth stencils for both eyes.
auto depthstencil = hook->get_last_depthstencil_used();
if (depthstencil != nullptr) {
D3D11_TEXTURE2D_DESC depthstencil_desc{};
depthstencil->GetDesc(&depthstencil_desc);
// Create eye depthstencils.
device->CreateTexture2D(&depthstencil_desc, nullptr, &m_left_eye_depthstencil);
device->CreateTexture2D(&depthstencil_desc, nullptr, &m_right_eye_depthstencil);
// Copy the current depthstencil into the right eye.
context->CopyResource(m_right_eye_depthstencil.Get(), depthstencil.Get());
}
spdlog::info("[VR] d3d11 textures have been setup");
}
void D3D11Component::OpenXR::initialize(XrSessionCreateInfo& session_info) {
std::scoped_lock _{this->mtx};
auto& hook = g_framework->get_d3d11_hook();
auto device = hook->get_device();
this->binding.device = device;
PFN_xrGetD3D11GraphicsRequirementsKHR fn = nullptr;
xrGetInstanceProcAddr(VR::get()->m_openxr->instance, "xrGetD3D11GraphicsRequirementsKHR", (PFN_xrVoidFunction*)(&fn));
if (fn == nullptr) {
spdlog::error("[VR] xrGetD3D11GraphicsRequirementsKHR not found");
return;
}
// get existing adapter from device
ComPtr<IDXGIDevice> dxgi_device{};
if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dxgi_device)))) {
spdlog::error("[VR] failed to get DXGI device from D3D11 device");
return;
}
ComPtr<IDXGIAdapter> adapter{};
if (FAILED(dxgi_device->GetAdapter(&adapter))) {
spdlog::error("[VR] failed to get DXGI adapter from DXGI device");
return;
}
DXGI_ADAPTER_DESC desc{};
if (FAILED(adapter->GetDesc(&desc))) {
spdlog::error("[VR] failed to get DXGI adapter description");
return;
}
XrGraphicsRequirementsD3D11KHR gr{XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR};
gr.adapterLuid = desc.AdapterLuid;
gr.minFeatureLevel = D3D_FEATURE_LEVEL_11_0;
fn(VR::get()->m_openxr->instance, VR::get()->m_openxr->system, &gr);
session_info.next = &this->binding;
}
std::optional<std::string> D3D11Component::OpenXR::create_swapchains() {
std::scoped_lock _{this->mtx};
spdlog::info("[VR] Creating OpenXR swapchains for D3D11");
this->destroy_swapchains();
auto& hook = g_framework->get_d3d11_hook();
auto device = hook->get_device();
auto swapchain = hook->get_swap_chain();
// Get back buffer.
ComPtr<ID3D11Texture2D> backbuffer{};
swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer));
if (backbuffer == nullptr) {
spdlog::error("[VR] Failed to get back buffer.");
return "Failed to get back buffer.";
}
// Get backbuffer description.
D3D11_TEXTURE2D_DESC backbuffer_desc{};
backbuffer->GetDesc(&backbuffer_desc);
backbuffer_desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
auto vr = VR::get();
auto& openxr = *vr->m_openxr;
this->contexts.clear();
this->contexts.resize(openxr.views.size());
// Create eye textures.
for (auto i = 0; i < openxr.views.size(); ++i) {
const auto& vp = openxr.view_configs[i];
spdlog::info("[VR] Creating swapchain for eye {}", i);
spdlog::info("[VR] Width: {}", vr->get_hmd_width());
spdlog::info("[VR] Height: {}", vr->get_hmd_height());
backbuffer_desc.Width = vr->get_hmd_width();
backbuffer_desc.Height = vr->get_hmd_height();
XrSwapchainCreateInfo swapchain_create_info{XR_TYPE_SWAPCHAIN_CREATE_INFO};
swapchain_create_info.arraySize = 1;
swapchain_create_info.format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
swapchain_create_info.width = backbuffer_desc.Width;
swapchain_create_info.height = backbuffer_desc.Height;
swapchain_create_info.mipCount = 1;
swapchain_create_info.faceCount = 1;
swapchain_create_info.sampleCount = backbuffer_desc.SampleDesc.Count;
swapchain_create_info.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
runtimes::OpenXR::Swapchain swapchain{};
swapchain.width = swapchain_create_info.width;
swapchain.height = swapchain_create_info.height;
if (xrCreateSwapchain(openxr.session, &swapchain_create_info, &swapchain.handle) != XR_SUCCESS) {
spdlog::error("[VR] D3D11: Failed to create swapchain.");
return "Failed to create swapchain.";
}
vr->m_openxr->swapchains.push_back(swapchain);
uint32_t image_count{};
auto result = xrEnumerateSwapchainImages(swapchain.handle, 0, &image_count, nullptr);
if (result != XR_SUCCESS) {
spdlog::error("[VR] Failed to enumerate swapchain images.");
return "Failed to enumerate swapchain images.";
}
auto& ctx = this->contexts[i];
ctx.textures.clear();
ctx.textures.resize(image_count);
for (uint32_t j = 0; j < image_count; ++j) {
spdlog::info("[VR] Creating swapchain image {} for swapchain {}", j, i);
ctx.textures[j] = {XR_TYPE_SWAPCHAIN_IMAGE_D3D11_KHR};
if (FAILED(device->CreateTexture2D(&backbuffer_desc, nullptr, &ctx.textures[j].texture))) {
spdlog::error("[VR] Failed to create swapchain texture {} {}", i, j);
return "Failed to create swapchain texture.";
}
// get immediate context
ComPtr<ID3D11DeviceContext> context{};
device->GetImmediateContext(&context);
context->CopyResource(ctx.textures[j].texture, backbuffer.Get());
}
result = xrEnumerateSwapchainImages(swapchain.handle, image_count, &image_count, (XrSwapchainImageBaseHeader*)&ctx.textures[0]);
if (result != XR_SUCCESS) {
spdlog::error("[VR] Failed to enumerate swapchain images after texture creation.");
return "Failed to enumerate swapchain images after texture creation.";
}
}
this->last_resolution = {vr->get_hmd_width(), vr->get_hmd_height()};
spdlog::info("[VR] Successfully created OpenXR swapchains for D3D11");
return std::nullopt;
}
void D3D11Component::OpenXR::destroy_swapchains() {
std::scoped_lock _{this->mtx};
if (this->contexts.empty()) {
return;
}
spdlog::info("[VR] Destroying swapchains.");
for (auto i = 0; i < this->contexts.size(); ++i) {
auto& ctx = this->contexts[i];
auto result = xrDestroySwapchain(VR::get()->m_openxr->swapchains[i].handle);
if (result != XR_SUCCESS) {
spdlog::error("[VR] Failed to destroy swapchain {}.", i);
} else {
spdlog::info("[VR] Destroyed swapchain {}.", i);
}
for (auto& tex : ctx.textures) {
tex.texture->Release();
}
ctx.textures.clear();
}
this->contexts.clear();
VR::get()->m_openxr->swapchains.clear();
}
void D3D11Component::OpenXR::copy(uint32_t swapchain_idx, ID3D11Texture2D* resource) {
std::scoped_lock _{this->mtx};
auto vr = VR::get();
if (vr->m_openxr->frame_state.shouldRender != XR_TRUE) {
return;
}
if (!vr->m_openxr->frame_began) {
spdlog::error("[VR] OpenXR: Frame not begun when trying to copy.");
//return;
}
if (this->contexts[swapchain_idx].num_textures_acquired > 0) {
spdlog::info("[VR] Already acquired textures for swapchain {}?", swapchain_idx);
}
auto device = g_framework->get_d3d11_hook()->get_device();
// get immediate context
ComPtr<ID3D11DeviceContext> context;
device->GetImmediateContext(&context);
const auto& swapchain = vr->m_openxr->swapchains[swapchain_idx];
auto& ctx = this->contexts[swapchain_idx];
XrSwapchainImageAcquireInfo acquire_info{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
uint32_t texture_index{};
LOG_VERBOSE("Acquiring swapchain image for {}", swapchain_idx);
auto result = xrAcquireSwapchainImage(swapchain.handle, &acquire_info, &texture_index);
if (result != XR_SUCCESS) {
spdlog::error("[VR] xrAcquireSwapchainImage failed: {}", vr->m_openxr->get_result_string(result));
} else {
ctx.num_textures_acquired++;
XrSwapchainImageWaitInfo wait_info{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO};
//wait_info.timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count();
wait_info.timeout = XR_INFINITE_DURATION;
LOG_VERBOSE("Waiting on swapchain image for {}", swapchain_idx);
result = xrWaitSwapchainImage(swapchain.handle, &wait_info);
if (result != XR_SUCCESS) {
spdlog::error("[VR] xrWaitSwapchainImage failed: {}", vr->m_openxr->get_result_string(result));
} else {
LOG_VERBOSE("Copying swapchain image {} for {}", texture_index, swapchain_idx);
context->CopyResource(ctx.textures[texture_index].texture, resource);
XrSwapchainImageReleaseInfo release_info{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
LOG_VERBOSE("Releasing swapchain image for {}", swapchain_idx);
auto result = xrReleaseSwapchainImage(swapchain.handle, &release_info);
if (result != XR_SUCCESS) {
spdlog::error("[VR] xrReleaseSwapchainImage failed: {}", vr->m_openxr->get_result_string(result));
return;
}
ctx.num_textures_acquired--;
}
}
}
} // namespace vrmod
| 33.388128
| 136
| 0.63642
|
fengjixuchui
|
769ab67ecf0ee03b324e9690cea3ba77cadf5b8a
| 912
|
cpp
|
C++
|
graph-source-code/463-D/8599017.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/463-D/8599017.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/463-D/8599017.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: MS C++
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <cassert>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
typedef vector<int> VI;
const int mod=1000000007;
const int MAXN=1002;
int n,K;
int a[6][MAXN],pos[6][MAXN],dp[MAXN];
void solve(){
scanf("%d%d",&n,&K);
for(int i=1;i<=K;i++)
for(int j=1;j<=n;j++){
scanf("%d",&a[i][j]);
pos[i][a[i][j]]=j;
}
int k,res=0;
for(int j=1;j<=n;j++){
int mx=0;
for(int i=1;i<j;i++){
for(k=2;k<=K && pos[k][a[1][i]]<pos[k][a[1][j]];k++);
if(k==K+1 && mx<dp[i])
mx=dp[i];
}
dp[j]=mx+1;
res=max(res,dp[j]);
}
printf("%d\n",res);
}
int main()
{
solve();
return 0;
}
| 15.724138
| 57
| 0.541667
|
AmrARaouf
|
769bdd7f174ebb9828896a352014acc70c9af3c4
| 14,894
|
cpp
|
C++
|
app/uart/main.cpp
|
wrmlab/wrmos
|
37067b659aa25e2d85f040ab0d2be85b6f4de485
|
[
"MIT"
] | 16
|
2018-06-05T15:23:08.000Z
|
2022-01-06T13:41:44.000Z
|
app/uart/main.cpp
|
sergey-worm/wrmos
|
37067b659aa25e2d85f040ab0d2be85b6f4de485
|
[
"MIT"
] | null | null | null |
app/uart/main.cpp
|
sergey-worm/wrmos
|
37067b659aa25e2d85f040ab0d2be85b6f4de485
|
[
"MIT"
] | 3
|
2018-03-15T16:40:59.000Z
|
2021-04-01T22:55:15.000Z
|
//##################################################################################################
//
// uart - userspace UART driver.
//
//##################################################################################################
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "sys_utils.h"
#include "l4_api.h"
#include "wrmos.h"
#include "cbuf.h"
#define UART_WITH_VIDEO
#include "uart.h"
// one-directional stream
struct Stream_t
{
Cbuf_t cbuf; // circular buffer
Wrm_sem_t sem; // 'irq received' semaphore
};
// driver data
struct Driver_t
{
Stream_t tx; //
Stream_t rx; //
Wrm_mtx_t write_to_uart_mtx; //
addr_t ioaddr; //
};
static Driver_t driver;
int wait_attach_msg(const char* thread_name, L4_thrid_t* client)
{
// register thread by name
word_t key0 = 0;
word_t key1 = 0;
int rc = wrm_nthread_register(thread_name, &key0, &key1);
if (rc)
{
wrm_loge("attach: wrm_nthread_register(%s) - rc=%u.\n", thread_name, rc);
assert(false);
}
wrm_logi("attach: thread '%s' is registered, key: %lx/%lx.\n", thread_name, key0, key1);
L4_utcb_t* utcb = l4_utcb();
// wait attach msg loop
L4_thrid_t from = L4_thrid_t::Nil;
while (1)
{
wrm_logi("attach: wait attach msg.\n");
int rc = l4_receive(L4_thrid_t::Any, L4_time_t::Never, &from);
if (rc)
{
wrm_loge("attach: l4_receive() - rc=%u.\n", rc);
continue;
}
word_t ecode = 0;
L4_msgtag_t tag = utcb->msgtag();
word_t k0 = utcb->mr[1];
word_t k1 = utcb->mr[2];
if (tag.untyped() != 2 || tag.typed() != 0)
{
wrm_loge("attach: wrong msg format.\n");
ecode = 1;
}
if (!ecode && (k0 != key0 || k1 != key1))
{
wrm_loge("attach: wrong key.\n");
ecode = 2;
}
// send reply
tag.untyped(1);
tag.typed(0);
utcb->mr[0] = tag.raw();
utcb->mr[1] = ecode;
rc = l4_send(from, L4_time_t::Zero);
if (rc)
wrm_loge("attach: l4_send(rep) - rc=%d.\n", rc);
if (!ecode && !rc)
break; // attached
}
*client = from;
wrm_logi("attach: attached to %u.\n", from.number());
return 0;
}
// read from tx.cbuf and write to uart device
// this func may be called from hw-thread and tx-thread
void write_to_uart()
{
//wrm_logd("--: %s().\n", __func__);
uart_tx_irq(driver.ioaddr, 0); // disable tx irq
unsigned written = 0;
// NOTE: The best way is write to UART FIFO char-by-char through uart_putc()
// while fifo-is-not-full. But TopUART doesn't allow detect state
// fifo-is-not-full. Therefore, we use uart_put_buf() and write FIFO_SZ
// bytes. For most UARTs driver return FIFO_SZ=1 --> we will work
// as uart_putc() while fifo-is-not-full. For TopUART FIFO_SZ=64, every
// writing we put to UART FIFO_SZ bytes.
#if 0 // char-by-char
// write to uart char-by-char
wrm_mtx_lock(&driver.write_to_uart_mtx);
while (1)
{
static char txchar = 0;
static int is_there_unsent = 0;
// read charecter from tx-buffer if need
if (!is_there_unsent)
{
unsigned read = driver.tx.cbuf.read(&txchar, 1);
if (!read)
break;
is_there_unsent = 1;
}
// write charecter to uart
int rc = uart_putc(driver.ioaddr, txchar);
if (rc < 0)
{
wrm_loge("--: uart_put_buf() - rc=%d.\n", rc);
break; // uart tx empty
}
if (!rc)
{
wrm_logd("--: uart_tx_full, enable tx irq.\n");
uart_tx_irq(driver.ioaddr, 1);
break;
}
is_there_unsent = 0;
written++;
}
wrm_mtx_unlock(&driver.write_to_uart_mtx);
#else // put buf
unsigned fifo_sz = 0;
char buf[128];
fifo_sz = uart_fifo_size(driver.ioaddr);
assert(fifo_sz);
if (fifo_sz > sizeof(buf))
{
wrm_logw("--: fifo_sz/%u > bufsz/%zu, use %zu.\n", fifo_sz, sizeof(buf), sizeof(buf));
fifo_sz = sizeof(buf);
}
// write to uart fifo-by-fifo
wrm_mtx_lock(&driver.write_to_uart_mtx);
while (1)
{
if (!(uart_status(driver.ioaddr) & Uart_status_tx_ready) && !driver.tx.cbuf.empty())
{
//wrm_logd("--: uart_tx_not_ready, data exist -> enable tx irq.\n");
uart_tx_irq(driver.ioaddr, 1);
break;
}
// read charecters from tx-buffer if need
unsigned read = driver.tx.cbuf.read(buf, fifo_sz);
//wrm_logd("--: read from cbuf %d bytes.\n", read);
if (!read)
break; // no data anymore
// write charecter to uart
int rc = uart_put_buf(driver.ioaddr, buf, read);
if (rc < 0)
{
wrm_loge("--: uart_put_buf() - rc=%d.\n", rc);
break;
}
written += rc;
if (read != (unsigned) rc)
{
wrm_loge("--: uart_put_buf() - wr=%u, lost %u bytes.\n", read, read - rc);
break;
}
}
wrm_mtx_unlock(&driver.write_to_uart_mtx);
#endif
//wrm_logd("--: written=%u.\n", written);
}
size_t put_to_txbuf(const char* buf, unsigned sz)
{
// put line by line and add '\r'
unsigned written = 0;
while (written < sz)
{
const char* pos = buf + written;
const char* end = strchr(pos, '\n');
unsigned l = end ? (end + 1 - pos) : (sz - written); // length for line or tail
// write all line
unsigned wr = driver.tx.cbuf.write(pos, l);
written += wr;
if (wr != l)
{
wrm_loge("tx: buffer full, write=%u, written=%u, lost=%u.\n", l, wr, l - wr);
break; // buf full
}
if (end)
{
wr = driver.tx.cbuf.write("\r", 1);
if (wr != 1)
{
wrm_loge("tx: buffer full, write=1, written=%u.\n", wr);
break; // buf full
}
}
}
return written;
}
long tx_thread(long unused)
{
wrm_logi("tx: hello: %s.\n", __func__);
wrm_logi("tx: myid=%u.\n", l4_utcb()->global_id().number());
// wait for attach message
L4_thrid_t client = L4_thrid_t::Nil;
int rc = wait_attach_msg("uart-tx-stream", &client);
if (rc)
{
wrm_loge("tx: wait_attach_msg() - rc=%d.\n", rc);
assert(false);
}
wrm_logi("tx: attached to client=%u\n", client.number());
// prepare for requests
L4_utcb_t* utcb = l4_utcb();
static char tx_buf[0x1000];
L4_acceptor_t acceptor = L4_acceptor_t::create(L4_fpage_t::create_nil(), true); // allow strings
L4_string_item_t bitem = L4_string_item_t::create_simple((word_t)tx_buf, sizeof(tx_buf)-1);
utcb->br[0] = acceptor.raw();
utcb->br[1] = bitem.word0();
utcb->br[2] = bitem.word1();
// wait request loop
while (1)
{
//wrm_logi("tx: wait request.\n");
L4_thrid_t from = L4_thrid_t::Nil;
int rc = l4_receive(client, L4_time_t::Never, &from);
if (rc)
{
wrm_loge("tx: l4_receive() - rc=%u.\n", rc);
assert(false);
}
L4_msgtag_t tag = utcb->msgtag();
word_t mr[L4_utcb_t::Mr_words];
memcpy(mr, utcb->mr, (1 + tag.untyped() + tag.typed()) * sizeof(word_t));
from = tag.propagated() ? utcb->sender() : from;
//wrm_logi("tx: received: from=%u, tag=0x%x, u=%u, t=%u, mr[1]=0x%x, mr[2]=0x%x.\n",
// from.number(), tag.raw(), tag.untyped(), tag.typed(), mr[1], mr[2]);
L4_typed_item_t item = L4_typed_item_t::create(mr[1], mr[2]);
L4_string_item_t sitem = L4_string_item_t::create(mr[1], mr[2]);
assert(tag.untyped() == 0);
assert(tag.typed() == 2);
assert(item.is_string_item());
//wrm_logi("tx: request is got: sz=%u.\n", sitem.length());
//wrm_logi("tx: request is got: buf=0x%x, sz=%u, txbf=0x%p: %.*s.\n",
// sitem.pointer(), sitem.length(), tx_buf, sitem.length(), (char*)sitem.pointer());
((char*)sitem.pointer())[sitem.length()] = '\0'; // add terminator
unsigned written = put_to_txbuf((char*)sitem.pointer(), sitem.length());
if (written != sitem.length())
{
wrm_loge("tx: buffer full, write=%u, written=%u, lost=%u.\n",
sitem.length(), written, sitem.length() - written);
}
//wrm_logd("tx: written=%u to cbuf.\n", written);
if (written)
{
write_to_uart();
}
// send reply to client
tag.propagated(false);
tag.ipc_label(0);
tag.untyped(2);
tag.typed(0);
utcb->mr[0] = tag.raw();
utcb->mr[1] = rc; // ecode
utcb->mr[2] = written; // bytes written
rc = l4_send(from, L4_time_t::Zero);
if (rc)
{
wrm_loge("l4_send(rep) - rc=%u.\n", rc);
l4_kdb("tx: l4_send(cli) is failed");
}
}
return 0;
}
long rx_thread(long unused)
{
wrm_logi("rx: hello: %s.\n", __func__);
wrm_logi("rx: myid=%u.\n", l4_utcb()->global_id().number());
// wait for attach message
L4_thrid_t client = L4_thrid_t::Nil;
int rc = wait_attach_msg("uart-rx-stream", &client);
if (rc)
{
wrm_loge("rx: wait_attach_msg() - rc=%u.\n", rc);
assert(false);
}
wrm_logi("rx: attached to client=%u\n", client.number());
// prepare for requests
L4_utcb_t* utcb = l4_utcb();
static char rx_buf[0x1000];
L4_acceptor_t acceptor = L4_acceptor_t::create(L4_fpage_t::create_nil(), false);
utcb->br[0] = acceptor.raw();
// wait request loop
while (1)
{
//wrm_logi("rx: wait request.\n");
L4_thrid_t from = L4_thrid_t::Nil;
int rc = l4_receive(client, L4_time_t::Never, &from);
L4_msgtag_t tag = utcb->msgtag();
if (rc)
{
wrm_loge("rx: l4_receive() - rc=%u.\n", rc);
assert(false);
}
word_t mr[256];
memcpy(mr, utcb->mr, (1 + tag.untyped() + tag.typed()) * sizeof(word_t));
from = tag.propagated() ? utcb->sender() : from;
//wrm_logi("rx: received ipc: from=%u, tag=0x%lx, u=%u, t=%u, mr[1]=0x%lx, mr[2]=0x%lx.\n",
// from.number(), tag.raw(), tag.untyped(), tag.typed(), mr[1], mr[2]);
assert(tag.untyped() == 1);
assert(tag.typed() == 0);
size_t cli_bfsz = mr[1];
size_t read = 0;
while (1)
{
read = driver.rx.cbuf.read(rx_buf, min(sizeof(rx_buf), cli_bfsz));
if (read)
break;
rc = wrm_sem_wait(&driver.rx.sem); // wait rx operation
if (rc)
{
wrm_loge("wrm_sem_wait(rx) - rc=%d.\n", rc);
rc = -1;
break;
}
}
//wrm_logi("rx: read=%u.\n", read);
// send reply to client
L4_string_item_t sitem = L4_string_item_t::create_simple((word_t)rx_buf, read);
tag.propagated(false);
tag.ipc_label(0); // ?
tag.untyped(1);
tag.typed(2);
utcb->mr[0] = tag.raw();
utcb->mr[1] = rc; // ecode
utcb->mr[2] = sitem.word0(); //
utcb->mr[3] = sitem.word1(); //
rc = l4_send(from, L4_time_t::Zero);
if (rc)
{
wrm_loge("l4_send(rep) - rc=%u.\n", rc);
l4_kdb("rx: l4_send(cli) is failed");
}
}
return 0;
}
void read_from_uart()
{
char buf[64];
unsigned read = 0;
while (1)
{
// read data from uart
unsigned rd = 0;
char ch = 0;
while (rd < sizeof(buf) && (ch = uart_getc(driver.ioaddr)))
buf[rd++] = ch;
//wrm_logd("hw: read from uart %d bytes.\n", rc);
//wrm_logd("hw: rx(%u): '%.*s' (rx=%u, tx=%u all=%u)\n",
// rc, rc, buf, cnt_rx, cnt_tx, cnt_all);
read += rd;
if (!rd)
break;
// write data to rx-buffer
unsigned written = driver.rx.cbuf.write(buf, rd);
if (written != rd)
{
wrm_loge("hw: rx_buf full, lost %u bytes.\n", rd - written);
break;
}
//wrm_logi("post rx sem.\n");
int rc = wrm_sem_post(&driver.rx.sem);
if (rc)
wrm_loge("hw: wrm_sem_post(rx.sem) - rc=%d.\n", rc);
}
if (!read)
wrm_loge("hw: no data for read in uart.\n");
}
void irq_thread(const char* uart_dev_name)
{
// rename main thread
memcpy(&l4_utcb()->tls[0], "u-hw", 4);
// attach to IRQ
unsigned intno = -1;
int rc = wrm_dev_attach_int(uart_dev_name, &intno);
wrm_logi("attach_int: dev=%s, irq=%u.\n", uart_dev_name, intno);
if (rc)
{
wrm_loge("wrm_dev_attach_int() - rc=%d.\n", rc);
return;
}
uart_rx_irq(driver.ioaddr, 1);
unsigned icnt_rx = 0;
unsigned icnt_tx = 0;
unsigned icnt_all = 0;
unsigned icnt_nil = 0;
// wait interrupt loop
while (1)
{
// wait interrupt
//wrm_logd("hw: wait interrupt ... (irq: rx/tx/all/nil=%u/%u/%u/%u).\n",
// icnt_rx, icnt_tx, icnt_all, icnt_nil);
rc = wrm_dev_wait_int(intno, Uart_need_ack_irq_before_reenable);
assert(!rc);
icnt_all++;
unsigned loop_cnt = 0;
while (1)
{
int status = uart_status(driver.ioaddr);
int tx_ready = !!(status & Uart_status_tx_ready);
int rx_ready = !!(status & Uart_status_rx_ready);
int tx_irq = !!(status & Uart_status_tx_irq);
int rx_irq = !!(status & Uart_status_rx_irq);
//wrm_logd("hw: status: loop=%u: ready_rx/tx=%d/%d, irq_rx/tx=%d/%d.\n",
// loop_cnt, rx_ready, tx_ready, rx_irq, tx_irq);
if (!rx_irq && !tx_irq)
{
// we got real irq but UART hasn't interrupt inside int_status register
//wrm_loge("hw: no irq: loop=%u: ready_rx/tx=%d/%d, irq_rx/tx=%d/%d.\n",
// loop_cnt, rx_ready, tx_ready, rx_irq, tx_irq);
icnt_nil++;
break;
}
if (rx_irq)
icnt_rx++;
if (tx_irq)
icnt_tx++;
if (rx_ready)
read_from_uart();
if (tx_ready)
write_to_uart();
loop_cnt++;
int need_check_status = uart_clear_irq(driver.ioaddr);
if (!need_check_status)
break;
}
}
}
int main(int argc, const char* argv[])
{
wrm_logi("hello.\n");
wrm_logi("argc=%d, argv=0x%p.\n", argc, argv);
for (int i=0; i<argc; i++)
wrm_logi("arg[%d] = %s.\n", i, argv[i]);
wrm_logi("myid=%u.\n", l4_utcb()->global_id().number());
// map IO
const char* uart_dev_name = argc>=2 ? argv[1] : "";
addr_t ioaddr = -1;
size_t iosize = -1;
int rc = wrm_dev_map_io(uart_dev_name, &ioaddr, &iosize);
if (rc)
{
wrm_loge("wrm_dev_map_io() - rc=%d.\n", rc);
return -1;
}
wrm_logi("map_io: addr=0x%lx, sz=0x%zx.\n", ioaddr, iosize);
driver.ioaddr = ioaddr;
static char rx_buf[0x1000];
static char tx_buf[0x2000];
driver.rx.cbuf.init(rx_buf, sizeof(rx_buf));
driver.tx.cbuf.init(tx_buf, sizeof(tx_buf));
rc = wrm_sem_init(&driver.rx.sem, Wrm_sem_binary, 0);
if (rc)
{
wrm_loge("wrm_sem_init(rx.sem) - rc=%d.", rc);
return -2;
}
rc = wrm_mtx_init(&driver.write_to_uart_mtx);
if (rc)
{
wrm_loge("wrm_mtx_init(write_to_uart_mtx) - rc=%d.", rc);
return -3;
}
// I do not known sys_freq.
// Do not init, I hope uart was initialized by kernel.
// uart_init(ioaddr, 115200, 40*1000*1000/*?*/);
// create tx thread
L4_fpage_t stack_fp = wrm_pgpool_alloc(Cfg_page_sz);
L4_fpage_t utcb_fp = wrm_pgpool_alloc(Cfg_page_sz);
assert(!stack_fp.is_nil());
assert(!utcb_fp.is_nil());
L4_thrid_t txid = L4_thrid_t::Nil;
rc = wrm_thr_create(utcb_fp, tx_thread, 0, stack_fp.addr(), stack_fp.size(), 255,
"u-tx", Wrm_thr_flag_no, &txid);
wrm_logi("create_thread: rc=%d, id=%u.\n", rc, txid.number());
if (rc)
{
wrm_loge("wrm_thr_create(tx) - rc=%d.", rc);
return -4;
}
// create rx thread
stack_fp = wrm_pgpool_alloc(Cfg_page_sz);
utcb_fp = wrm_pgpool_alloc(Cfg_page_sz);
assert(!stack_fp.is_nil());
assert(!utcb_fp.is_nil());
L4_thrid_t rxid = L4_thrid_t::Nil;
rc = wrm_thr_create(utcb_fp, rx_thread, 0, stack_fp.addr(), stack_fp.size(), 255,
"u-rx", Wrm_thr_flag_no, &rxid);
wrm_logi("create_thread: rc=%d, id=%u.\n", rc, rxid.number());
if (rc)
{
wrm_loge("wrm_thr_create(rx) - rc=%d.\n", rc);
return -5;
}
irq_thread(uart_dev_name);
wrm_loge("return from app uart - something going wrong.\n");
return 0;
}
| 24.864775
| 100
| 0.606889
|
wrmlab
|
769cf243a888d3bcc6809d48babe1b071ff489e7
| 319
|
cpp
|
C++
|
WumbukDraw/staticimage.cpp
|
YangPeihao1203/WumbukDraw
|
e0854e62cc050c99deda04a849d46824f458cbbc
|
[
"MIT"
] | null | null | null |
WumbukDraw/staticimage.cpp
|
YangPeihao1203/WumbukDraw
|
e0854e62cc050c99deda04a849d46824f458cbbc
|
[
"MIT"
] | null | null | null |
WumbukDraw/staticimage.cpp
|
YangPeihao1203/WumbukDraw
|
e0854e62cc050c99deda04a849d46824f458cbbc
|
[
"MIT"
] | null | null | null |
#include "staticimage.h"
StaticImage::StaticImage()
{
}
void StaticImage::inSertPicture(QString filePath,QGraphicsScene *parent)
{
QPixmap pixmap =QPixmap::fromImage(QImage(filePath));
this->setPixmap(pixmap);
setFlag(QGraphicsItem::ItemIsMovable);
}
| 19.9375
| 73
| 0.623824
|
YangPeihao1203
|
371dbadc8e93569fead136aa3ca52d43f1fe2f8f
| 1,522
|
cpp
|
C++
|
pepnovo/src/QuickClustering.cpp
|
compomics/jwrapper-pepnovo
|
1bd21a4910d7515dfab7747711917176a6b5ce99
|
[
"Apache-2.0"
] | null | null | null |
pepnovo/src/QuickClustering.cpp
|
compomics/jwrapper-pepnovo
|
1bd21a4910d7515dfab7747711917176a6b5ce99
|
[
"Apache-2.0"
] | null | null | null |
pepnovo/src/QuickClustering.cpp
|
compomics/jwrapper-pepnovo
|
1bd21a4910d7515dfab7747711917176a6b5ce99
|
[
"Apache-2.0"
] | null | null | null |
#include "QuickClustering.h"
#include "PMCSQS.h"
#include "auxfun.h"
// the sim matrix stores the similarity distances computed between clusters
int num_sim_matrix_spectra = 0;
unsigned char * sim_matrix = NULL;
unsigned char * max_sim_addr = NULL;
void print_byte(unsigned char byte)
{
int i;
unsigned char mask=0X1;
for (i=0; i<8; i++)
{
cout << ( (byte & mask) ? '1' : '0');
mask <<= 1;
}
}
void mark_bit_zero(unsigned char *addr, int position)
{
const unsigned char ANDmasks[]={254,253,251,247,239,223,191,127};
int bit_offset = (position & 0X7);
int byte_offset = (position >> 3);
*(addr+byte_offset) &= ANDmasks[bit_offset];
}
void mark_bit_one(unsigned char *addr, int position)
{
const unsigned char ORmasks[] ={1,2,4,8,16,32,64,128};
int bit_offset = (position & 0X7);
int byte_offset = (position >> 3);
*(addr+byte_offset) |= ORmasks[bit_offset];
}
// returns full int assumes we are at position 31 in the 4 bytes
int get_matrix_32_bits(unsigned char *row_start, int position)
{
int cell_off = (position >> 5);
return (*((int *)row_start+cell_off));
// return 1;
}
int get_matrix_val(unsigned char *row_start, int position)
{
const unsigned char masks[] ={1,2,4,8,16,32,64,128};
int bit_offset = (position & 0X7);
int byte_offset = (position >> 3);
return ((*(row_start+byte_offset) & masks[bit_offset]));
// return 1;
}
// global debugging variable
int wrongly_filtered_spectra;
| 20.293333
| 76
| 0.65046
|
compomics
|
372164b0b94deb130806f24ae1c6cf3f7bc02514
| 2,280
|
cpp
|
C++
|
src/stmt.cpp
|
magicmoremagic/bengine-sqlite
|
4e777cbbca9e64be5c49a24778847bf8e23fd99d
|
[
"MIT"
] | null | null | null |
src/stmt.cpp
|
magicmoremagic/bengine-sqlite
|
4e777cbbca9e64be5c49a24778847bf8e23fd99d
|
[
"MIT"
] | null | null | null |
src/stmt.cpp
|
magicmoremagic/bengine-sqlite
|
4e777cbbca9e64be5c49a24778847bf8e23fd99d
|
[
"MIT"
] | null | null | null |
#include "pch.hpp"
#include "stmt.hpp"
#include "db.hpp"
#include "result_code.hpp"
#include "sqlite.hpp"
#include <cassert>
#include <limits>
namespace be::sqlite {
///////////////////////////////////////////////////////////////////////////////
/// \brief Compiles the provided SQL query against the provided database and
/// constructs a Stmt object to represent it.
///
/// \details A statement Id will be generated automatically by hashing the
/// SQL text provided.
///
/// \note The lifetime of the provided Db object must extend beyond the end
/// of the newly created Stmt object.
///
/// \param db The database on which the statement is to be executed.
/// \param sql The SQL text of the statement to compile.
Stmt::Stmt(Db& db, const S& sql)
: Stmt(db, Id(sql), sql) { }
///////////////////////////////////////////////////////////////////////////////
/// \brief Compiles the provided SQL query against the provided database and
/// constructs a Stmt object to represent it using the provided ID.
///
/// \note The lifetime of the provided Db object must extend beyond the end
/// of the newly created Stmt object.
///
/// \param db The database on which the statement is to be executed.
/// \param id The Id of the statement.
/// \param sql The SQL text of the statement to compile.
Stmt::Stmt(Db& db, Id id, const S& sql) {
sqlite3_stmt* stmt = nullptr;
const char* tail = nullptr;
const char* start = sql.c_str();
const char* end = start + sql.length();
assert(sql.length() + 1 < static_cast<std::size_t>(std::numeric_limits<int>::max()));
int result = sqlite3_prepare_v2(db.raw(), start, static_cast<int>(sql.length() + 1), &stmt, &tail);
if (result != SQLITE_OK || !stmt) {
throw SqlTrace(db.raw(), ext_result_code(result), sql);
} else if (tail && tail < end) {
throw SqlTrace(ExtendedResultCode::api_misuse, "Multiple SQL statements provided to Stmt constructor!", sql);
} else {
stmt_ptr_ = sqlite3_stmt_ptr(stmt);
stmt_ = stmt;
con_ = db.raw();
id_ = id;
}
}
///////////////////////////////////////////////////////////////////////////////
void Stmt::deleter::operator()(sqlite3_stmt* stmt) {
sqlite3_finalize(stmt);
}
} // be::sqlite
| 37.377049
| 115
| 0.59386
|
magicmoremagic
|
3721ef1e6c9619445cf4d06c28898e68e94f01de
| 7,611
|
cpp
|
C++
|
library/Custom/fastIO.cpp
|
sarafanshul/KACTL
|
fa14ed34e93cd32d8625ed3729ba2eee55838340
|
[
"MIT"
] | 4
|
2021-01-05T09:25:59.000Z
|
2021-09-27T03:57:28.000Z
|
library/Custom/fastIO.cpp
|
sarafanshul/KACTL
|
fa14ed34e93cd32d8625ed3729ba2eee55838340
|
[
"MIT"
] | null | null | null |
library/Custom/fastIO.cpp
|
sarafanshul/KACTL
|
fa14ed34e93cd32d8625ed3729ba2eee55838340
|
[
"MIT"
] | null | null | null |
#ifndef CUST_DEBUG
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("unroll-loops")
#endif
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ALL(x) x.begin(),x.end()
#define PB push_back
#define F first
#define S second
#define ll long long
#define double long double
#define MP make_pair
using namespace std;
template <typename K, typename V = __gnu_pbds::null_type>
using tree = __gnu_pbds::tree<K, V, less<K>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>;
using llong = long long;
auto isz = [](const auto& c) { return int(c.size()); };
mt19937 rng((size_t) make_shared<char>().get());
#ifndef _LIB_FASTIO_
#define _LIB_FASTIO_
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wextra"
#pragma GCC diagnostic ignored "-Wconversion"
/** Fast allocation */
#ifdef FAST_ALLOCATOR_MEMORY
int allocator_pos = 0;
char allocator_memory[(int)FAST_ALLOCATOR_MEMORY];
inline void * operator new ( size_t n ) {
char *res = allocator_memory + allocator_pos;
allocator_pos += n;
assert(allocator_pos <= (int)FAST_ALLOCATOR_MEMORY);
return (void *)res;
}
inline void operator delete ( void * ) noexcept { }
//inline void * operator new [] ( size_t ) { assert(0); }
//inline void operator delete [] ( void * ) { assert(0); }
#endif
/** Fast input-output */
/** Read */
static const int buf_size = 4096;
static unsigned char buf[buf_size];
static int buf_len = 0, buf_pos = 0;
inline bool isEof() {
if (buf_pos == buf_len) {
buf_pos = 0, buf_len = fread(buf, 1, buf_size, stdin);
if (buf_pos == buf_len)
return 1;
}
return 0;
}
inline int getChar() {
return isEof() ? -1 : buf[buf_pos++];
}
inline int peekChar() {
return isEof() ? -1 : buf[buf_pos];
}
inline bool seekEof() {
int c;
while ((c = peekChar()) != -1 && c <= 32)
buf_pos++;
return c == -1;
}
inline void skipBlanks() {
while (!isEof() && buf[buf_pos] <= 32U)
buf_pos++;
}
inline int readChar() {
int c = getChar();
while (c != -1 && c <= 32)
c = getChar();
return c;
}
inline unsigned int readUInt() {
int c = readChar();
unsigned int x = 0;
while ('0' <= c && c <= '9')
x = x * 10 + c - '0', c = getChar();
return x;
}
template <class T = int>
inline T readInt() {
int s = 1, c = readChar();
T x = 0;
if (c == '-')
s = -1, c = getChar();
else if (c == '+')
c = getChar();
while ('0' <= c && c <= '9')
x = x * 10 + c - '0', c = getChar();
return s == 1 ? x : -x;
}
inline long long readLong() {
return readInt<long long>();
}
inline double readDouble() {
int s = 1, c = readChar();
double x = 0;
if (c == '-')
s = -1, c = getChar();
while ('0' <= c && c <= '9')
x = x * 10 + c - '0', c = getChar();
if (c == '.') {
c = getChar();
double coef = 1;
while ('0' <= c && c <= '9')
x += (c - '0') * (coef *= 1e-1), c = getChar();
}
return s == 1 ? x : -x;
}
inline void readWord(char *s) {
int c = readChar();
while (c > 32)
*s++ = c, c = getChar();
*s = 0;
}
inline void readWord(string &s) {
s.clear();
int c = readChar();
while (c > 32)
s += c, c = getChar();
}
inline bool readLine(char *s) {
int c = getChar();
while (c != '\n' && c != -1)
*s++ = c, c = getChar();
*s = 0;
return c != -1;
}
inline bool readLine(string &s) {
s.clear();
int c = getChar();
while (c != '\n' && c != -1)
s += c, c = getChar();
return c != -1;
}
/** Write */
static int write_buf_pos = 0;
static char write_buf[buf_size];
inline void writeChar(int x) {
if (write_buf_pos == buf_size)
fwrite(write_buf, 1, buf_size, stdout), write_buf_pos = 0;
write_buf[write_buf_pos++] = x;
}
inline void flush() {
if (write_buf_pos) {
fwrite(write_buf, 1, write_buf_pos, stdout), write_buf_pos = 0;
fflush(stdout);
}
}
template <class T>
inline void writeInt(T x, char end = 0, int output_len = -1) {
if (x < 0)
writeChar('-'), x = -x;
char s[24];
int n = 0;
while (x || !n)
s[n++] = '0' + x % 10, x /= 10;
while (n < output_len)
s[n++] = '0';
while (n--)
writeChar(s[n]);
if (end)
writeChar(end);
}
inline void writeWord(const char *s) {
while (*s)
writeChar(*s++);
}
inline void writeWord(const string& s) {
writeWord(s.c_str());
}
inline void writeDouble(double x, int output_len = 11) {
if (x < 0)
writeChar('-'), x = -x;
int t = (int)x;
writeInt(t), x -= t;
writeChar('.');
for (int i = output_len - 1; i > 0; i--) {
x *= 10;
t = std::min(9, (int)x);
writeChar('0' + t), x -= t;
}
x *= 10;
t = std::min(9, (int)(x + 0.5));
writeChar('0' + t);
}
/** Buffer flusher */
static struct buffer_flusher_t {
~buffer_flusher_t() {
flush();
}
} buffer_flusher;
/** Reader and writer */
struct fast_reader {
fast_reader& operator>>(int& n) {
n = readInt(); return *this;
}
fast_reader& operator>>(unsigned int& n) {
n = readUInt(); return *this;
}
fast_reader& operator>>(llong& n) {
n = readLong(); return *this;
}
fast_reader& operator>>(double& n) {
n = readDouble(); return *this;
}
fast_reader& operator>>(float& n) {
n = (float) readDouble(); return *this;
}
fast_reader& operator>>(string& s) {
readWord(s); return *this;
}
fast_reader& operator>>(char& c) {
c = (char) readChar(); return *this;
}
template<typename T>
fast_reader& operator>>(vector<T>& a) {
for (T& i : a) {
(*this) >> i;
}
return *this;
}
} f_reader;
struct fast_writer {
template<typename T>
fast_writer& operator<<(T n) {
writeInt(n); return *this;
}
fast_writer& operator<<(double n) {
writeDouble(n); return *this;
}
fast_writer& operator<<(float n) {
writeDouble(n); return *this;
}
fast_writer& operator<<(const string& s) {
writeWord(s); return *this;
}
fast_writer& operator<<(const char* s) {
writeWord(s); return *this;
}
fast_writer& operator<<(char c) {
writeChar(c); return *this;
}
template<typename T>
fast_writer& operator<<(const vector<T>& a) {
for (size_t i = 0; i < a.size(); ++i) {
if (i) {
(*this) << ' ';
}
(*this) << a[i];
}
return *this;
}
void flush() {
::flush();
}
} f_writer;
#define cin f_reader
#define cout f_writer
#pragma GCC diagnostic pop
#endif //_LIB_FASTIO_
#ifndef _LIB_UTILS_
#define _LIB_UTILS_
template <typename T, T val = T()>
auto make_vector(size_t d) {
return vector<T>(d, val);
}
template <typename T, T val = T(), typename ...Ds>
auto make_vector(size_t d, Ds... ds) {
return vector<decltype(make_vector<T, val>(ds...))>(d, make_vector<T, val>(ds...));
}
#endif //_LIB_UTILS_
#ifdef CUST_DEBUG
template<class K, class V>ostream& operator<<(ostream&s,const pair<K,V>&p){s<<'<'<<p.F<<','<<p.S<<'>';return s;}
template<class T, class=typename T::value_type, class=typename enable_if<!is_same<T,string>::value>::type>
ostream& operator<<(ostream&s,const T&v){s<<'[';for(auto&x:v){s<<x<<", ";}if(!v.empty()){s<<"\b\b";}s<<']';return s;}
void __prnt(){cerr<<endl;} template<class T, class...Ts>void __prnt(T&&a,Ts&&...etc){cerr<<a<<' ';__prnt(etc...);}
#define print(...) __prnt(__VA_ARGS__)
#else
#define print(...)
#endif
const long long MAXN = 1e5 +7;
void check(){
}
int32_t main(){
int t = 1;
// cin >> t;
for(int i = 1 ; i <= t ;i++){ check(); }
return 0;
}
| 22.189504
| 117
| 0.581658
|
sarafanshul
|
3722de4415fda998571a8d968689831478fc0bf1
| 43
|
hpp
|
C++
|
src/boost_mpl_aux__type_wrapper.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_mpl_aux__type_wrapper.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_mpl_aux__type_wrapper.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/mpl/aux_/type_wrapper.hpp>
| 21.5
| 42
| 0.790698
|
miathedev
|
372398f052543364536b3337a1043e781c804f22
| 7,932
|
cpp
|
C++
|
src/Modules/UI/Macro Elements/Options_Graphics.cpp
|
Yattabyte/reVision
|
014cb450d1c30b8f64abbacf00425b4f814b05a0
|
[
"MIT"
] | 5
|
2018-10-12T17:40:17.000Z
|
2020-11-20T10:49:34.000Z
|
src/Modules/UI/Macro Elements/Options_Graphics.cpp
|
Yattabyte/reVision
|
014cb450d1c30b8f64abbacf00425b4f814b05a0
|
[
"MIT"
] | 71
|
2018-07-19T01:59:38.000Z
|
2020-03-29T18:03:13.000Z
|
src/Modules/UI/Macro Elements/Options_Graphics.cpp
|
Yattabyte/reVision
|
014cb450d1c30b8f64abbacf00425b4f814b05a0
|
[
"MIT"
] | 1
|
2022-03-24T13:21:25.000Z
|
2022-03-24T13:21:25.000Z
|
#include "Modules/UI/Macro Elements/Options_Graphics.h"
#include "Modules/UI/Basic Elements/Slider.h"
#include "Modules/UI/Basic Elements/SideList.h"
#include "Modules/UI/Basic Elements/Toggle.h"
#include "Engine.h"
Options_Graphics::Options_Graphics(Engine& engine) :
Options_Pane(engine)
{
// Title
m_title->setText("Graphics Options");
// Material Size Option
float materialSize = 1024;
engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_MATERIAL_SIZE, materialSize);
auto element_material_list = std::make_shared<SideList>(engine);
element_material_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" });
m_materialSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F };
int counter = 0;
int index = 0;
for (const auto& size : m_materialSizes) {
if (materialSize == size)
index = counter;
counter++;
}
element_material_list->setIndex(index);
addOption(engine, element_material_list, 1.0F, "Texture Quality:", "Adjusts the resolution of in-game geometry textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_material_list]() { setTextureResolution(element_material_list->getIndex()); });
// Shadow Size Option
float shadowSize = 1024;
engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_SHADOW_SIZE, shadowSize);
auto element_shadow_list = std::make_shared<SideList>(engine);
element_shadow_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" });
m_shadowSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F };
counter = 0;
index = 0;
for (const auto& size : m_shadowSizes) {
if (shadowSize == size)
index = counter;
counter++;
}
element_shadow_list->setIndex(index);
addOption(engine, element_shadow_list, 1.0F, "Shadow Quality:", "Adjusts the resolution of all dynamic light shadows textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_shadow_list]() { setShadowSize(element_shadow_list->getIndex()); });
// Reflection Size Option
float envSize = 1024;
engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_ENVMAP_SIZE, envSize);
auto element_env_list = std::make_shared<SideList>(engine);
element_env_list->setStrings({ "Low", "Medium", "High", "Very High", "Ultra" });
m_reflectionSizes = { 128.0F, 256.0F, 512.0F, 1024.0F, 2048.0F };
counter = 0;
index = 0;
for (const auto& size : m_reflectionSizes) {
if (envSize == size)
index = counter;
counter++;
}
element_env_list->setIndex(index);
addOption(engine, element_env_list, 1.0F, "Reflection Quality:", "Adjusts the resolution of all environment map textures.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_env_list]() { setReflectionSize(element_env_list->getIndex()); });
// Light Bounce Option
float bounceSize = 1024;
engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_RH_BOUNCE_SIZE, bounceSize);
auto element_bounce_list = std::make_shared<SideList>(engine);
element_bounce_list->setStrings({ "Very Low", "Low", "Medium", "High", "Very High", "Ultra" });
m_bounceQuality = { 8, 12, 16, 24, 32, 64 };
counter = 0;
index = 0;
for (const auto& size : m_bounceQuality) {
if (bounceSize == size)
index = counter;
counter++;
}
element_bounce_list->setIndex(index);
addOption(engine, element_bounce_list, 1.0F, "Light Bounce Quality:", "Adjusts the resolution of the real-time GI simulation.", static_cast<int>(SideList::Interact::on_index_changed), [&, element_bounce_list]() { setBounceQuality(element_bounce_list->getIndex()); });
// Shadow Count Option
float maxShadowCasters = 6.0F;
engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_SHADOW_MAX_PER_FRAME, maxShadowCasters);
auto maxShadow_slider = std::make_shared<Slider>(engine, maxShadowCasters, glm::vec2(1.0F, 100.0F));
addOption(engine, maxShadow_slider, 0.75F, "Max Concurrent Shadows:", "Set the maximum number of shadows updated per frame.", static_cast<int>(Slider::Interact::on_value_change), [&, maxShadow_slider]() {
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SHADOW_MAX_PER_FRAME, maxShadow_slider->getValue());
});
// Envmap Count Option
float maxReflectionCasters = 6.0F;
engine.getPreferenceState().getOrSetValue(PreferenceState::Preference::C_ENVMAP_MAX_PER_FRAME, maxReflectionCasters);
auto maxReflection_slider = std::make_shared<Slider>(engine, maxReflectionCasters, glm::vec2(1.0F, 100.0F));
addOption(engine, maxReflection_slider, 0.75F, "Max Concurrent Reflections:", "Set the maximum number of reflections updated per frame.", static_cast<int>(Slider::Interact::on_value_change), [&, maxReflection_slider]() {
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_ENVMAP_MAX_PER_FRAME, maxReflection_slider->getValue());
});
// Bloom Option
bool element_bloom_state = true;
engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_BLOOM, element_bloom_state);
auto element_bloom = std::make_shared<Toggle>(engine, element_bloom_state);
addOption(engine, element_bloom, 0.5F, "Bloom:", "Turns the bloom effect on or off.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_bloom]() { setBloom(element_bloom->isToggled()); });
// SSAO Option
bool element_ssao_state = true;
engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_SSAO, element_ssao_state);
auto element_ssao = std::make_shared<Toggle>(engine, element_ssao_state);
addOption(engine, element_ssao, 0.5F, "SSAO:", "Turns screen-space ambient occlusion effect on or off. Works with baked AO.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_ssao]() { setSSAO(element_ssao->isToggled()); });
// SSR Option
bool element_ssr_state = true;
engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_SSR, element_ssr_state);
auto element_ssr = std::make_shared<Toggle>(engine, element_ssr_state);
addOption(engine, element_ssr, 0.5F, "SSR:", "Turns screen-space reflections on or off. Works with baked reflections.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_ssr]() { setSSR(element_ssr->isToggled()); });
// FXAA Option
bool element_fxaa_state = true;
engine.getPreferenceState().getOrSetValue<bool>(PreferenceState::Preference::C_FXAA, element_fxaa_state);
auto element_fxaa = std::make_shared<Toggle>(engine, element_fxaa_state);
addOption(engine, element_fxaa, 0.5F, "FXAA:", "Turns fast approximate anti-aliasing on or off.", static_cast<int>(Toggle::Interact::on_toggle), [&, element_fxaa]() { setFXAA(element_fxaa->isToggled()); });
}
void Options_Graphics::setTextureResolution(const size_t& index)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_MATERIAL_SIZE, m_materialSizes[index]);
}
void Options_Graphics::setShadowSize(const size_t& index)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SHADOW_SIZE, m_shadowSizes[index]);
}
void Options_Graphics::setReflectionSize(const size_t& index)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_ENVMAP_SIZE, m_reflectionSizes[index]);
}
void Options_Graphics::setBounceQuality(const size_t& index)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_RH_BOUNCE_SIZE, m_bounceQuality[index]);
}
void Options_Graphics::setBloom(const bool& b)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_BLOOM, b ? 1.0F : 0.0F);
}
void Options_Graphics::setSSAO(const bool& b)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SSAO, b ? 1.0F : 0.0F);
}
void Options_Graphics::setSSR(const bool& b)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_SSR, b ? 1.0F : 0.0F);
}
void Options_Graphics::setFXAA(const bool& b)
{
m_engine.getPreferenceState().setValue(PreferenceState::Preference::C_FXAA, b ? 1.0F : 0.0F);
}
| 50.522293
| 271
| 0.757186
|
Yattabyte
|
3726cc4dcad99bf88a8ef4a4fd269dd02625331c
| 3,951
|
cc
|
C++
|
verilog/analysis/checkers/disable_statement_rule_test.cc
|
imphil/verible
|
cc9ec78b29e2e0190f6244a7d8981a2a90d77d79
|
[
"Apache-2.0"
] | 487
|
2019-11-07T02:16:12.000Z
|
2021-07-08T14:44:12.000Z
|
verilog/analysis/checkers/disable_statement_rule_test.cc
|
hzeller/verible
|
c926ededf7953febb5f577b081474987d0f0209d
|
[
"Apache-2.0"
] | 704
|
2019-11-12T18:00:12.000Z
|
2021-07-08T08:21:31.000Z
|
verilog/analysis/checkers/disable_statement_rule_test.cc
|
hzeller/verible
|
c926ededf7953febb5f577b081474987d0f0209d
|
[
"Apache-2.0"
] | 96
|
2019-11-12T06:21:03.000Z
|
2021-07-06T23:20:39.000Z
|
// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "verilog/analysis/checkers/disable_statement_rule.h"
#include <initializer_list>
#include "common/analysis/linter_test_utils.h"
#include "common/analysis/syntax_tree_linter_test_utils.h"
#include "common/text/symbol.h"
#include "gtest/gtest.h"
#include "verilog/CST/verilog_nonterminals.h"
#include "verilog/CST/verilog_treebuilder_utils.h"
#include "verilog/analysis/verilog_analyzer.h"
#include "verilog/parser/verilog_token_enum.h"
namespace verilog {
namespace analysis {
namespace {
using verible::LintTestCase;
using verible::RunLintTestCases;
TEST(DisableStatementTest, FunctionPass) {
const std::initializer_list<LintTestCase> kDisableStatementTestCases = {
{""},
{"module m;\ninitial begin;\n", "fork\n", "begin\n#6;\nend\n",
"begin\n#3;\nend\n", "join_any\n", "disable fork;\n", "end\nendmodule"},
{"module m;\ninitial begin\n", "fork\n", "begin : foo\n",
"disable foo;\n", "end\n", "join_any\n", "end\nendmodule"},
{"module m;\ninitial begin\n", "fork\n", "begin : foo\n",
"begin : foo_2\n", "disable foo_2;\n", "end\n", "end\n", "join_any\n",
"end\nendmodule"},
{"module m;\ninitial begin\n", "fork\n", "begin : foo\n",
"begin : foo_2\n", "disable foo;\n", "end\n", "end\n", "join_any\n",
"end\nendmodule"},
};
RunLintTestCases<VerilogAnalyzer, DisableStatementNoLabelsRule>(
kDisableStatementTestCases);
}
TEST(DisableStatementTest, ForkDisableStatementsFail) {
constexpr int kToken = TK_disable;
const std::initializer_list<LintTestCase> kDisableStatementTestCases = {
{"module m;\ninitial begin\n",
"fork\n",
"begin\n#6;\nend\n",
"begin\n#3;\nend\n",
"join_any\n",
{kToken, "disable"},
" fork_invalid;\n",
"end\nendmodule"},
{"module m;\ninitial begin\n",
"fork:fork_label\n",
"begin\n#6;\nend\n",
"begin\n#3;\nend\n",
"join_any\n",
{kToken, "disable"},
" fork_label;\n",
"end\nendmodule"},
};
RunLintTestCases<VerilogAnalyzer, DisableStatementNoLabelsRule>(
kDisableStatementTestCases);
}
TEST(DisableStatementTest, NonSequentialDisableStatementsFail) {
constexpr int kToken = TK_disable;
const std::initializer_list<LintTestCase> kDisableStatementTestCases = {
{"module m;\n",
"initial begin;\n",
"fork\n",
"begin : foo\n",
"end\n",
{kToken, "disable"},
" foo;\n",
"join_any\n",
"end\nendmodule"},
{"module m;\n",
"initial begin:foo\n",
"end\n",
"initial begin:boo\n",
{kToken, "disable"},
" foo;\n",
"end\nendmodule"},
{"module m;\n",
"initial begin:foo;\n",
"begin : bar\n",
{kToken, "disable"},
" foo;\n",
"end\n",
"end\nendmodule"},
{"module m;\n",
"final begin:foo;\n",
"begin : bar\n",
{kToken, "disable"},
" foo;\n",
"end\n",
"end\nendmodule"},
{"module m;\n",
"always_comb begin:foo;\n",
"begin : bar\n",
{kToken, "disable"},
" foo;\n",
"end\n",
"end\nendmodule"},
};
RunLintTestCases<VerilogAnalyzer, DisableStatementNoLabelsRule>(
kDisableStatementTestCases);
}
} // namespace
} // namespace analysis
} // namespace verilog
| 31.608
| 79
| 0.628702
|
imphil
|
37309bee6eb272dc1b99f9659ca749ea8ee4cf80
| 9,450
|
cpp
|
C++
|
utils.cpp
|
Litvinovis/webserver
|
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
|
[
"Apache-2.0"
] | 2
|
2021-04-22T11:07:04.000Z
|
2022-01-04T13:57:57.000Z
|
utils.cpp
|
Litvinovis/webserver
|
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
|
[
"Apache-2.0"
] | 18
|
2021-05-10T15:33:00.000Z
|
2021-05-30T16:32:16.000Z
|
utils.cpp
|
Litvinovis/webserver
|
1d7156dcfb7bc0c4abeff650d2cf4114bbd8129e
|
[
"Apache-2.0"
] | 2
|
2021-04-15T13:06:08.000Z
|
2021-05-26T18:08:41.000Z
|
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include "utils.hpp"
#include "Setting.hpp"
#include <cstring> // for linux
namespace utils {
std::vector<char> read_file(std::string filename) {
std::vector<char> buf;
int fd;
char* line;
if ((fd = open(filename.c_str(), O_RDONLY)) < 0)
utils::e_throw("open", __FILE__, __LINE__);
while (get_next_line(fd, &line) > 0)
buf.insert(buf.end(), line, line + std::strlen(line));
buf.insert(buf.end(), line, line + std::strlen(line));
close(fd);
return buf;
}
std::vector<char> read_file_raw(std::string filename) {
std::vector<char> buf;
int fd;
char line[5];
int m;
if ((fd = open(filename.c_str(), O_RDONLY)) < 0)
utils::e_throw("open", __FILE__, __LINE__);
while ((m = read(fd, line, 5)) > 0)
{
if (m == -1)
utils::e_throw("read", __FILE__, __LINE__);
buf.insert(buf.end(), line, line + m);
}
close(fd);
return buf;
}
void write_file_raw(std::string filename, std::vector<char> buf) {
int fd;
int m;
int offset;
offset = 0;
m = 0;
if ((fd = open(filename.c_str(), O_TRUNC | O_WRONLY | O_CREAT, 0644)) < 0)
utils::e_throw("open", __FILE__, __LINE__);
std::vector<char>::iterator it = buf.begin();
while (it != buf.end())
{
if(lseek(fd, 0, SEEK_CUR) == -1)
utils::e_throw("lseek", __FILE__, __LINE__);
if ((m = write(fd, &buf[offset], buf.size())) < 0)
utils::e_throw("write_file_raw", __FILE__, __LINE__);
offset = offset + m;
it = it + m;
}
close(fd);
}
bool file_exists (std::string filename) {
struct stat buffer;
return (stat (filename.c_str(), &buffer) == 0);
}
int file_dir_exists (std::string filename) {
struct stat info;
if( stat(filename.c_str(), &info ) != 0 )
return 0;
else if( info.st_mode & S_IFDIR )
return 2;
else
return 1;
}
bool in_array(const std::string &value, const std::vector<std::string> &array)
{
for ( std::vector<std::string>::const_iterator it = array.begin();
it != array.end(); ++it)
{
if (value == *it)
return true;
}
return false;
}
size_t get_current_time_in_ms(void)
{
struct timeval tv;
size_t time_in_mill;
gettimeofday(&tv, NULL);
time_in_mill = tv.tv_sec * 1000 + tv.tv_usec / 1000;
return (time_in_mill);
}
void ft_usleep(int ms)
{
size_t start_time;
size_t end_time;
int elapsed_time;
start_time = get_current_time_in_ms();
end_time = get_current_time_in_ms();
elapsed_time = end_time - start_time;
while (elapsed_time < ms)
{
usleep(10);
end_time = get_current_time_in_ms();
elapsed_time = end_time - start_time;
}
}
std::string ft_strtrim(const std::string &s1, const std::string& set)
{
size_t start = 0;
size_t end = 0;
size_t index = 0;
while (s1.c_str()[index] && utils::ft_strchr(set, s1.c_str()[index]) != -1) {
index++;
}
start = index;
end = s1.length();
return s1.substr(start, end);
}
std::string ft_strtrim2(const std::string &s1, const std::string& set)
{
size_t start;
size_t end;
size_t index = 0;
while (s1[index] && utils::ft_strchr(set, s1[index]) != -1) {
index++;
}
start = index;
end = s1.length();
while (end && utils::ft_strchr(set, s1[end]) != -1) {
--end;
}
return s1.substr(start, end);
}
int ft_strchr(const std::string& str, int ch)
{
char *src;
int index;
src = (char *)str.c_str();
index = 0;
while (src[index] != 0)
if (src[index++] == ch)
return (index);
if (src[index] == ch)
return (index);
return (-1);
}
std::map<std::string, std::string>
parseBufToHeaderMap(const std::map<std::string, std::string> & header,
const std::vector<char> & buf)
{
// All headers in map (key - value)
std::vector<char>::const_iterator head = buf.begin();
std::vector<char>::const_iterator tail = head;
std::map<std::string, std::string> header_new = header;
while (head != buf.end() && *head != '\r')
{
while (tail != buf.end() && *tail != '\r')
++tail;
std::vector<char>::const_iterator separator = head;
while (separator != buf.end() && separator != tail && *separator != ':')
++separator;
if (separator == tail)
break;
std::string key(head, separator);
std::vector<char>::const_iterator value = ++separator;
while (value != tail && (*value == ' ' || *value == ':'))
++value;
header_new[key] = std::string(value, tail);
while (tail != buf.end() && (*tail == '\r' || *tail == '\n'))
++tail;
head = tail;
}
return header_new;
}
std::string base64encode(std::vector<char> buf) {
const char base64Keys[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
std::string output;
char chr1, chr2, chr3;
int enc1, enc2, enc3, enc4;
size_t i = 0;
size_t buf_len = buf.size();
output.reserve(4 * buf_len / 3);
while (i < buf_len)
{
chr1 = (i < buf_len) ? buf[i++] : 0;
chr2 = (i < buf_len) ? buf[i++] : 0;
chr3 = (i < buf_len) ? buf[i++] : 0;
enc1 = chr1 >> 2;
enc2 = ((chr1 & 0x3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 0xF) << 2) | (chr3 >> 6);
enc4 = chr3 & 0x3F;
if (chr2 == 0)
{
enc3 = 64;
enc4 = 64;
}
else if (chr3 == 0)
{
enc4 = 64;
}
output += base64Keys[enc1];
output += base64Keys[enc2];
output += base64Keys[enc3];
output += base64Keys[enc4];
}
return output;
}
std::string base64decode(const std::string & s) {
const char base64Keys[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string output;
output.clear();
output.reserve(3 * s.length() / 4);
std::vector<int> T(256, -1);
for (int i = 0; i < 64; ++i)
{
T[base64Keys[i]] = i;
}
int val = 0;
int valb = -8;
for (size_t i = 0; i < s.length(); ++i)
{
char c = s[i];
if (T[c] == -1) break;
val = (val << 6) + T[c];
valb += 6;
if (valb >= 0)
{
output += char((val >> valb) & 0xFF);
valb -= 8;
}
}
return output;
}
std::string to_string(int n)
{
char * loc_num = ft_itoa(n);
std::string msg = std::string(loc_num);
free(loc_num);
return msg;
}
std::string get_current_time_fmt()
{
struct timeval tv;
time_t nowtime;
struct tm *nowtm;
char tmbuf[64];
gettimeofday(&tv, NULL);
nowtime = tv.tv_sec;
nowtm = localtime(&nowtime);
strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm);
std::string str(tmbuf);
return str;
}
void log_print_template(const char *color, const std::string & filename, const std::string & msg, int n)
{
std::cout << color;
std::cout << get_current_time_fmt() << " ";
std::cout << filename << ":" << RES << " " << msg;
if (n != -1) std::cout << n;
std::cout << std::endl;
}
void log(Setting & config, const std::string & filename,
const std::string & msg, int n)
{
if (filename == "EventLoop.cpp" && config.getDebugLevel() == -9)
log_print_template(GRA, filename, msg, n);
if (filename == "Response.cpp" && config.getDebugLevel() > 1)
log_print_template(CYN, filename, msg, n);
if (filename == "ProcessMethod.cpp" && config.getDebugLevel() > 1)
log_print_template(MAG, filename, msg, n);
if (filename == "Client.cpp" && config.getDebugLevel() > 2)
log_print_template(BLU, filename, msg, n);
if (filename == "HTTP HEADER" && config.getDebugLevel() == -1)
log_print_template(GRN, filename, msg, n);
}
void e_throw(const std::string & msg, const std::string & filename, int line)
{
throw std::runtime_error(msg + ": " + strerror(errno)
+ " at "+ filename + ":" + to_string(line));
}
}
| 30.882353
| 108
| 0.480635
|
Litvinovis
|
37332b84069848d85aeb8f925be6fd3454cd7939
| 604
|
hpp
|
C++
|
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
|
Aschratt/Texturize
|
bba688d1afd60363f03e02d28e642a63845591d6
|
[
"MIT"
] | 11
|
2019-05-17T12:23:12.000Z
|
2020-11-12T14:03:23.000Z
|
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
|
crud89/Texturize
|
bba688d1afd60363f03e02d28e642a63845591d6
|
[
"MIT"
] | 2
|
2019-04-01T08:37:36.000Z
|
2019-04-01T08:49:15.000Z
|
libs/Texturize.Codecs.EXR/include/Codecs/exr.hpp
|
crud89/Texturize
|
bba688d1afd60363f03e02d28e642a63845591d6
|
[
"MIT"
] | 1
|
2019-06-25T01:04:35.000Z
|
2019-06-25T01:04:35.000Z
|
#pragma once
#include <texturize.hpp>
#include <analysis.hpp>
#include <codecs.hpp>
#include <string>
#include <iostream>
namespace Texturize {
/// \brief
class TEXTURIZE_API EXRCodec :
public ISampleCodec
{
public:
virtual void load(const std::string& fileName, Sample& sample) const override;
virtual void load(std::istream& stream, Sample& sample) const override;
virtual void save(const std::string& fileName, const Sample& sample, const int depth = CV_8U) const override;
virtual void save(std::ostream& stream, const Sample& sample, const int depth = CV_8U) const override;
};
}
| 27.454545
| 111
| 0.738411
|
Aschratt
|
3733399ac2e2ccfedf640afe18d3d4056fa00c11
| 1,757
|
cpp
|
C++
|
queue/queue_LL.cpp
|
vivekrajx/dsa
|
23351634652aaabfa40f8679ccff9f6fa9f844e9
|
[
"MIT"
] | null | null | null |
queue/queue_LL.cpp
|
vivekrajx/dsa
|
23351634652aaabfa40f8679ccff9f6fa9f844e9
|
[
"MIT"
] | null | null | null |
queue/queue_LL.cpp
|
vivekrajx/dsa
|
23351634652aaabfa40f8679ccff9f6fa9f844e9
|
[
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
struct Node {
int data;
Node* link;
};
//declated glboally
struct Node * front = NULL;
struct Node * rear = NULL;
//Enqueue from front & Dequeue from rear both take O(1) time here.
//Enqueue from rear
void Enqueue(int x)
{
Node* temp = new Node();
temp->data = x;
temp->link = NULL;
//if queue is empty
if(front == NULL and rear == NULL)
{
front = rear = temp; //set both front and rear as to temp
return;
}
rear->link = temp; //build new link while enqueuing
rear = temp; //update rear
}
//Dequeue from front
void Dequeue()
{
Node * temp = front;
// we created this temp ptr to node in which we store
//the addr of current head or current front
//CASE 1: if queue is empty
if(front == NULL) return;
//CASE 2: only element in queue
if(front == rear)
{
front = rear = NULL; //removed the only element in the queue
}
//CASE 3: all other cases
else
{
front = front->link;
}
free(temp); //since front was incr, leaving a prev front in mem we free it
}
void Print(){
cout<<"Queue: ";
Node* current = front; // Initialize current
while (current != NULL)
{
cout<<current->data<<" ";
current = current->link;
}
cout<<endl;
}
int Front(){
return front->data; //return front element of queue
}
int Rear(){
return rear->data; //return rear element of queue
}
bool isEmpty(){
if(front==NULL)
return true;
else
return false;
}
int main(){
Enqueue(2); Print();
Enqueue(4); Print();
Enqueue(6); Print();
Dequeue(); Print();
Dequeue(); Print();
Dequeue(); Print();
}
| 19.307692
| 78
| 0.575982
|
vivekrajx
|
3735173760e30d35d79fd6810a10f9c753be25fc
| 34,117
|
cpp
|
C++
|
closed/FuriosaAI/code/resnet50/resnet50.cpp
|
ctuning/inference_results_v1.1
|
d9176eca28fcf6d7a05ccb97994362a76a1eb5ab
|
[
"Apache-2.0"
] | 12
|
2021-09-23T08:05:57.000Z
|
2022-03-21T03:52:11.000Z
|
closed/FuriosaAI/code/resnet50/resnet50.cpp
|
ctuning/inference_results_v1.1
|
d9176eca28fcf6d7a05ccb97994362a76a1eb5ab
|
[
"Apache-2.0"
] | 11
|
2021-09-23T20:34:06.000Z
|
2022-01-22T07:58:02.000Z
|
closed/FuriosaAI/code/resnet50/resnet50.cpp
|
ctuning/inference_results_v1.1
|
d9176eca28fcf6d7a05ccb97994362a76a1eb5ab
|
[
"Apache-2.0"
] | 16
|
2021-09-23T20:26:38.000Z
|
2022-03-09T12:59:56.000Z
|
#include <cassert>
#include <sstream>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <map>
#include <mutex>
#include <thread>
#include <vector>
#include <fstream>
#include <streambuf>
#include <atomic>
#include <string.h>
#include "loadgen.h"
#include "query_sample_library.h"
#include "system_under_test.h"
#include "test_settings.h"
#include "../common/nux.h"
#include <stdlib.h>
#include "../common/unlower.h"
using namespace std::string_literals;
// #define ASYNC
// #define PROFILE
// #define DEBUG
#define POST_PROCESS
#ifdef PROFILE
std::string PROFILE_RECORD_INFERENCE = "Inference";
std::string PROFILE_RECORD_PREPARE_SUBMISSION = "PrepareSubmission";
std::string PROFILE_RECORD_POST_PROCESS = "PostProcess";
std::string PROFILE_RECORD_OUT_OF_TIMED = "OutOfTimed";
std::string build_profile_record(std::string record_name, std::string annotation) {
return record_name + "(" + annotation + ")";
}
#endif
std::string DATA_PATH = "../preprocessed/imagenet-golden/raw/";
std::string VAL_MAP_PATH = "../common/val_map.txt";
const int IMAGE_SIZE = (224*224*3);
int INPUT_SIZE = IMAGE_SIZE;
int OUTPUT_SIZE = 1001;
std::vector<std::unique_ptr<unsigned char[]>> images;
std::optional<LoweringInfo> input_lowering;
std::optional<LoweringInfo> output_lowering;
std::optional<LoweringInfo> TensorDescToLoweringInfo(nux_tensor_desc_t desc, int unlowered_channel, int unlowered_height, int unlowered_width) {
int dim = nux_tensor_dim_num(desc);
if (dim != 6)
return {};
if (nux_tensor_axis(desc, 0) != Axis::axis_batch)
return {};
if (nux_tensor_axis(desc, 1) == Axis::axis_height_outer &&
nux_tensor_axis(desc, 2) == Axis::axis_channel_outer &&
nux_tensor_axis(desc, 3) == Axis::axis_height
) {
if (nux_tensor_axis(desc, 4) == Axis::axis_channel &&
nux_tensor_axis(desc, 5) == Axis::axis_width) {
return DynamicHCHCW(
nux_tensor_dim(desc, 1),
nux_tensor_dim(desc, 2),
nux_tensor_dim(desc, 3),
nux_tensor_dim(desc, 4),
nux_tensor_dim(desc, 5),
unlowered_channel,
unlowered_height,
unlowered_width
);
}
if (nux_tensor_axis(desc, 4) == Axis::axis_width &&
nux_tensor_axis(desc, 5) == Axis::axis_channel
) {
return DynamicHCHWC(
nux_tensor_dim(desc, 1),
nux_tensor_dim(desc, 2),
nux_tensor_dim(desc, 3),
nux_tensor_dim(desc, 4),
nux_tensor_dim(desc, 5),
unlowered_channel,
unlowered_height,
unlowered_width
);
}
}
return {};
}
class QSL : public mlperf::QuerySampleLibrary {
public:
QSL(int sampleSize = 50000)
: mSampleSize(sampleSize) {
std::ifstream val_file(VAL_MAP_PATH.c_str());
std::string input_filename;
std::cout << "sample size: " << std::to_string(sampleSize) << std::endl;
int answer;
while(val_file >> input_filename >> answer) {
mItems.emplace_back(input_filename.substr(0, input_filename.size() - 5) + ".JPEG.raw", answer);
}
images.resize(mItems.size());
};
~QSL() override{};
const std::string& Name() const override { return mName; }
size_t TotalSampleCount() override { return mSampleSize; }
size_t PerformanceSampleCount() override {
std::cout << "PerformanceSampleCount" << 10240 << '\n';
return 10240;
}
void LoadSamplesToRam(
const std::vector<mlperf::QuerySampleIndex>& samples) override {
for(auto index : samples) {
std::string filename = DATA_PATH + mItems[index].first;
std::ifstream inf(filename.c_str(), std::ios::binary);
if (input_lowering) {
std::vector<char> buffer(IMAGE_SIZE);
inf.read((char*)&buffer[0], 224*224*3);
std::visit([&](auto info){
INPUT_SIZE = info.lowered_size();
images[index].reset((unsigned char*)std::aligned_alloc(64, info.lowered_size()));
info.for_each([&](int c, int co, int ci, int h, int ho, int hi, int w) {
images[index][info.index(co, ci, ho, hi, w)] = buffer[c*224*224+h*224+w];
});
}, *input_lowering);
} else {
images[index].reset((unsigned char*)std::aligned_alloc(64, IMAGE_SIZE));
inf.read((char*)&images[index][0], 224*224*3);
}
}
}
void UnloadSamplesFromRam(
const std::vector<mlperf::QuerySampleIndex>& samples) override {
for(auto index : samples) {
//std::cout << "UNLOAD " << index << '\n';
images[index].reset();
}
}
private:
std::string mName{"FuriosaAI-QSL"};
int mSampleSize;
std::vector<std::pair<std::string, int>> mItems;
};
class Resnet50Reporter {
protected:
void post_inference(unsigned char* buffer,
mlperf::QuerySampleResponse& response) {
float max_index = 0;
char* data_arr = (char*)buffer;
if (output_lowering) {
std::visit([&](auto info){
for(int i = 1; i < 1001; i ++) {
if (data_arr[info.index((int)max_index, 0, 0)] < data_arr[info.index(i, 0, 0)]) {
max_index = i;
}
}
}, *output_lowering);
} else {
for(int i = 1; i < 1001; i ++) {
if (data_arr[(int)max_index] < data_arr[i]) {
max_index = i;
}
}
}
*(float*)response.data = max_index;
}
};
class FuriosaBasicSUT : public mlperf::SystemUnderTest, Resnet50Reporter {
public:
nux_session_t mSession;
nux_completion_queue_t mQueue;
nux_session_option_t mSessionOption;
nux_tensor_array_t mInputs;
nux_tensor_array_t mOutputs;
std::atomic<int> mIssued;
std::atomic<int> mCompleted;
FuriosaBasicSUT()
{
// Start with some large value so that we don't reallocate memory.
initResponse(1);
std::ifstream inf("mlcommons_resnet50_v1.5_int8.enf", std::ios::binary);
mSessionOption = nux_session_option_create();
nux_session_option_set_device(mSessionOption, "npu0pe0-1");
std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)),
std::istreambuf_iterator<char>());
{
auto err = nux_session_create((nux_buffer_t)model_buf.data(), model_buf.size(), mSessionOption, &mSession);
if (err != nux_error_t_success) {
std::cerr << "SUT:nux async session create error: " << err << '\n';
exit(-1);
}
}
nux_model_t model = nux_session_get_model(mSession);
mInputs = nux_tensor_array_create_inputs(model);
mOutputs = nux_tensor_array_allocate_outputs(model);
auto input_desc = nux_input_desc(model, 0);
input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224);
auto output_desc = nux_output_desc(model, 0);
output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1);
if (output_lowering)
std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering);
}
std::vector<std::thread> mCompleteThreads;
~FuriosaBasicSUT() override {
nux_session_destroy(mSession);
}
const std::string& Name() const override { return mName; }
void IssueQuery(const std::vector<mlperf::QuerySample>& samples) override {
int n = samples.size();
if (n > mResponses.size()) {
std::cerr << "Warning: reallocating response buffer in BasicSUT. Maybe "
"you should initResponse with larger value!?"
<< std::endl;
initResponse(samples.size());
}
for (int i = 0; i < n; i++) {
mResponses[i].id = samples[i].id;
auto tensor0 = nux_tensor_array_get(mInputs, 0);
auto* data = images[samples[i].index].get();
nux_error_t err;
//std::cout << "Issuing: " << samples[i].index << ' ' << i << '/' << n << ' ' << data.size() << '\n';
// Use allocated aligned buffer
tensor_set_buffer(tensor0, (nux_buffer_t)data, INPUT_SIZE, nullptr);
//auto err = tensor_set_buffer(tensor0, (nux_buffer_t)data.data(), data.size(), nullptr);
err = nux_session_run(mSession, mInputs, mOutputs);
if (err != 0) {
std::cout << "Error: " << err << '\n';
}
auto result = nux_tensor_array_get(mOutputs, 0);
nux_buffer_t buffer;
nux_buffer_len_t len;
tensor_get_buffer(result, &buffer, &len);
post_inference(buffer, mResponses[0]);
mlperf::QuerySamplesComplete(mResponses.data(), 1);
}
}
void FlushQueries() override {}
void ReportLatencyResults(
const std::vector<mlperf::QuerySampleLatency>& latencies_ns) override{};
private:
void initResponse(int size) {
mResponses.resize(size,
{0, reinterpret_cast<uintptr_t>(&mBuf), sizeof(mBuf)});
}
float mBuf{1};
std::string mName{"FuriosaAI-BasicSUT"};
std::vector<mlperf::QuerySampleResponse> mResponses;
};
class FuriosaQueueSUT : public mlperf::SystemUnderTest, Resnet50Reporter {
public:
std::vector<nux_session_t> mSessions;
FuriosaQueueSUT(int numCompleteThreads, int maxSize) {
std::ifstream inf("mlcommons_resnet50_v1.5_int8_batch8.enf", std::ios::binary);
std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)),
std::istreambuf_iterator<char>());
for(int npu_id = 0; npu_id < numCompleteThreads / 2; npu_id++) {
for(int pe_id = 0; pe_id < 2; pe_id++) {
std::stringstream ostr;
ostr << "npu" << npu_id << "pe" << pe_id;
auto sessionOption = nux_session_option_create();
nux_session_option_set_device(sessionOption, ostr.str().c_str());
nux_session_t session;
auto err = nux_session_create((nux_buffer_t)model_buf.data(), model_buf.size(), sessionOption, &session);
if (err != nux_error_t_success) {
std::cerr << "SUT:nux session create error: " << err << '\n';
exit(-1);
}
mSessions.push_back(session);
if (npu_id == 0 && pe_id == 0) {
nux_model_t model = nux_session_get_model(session);
auto input_desc = nux_input_desc(model, 0);
input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224);
auto output_desc = nux_output_desc(model, 0);
output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1);
if (output_lowering)
std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering);
}
}
}
initResponse(numCompleteThreads, maxSize);
for (int i = 0; i < numCompleteThreads; i++) {
mThreads.emplace_back(&FuriosaQueueSUT::CompleteThread, this, i);
}
}
~FuriosaQueueSUT() override {
{
std::unique_lock<std::mutex> lck(mMtx);
mDone = true;
mCondVar.notify_all();
}
for (auto& thread : mThreads) {
thread.join();
}
}
const std::string& Name() const override { return mName; }
void IssueQuery(const std::vector<mlperf::QuerySample>& samples) override {
{
std::unique_lock<std::mutex> lck(mMtx);
mWorkQueue = &samples;
mQueueTail = 0;
}
mCondVar.notify_one();
}
void FlushQueries() override {}
void ReportLatencyResults(
const std::vector<mlperf::QuerySampleLatency>& latencies_ns) override{};
private:
void CompleteThread(int threadIdx) {
auto& inputs = mInputs[threadIdx];
auto& responses = mResponses[threadIdx];
auto& session = mSessions[threadIdx];
nux_model_t model = nux_session_get_model(session);
auto input_tensor = nux_tensor_array_create_inputs(model);
auto output_tensor = nux_tensor_array_allocate_outputs(model);
size_t maxSize{responses.size()};
size_t actualSize{0};
while (true) {
{
std::unique_lock<std::mutex> lck(mMtx);
mCondVar.wait(lck, [&]() { return mWorkQueue && mWorkQueue->size() != mQueueTail || mDone; });
if (mDone) {
break;
}
auto* requests = &(*mWorkQueue)[mQueueTail];
actualSize = std::min(maxSize, mWorkQueue->size() - mQueueTail);
mQueueTail += actualSize;
for (int i = 0; i < actualSize; i++) {
responses[i].id = requests[i].id;
}
if (mWorkQueue->size() == mQueueTail) {
mWorkQueue = nullptr;
}
lck.unlock();
mCondVar.notify_one();
for(int i = 0; i < actualSize; i ++) {
int index = requests[i].index;
auto* data = images[index].get();
memcpy(&inputs[i*INPUT_SIZE] , data, INPUT_SIZE);
}
auto tensor0 = nux_tensor_array_get(input_tensor, 0);
tensor_set_buffer(tensor0, (nux_buffer_t)&inputs[0], maxSize * INPUT_SIZE, nullptr);
auto err = nux_session_run(session, input_tensor, output_tensor);
if (err != 0) {
std::cout << "Error: " << err << '\n';
}
auto result = nux_tensor_array_get(output_tensor, 0);
nux_buffer_t buffer;
nux_buffer_len_t len;
tensor_get_buffer(result, &buffer, &len);
for(int i = 0; i < actualSize; i ++)
post_inference((unsigned char*)buffer + OUTPUT_SIZE * i, responses[i]);
}
mlperf::QuerySamplesComplete(responses.data(), actualSize);
}
}
void initResponse(int numCompleteThreads, int size) {
mBuf.resize(numCompleteThreads*size);
mInputs.resize(numCompleteThreads);
for(int i = 0; i < numCompleteThreads; i ++)
mInputs[i].reset((unsigned char*)std::aligned_alloc(64, INPUT_SIZE*size));
mResponses.resize(numCompleteThreads);
for(int i = 0; i < numCompleteThreads; i ++) {
for(int j = 0; j < size; j ++) {
mResponses[i].emplace_back(mlperf::QuerySampleResponse{0, reinterpret_cast<uintptr_t>(&mBuf[i*size+j]), sizeof(float)});
}
}
}
std::vector<float> mBuf;
std::string mName{"FuriosaQueueSUT"};
std::vector<std::vector<mlperf::QuerySampleResponse>> mResponses;
std::vector<std::unique_ptr<unsigned char[]>> mInputs;
std::vector<std::thread> mThreads;
const std::vector<mlperf::QuerySample>* mWorkQueue{nullptr};
size_t mQueueTail;
std::mutex mMtx;
std::condition_variable mCondVar;
bool mDone{false};
};
struct Context {
mlperf::ResponseId *ids;
nux_tensor_array_t input;
nux_tensor_array_t output;
unsigned char *buffer;
int len;
};
class StreamSession : public Resnet50Reporter {
public:
// Nux Session
nux_async_session_t mSession;
nux_completion_queue_t mQueue;
nux_handle_t mNux;
nux_model_t mModel;
// SessionWarpper options
nux_session_option_t mSessionOption;
// IOs
nux_tensor_array_t mInput;
nux_tensor_array_t mOutput;
mlperf::ResponseId *mIds;
unsigned char *mBuffer;
Context *mContext;
// Compltion thread
std::thread mCompletionThread;
int mModelBatch;
const std::string& Name() const { return mName; }
StreamSession(
int numWorkers = 12,
int modelBatch = 1,
std::string deviceName = "npu0pe0-1",
std::string source = "") {
#ifdef DEBUG
std::cout << "Constructing StreamSession(" << numWorkers << ")" << std::endl;
#endif
mModelBatch = modelBatch;
mSessionOption = nux_session_option_create();
nux_session_option_set_worker_num(mSessionOption, numWorkers);
nux_session_option_set_device(mSessionOption, deviceName.c_str());
nux_session_option_set_input_queue_size(mSessionOption, 8);
nux_session_option_set_output_queue_size(mSessionOption, 256);
#ifdef DEBUG
std::cout << "Prepare Nux session with device name: " << deviceName << std::endl;
#endif
std::ifstream inf(source, std::ios::binary);
std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)),
std::istreambuf_iterator<char>());
auto err = nux_async_session_create(
(nux_buffer_t)model_buf.data(),
model_buf.size(),
mSessionOption,
&mSession,
&mQueue);
#ifdef DEBUG
std::cout << "create async session done: " << deviceName << std::endl;
#endif
if (err != nux_error_t_success) {
std::cerr << "SUT:nux async session create error: " << err << std::endl;
exit(-1);
}
mModel = nux_async_session_get_model(mSession);
nux_async_session_get_nux_handle(mSession, &mNux);
#ifdef DEBUG
std::cout << "Prepare first submission" << std::endl;
#endif
mInput = nux_tensor_array_create_inputs(mModel);
mOutput = nux_tensor_array_allocate_outputs(mModel);
mContext = (Context *) malloc(sizeof(Context));
mIds = (mlperf::ResponseId *) malloc(sizeof(mlperf::ResponseId) * mModelBatch);
mBuffer = (unsigned char*) std::aligned_alloc(64, INPUT_SIZE * mModelBatch);
auto input_desc = nux_input_desc(mModel, 0);
input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224);
auto output_desc = nux_output_desc(mModel, 0);
output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1);
if (output_lowering)
std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering);
#ifdef DEBUG
std::cout << "Run completion thread" << std::endl;
#endif
mCompletionThread = std::thread([this] { CompleteThread(); });
}
~StreamSession() {
nux_tensor_array_destroy(mInput);
nux_tensor_array_destroy(mOutput);
free(mContext);
free(mIds);
nux_async_session_destroy(mSession);
nux_completion_queue_destroy(mQueue);
mCompletionThread.join();
}
void SubmitQuery(std::vector<mlperf::QuerySample> samples, int begin, int len) {
#ifdef PROFILE
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(samples[begin].id)).c_str());
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(samples[begin].id)).c_str());
#endif
if (len == 1) {
mIds[0] = samples[begin].id;
auto tensor = nux_tensor_array_get(mInput, 0);
auto* data = images[samples[begin].index].get();
auto err = tensor_set_buffer(tensor, (nux_buffer_t) data, INPUT_SIZE, nullptr);
if (err != 0) {
std::cout << "Error: " << err << '\n';
}
} else {
for(int i = 0; i < len ; i ++) {
mIds[i] = samples[begin + i].id;
auto* data = images[samples[begin + i].index].get();
memcpy(&mBuffer[i*INPUT_SIZE] , data, INPUT_SIZE);
}
auto tensor = nux_tensor_array_get(mInput, 0);
auto err = tensor_set_buffer(tensor, (nux_buffer_t)&mBuffer[0], mModelBatch * INPUT_SIZE, nullptr);
if (err != 0) {
std::cout << "Error: " << err << '\n';
}
}
mContext->ids = mIds;
mContext->input = mInput;
mContext->output = mOutput;
mContext->buffer = mBuffer;
mContext->len = len;
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(samples[begin].id)).c_str());
#endif
#ifdef DEBUG
std::cout
<< "Submit ctx addr: " << (void *) mContext
<< ", ctx->output: " << (void *) mContext->output
<< ", ctx->input: " << (void *) mContext->input
<< std::endl;
#endif
auto err = nux_async_session_run(mSession, (nux_context_t) mContext, mInput, mOutput);
if (err != 0) {
std::cout << "nux session run error: " << err << '\n';
}
#ifdef PROFILE
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "alloc-for-next-" + std::to_string(samples[begin].id)).c_str());
#endif
mInput = nux_tensor_array_create_inputs(mModel);
mOutput = nux_tensor_array_allocate_outputs(mModel);
mContext = (Context *) malloc(sizeof(Context));
mIds = (mlperf::ResponseId *) malloc(sizeof(mlperf::ResponseId) * mModelBatch);
mBuffer = (unsigned char*) std::aligned_alloc(64, INPUT_SIZE * mModelBatch);
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "alloc-for-next-" + std::to_string(samples[begin].id)).c_str());
#endif
}
void CompleteThread() {
std::cout << "Completion Thread has been launched" << '\n';
nux_context_t context;
nux_tensor_array_t output;
float tempBuf[mModelBatch];
std::vector<mlperf::QuerySampleResponse> responses;
for (int i = 0 ; i < mModelBatch ; i++) {
responses.push_back(mlperf::QuerySampleResponse {0, reinterpret_cast<uintptr_t>(&tempBuf[i]), sizeof(float)});
}
enum nux_error_t error;
while (nux_completion_queue_next(mQueue,
&context,
&error)) {
Context* ctx = (Context*) context;
#ifdef DEBUG
std::cout
<< "Recv ctx addr: " << (void *) ctx
<< ", ctx->output: " << (void *) ctx->output
<< ", ctx->input: " << (void *) ctx->input
<< std::endl;
#endif
#ifdef PROFILE
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(ctx->ids[0])).c_str());
#endif
auto result = nux_tensor_array_get(ctx->output, 0);
nux_buffer_t buffer;
nux_buffer_len_t buffer_len;
tensor_get_buffer(result, &buffer, &buffer_len);
for (int i = 0; i < ctx->len ; i ++) {
responses[i].id = ctx->ids[i];
responses[i].size = sizeof(float);
#ifdef POST_PROCESS
post_inference((unsigned char*)buffer + OUTPUT_SIZE * i, responses[i]);
#else
responses[i].data = (uintptr_t)&buffer + OUTPUT_SIZE * i;
#endif
}
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(ctx->ids[0])).c_str());
#endif
mlperf::QuerySamplesComplete(responses.data(), ctx->len);
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(ctx->ids[0])).c_str());
#endif
#ifdef PROFILE
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "dealloc-" + std::to_string(ctx->ids[0])).c_str());
#endif
nux_tensor_array_destroy(ctx->input);
nux_tensor_array_destroy(ctx->output);
free(ctx->ids);
free(ctx->buffer);
free(ctx);
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_OUT_OF_TIMED, "dealloc-" + std::to_string(ctx->ids[0])).c_str());
#endif
}
}
private:
std::string mName{"FuriosaAI-StreamSession-SUT"};
};
class BlockingSession : public Resnet50Reporter {
public:
// Nux Session
nux_session_t mSession;
nux_handle_t mNux;
nux_model_t mModel;
// SessionWarpper options
nux_session_option_t mSessionOption;
// IOs
nux_tensor_array_t mInput;
nux_tensor_array_t mOutput;
std::vector<mlperf::QuerySampleResponse> mResponses;
const std::string& Name() const { return mName; }
BlockingSession() {
#ifdef DEBUG
std::cout << "Constructing BlockingSession" << std::endl;
#endif
mSessionOption = nux_session_option_create();
nux_session_option_set_device(mSessionOption, "npu0pe0-1");
#ifdef DEBUG
std::cout << "Prepare Nux session" << std::endl;
#endif
std::ifstream inf("mlcommons_resnet50_v1.5_int8.enf", std::ios::binary);
std::vector<char> model_buf((std::istreambuf_iterator<char>(inf)),
std::istreambuf_iterator<char>());
auto err = nux_session_create(
(nux_buffer_t)model_buf.data(),
model_buf.size(),
mSessionOption,
&mSession);
if (err != nux_error_t_success) {
std::cerr << "SUT:nux session create error: " << err << std::endl;
exit(-1);
}
mModel = nux_session_get_model(mSession);
nux_session_get_nux_handle(mSession, &mNux);
auto input_desc = nux_input_desc(mModel, 0);
input_lowering = TensorDescToLoweringInfo(input_desc, 3, 224, 224);
auto output_desc = nux_output_desc(mModel, 0);
output_lowering = TensorDescToLoweringInfo(output_desc, 1001, 1, 1);
if (output_lowering)
std::visit([](auto info){OUTPUT_SIZE = info.lowered_size();}, *output_lowering);
#ifdef DEBUG
std::cout << "Prepare first submission" << std::endl;
#endif
mInput = nux_tensor_array_create_inputs(mModel);
mOutput = nux_tensor_array_allocate_outputs(mModel);
int tempBuf{0};
mResponses.resize(1, {0, reinterpret_cast<uintptr_t>(&tempBuf), sizeof(int)});
}
~BlockingSession() {
nux_tensor_array_destroy(mInput);
nux_tensor_array_destroy(mOutput);
nux_session_destroy(mSession);
}
void Run(mlperf::QuerySample sample) {
#ifdef DEBUG
std::cout << "run sample: " << std::to_string(sample.id) << std::endl;
#endif
#ifdef PROFILE
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(sample.id)).c_str());
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(sample.id)).c_str());
#endif
auto tensor = nux_tensor_array_get(mInput, 0);
auto* data = images[sample.index].get();
auto err = tensor_set_buffer(tensor, (nux_buffer_t) data, INPUT_SIZE, nullptr);
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_PREPARE_SUBMISSION, std::to_string(sample.id)).c_str());
#endif
err = nux_session_run(mSession, mInput, mOutput);
if (err != 0) {
std::cout << "nux session run error: " << err << std::endl;
}
#ifdef PROFILE
nux_profiler_record_begin(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(sample.id)).c_str());
#endif
auto result = nux_tensor_array_get(mOutput, 0);
nux_buffer_t buffer;
nux_buffer_len_t len;
tensor_get_buffer(result, &buffer, &len);
mResponses[0].id = sample.id;
mResponses[0].size = len;
#ifdef POST_PROCESS
post_inference(buffer, mResponses[0]);
#else
mResponses[0].data = (uintptr_t)&buffer;
#endif
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_POST_PROCESS, std::to_string(sample.id)).c_str());
#endif
mlperf::QuerySamplesComplete(mResponses.data(), 1);
#ifdef PROFILE
nux_profiler_record_end(mNux, build_profile_record(PROFILE_RECORD_INFERENCE, std::to_string(sample.id)).c_str());
#endif
}
private:
std::string mName{"FuriosaAI-BlockingSession-SUT"};
};
class FuriosaSUTAlt : public mlperf::SystemUnderTest {
public:
#ifdef ASYNC
std::unique_ptr<StreamSession> mSession;
#else
std::unique_ptr<BlockingSession> mSession;
#endif
FuriosaSUTAlt(int numWorkers = 12) {
#ifdef DEBUG
std::cout << "Constructing FuriosaSUTAlt" << std::endl;
#endif
#ifdef ASYNC
mSession.reset(new StreamSession(
numWorkers, 8, "npu0pe0-1", "mlcommons_resnet50_v1.5_int8.enf"));
#else
mSession.reset(new BlockingSession());
#endif
}
~FuriosaSUTAlt() {
mSession.reset();
}
const std::string &Name() const override { return mSession->Name(); }
void IssueQuery(const std::vector<mlperf::QuerySample> &samples) override {
#ifdef ASYNC
mSession->SubmitQuery(samples, 0, 1);
#else
mSession->Run(samples[0]);
#endif
}
void FlushQueries() override {}
void ReportLatencyResults(
const std::vector<mlperf::QuerySampleLatency> &latencies_ns) override {};
};
class FuriosaMultiThreadSUT : public mlperf::SystemUnderTest {
public:
std::vector<std::unique_ptr<StreamSession>> mSessions;
FuriosaMultiThreadSUT(int numWorkers = 4) {
#ifdef DEBUG
std::cout << "Constructing FuriosaMultiThreadSUT" << std::endl;
#endif
for (int peId = 0 ; peId < 2 ; peId++) {
std::stringstream ostr;
ostr << "npu0pe" << peId;
mSessions.emplace_back(new StreamSession(
numWorkers, 8, ostr.str(), "mlcommons_resnet50_v1.5_int8_batch8.enf"));
}
}
~FuriosaMultiThreadSUT() {
mSessions.clear();
}
const std::string &Name() const override { return mName; }
void IssueQuery(const std::vector<mlperf::QuerySample> &samples) override {
#pragma omp parallel for num_threads(2)
for (int i = 0 ; i < 2 ; i++) {
auto& session = mSessions[i];
int half = samples.size() / 2;
int begin = i * half;
int end = begin + half;
int num_iter = (end - begin) / 8;
int remainder = (end - begin) % 8;
#ifdef DEBUG
std::cout << "half: " << std::to_string(half)
<< ", begin: " << std::to_string(begin)
<< ", end: " << std::to_string(end)
<< ", num_iter: " << std::to_string(num_iter)
<< ", remainder: " << std::to_string(remainder)
<< std::endl;
#endif
for (int j = 0 ; j < num_iter ; j++) {
session->SubmitQuery(samples, begin + j * 8, 8);
}
if (remainder > 0) {
session->SubmitQuery(samples, begin + num_iter * 8, remainder);
}
}
}
void FlushQueries() override {}
void ReportLatencyResults(
const std::vector<mlperf::QuerySampleLatency> &latencies_ns) override {};
private:
std::string mName{"FuriosaAI-FuriosaMultiThreadSUT"};
};
int main(int argc, char** argv) {
enable_logging();
if (getenv("DATA")) {
DATA_PATH = getenv("DATA");
}
if (getenv("VAL_MAP")) {
VAL_MAP_PATH = getenv("VAL_MAP");
}
//assert(argc >= 2 && "Need to pass in at least one argument: target_qps");
int target_qps = 100;
bool useQueue{false};
int numCompleteThreads{4};
int maxSize{1};
bool server_coalesce_queries{false};
int num_issue_threads{0};
bool isAccuracyRun = false;
int num_samples = 50000;
if (argc >= 2 && argv[1][0] >= '0' && argv[1][0] <= '9') {
num_samples = std::stoi(argv[1]);
isAccuracyRun = true;
}
mlperf::TestSettings testSettings;
decltype(testSettings.scenario) arg_scenario = mlperf::TestScenario::SingleStream;
for(int i = 1; i < argc; i ++) {
if (i + 1 < argc && argv[i] == "--count"s) {
num_samples = std::stoi(argv[i+1]);
}
if (i + 1 < argc && argv[i] == "--scenario"s) {
if (argv[i+1] == "SingleStream"s) {
std::cout << "Running the SingleStream scenario." << '\n';
} else if (argv[i+1] == "Offline"s) {
arg_scenario = mlperf::TestScenario::Offline;
std::cout << "Running the Offline scenario." << '\n';
} else {
std::cout << "Not supported scenario: " << argv[i+1] << '\n';
return -1;
}
}
if (argv[i] == "--accuracy"s) {
isAccuracyRun = true;
}
}
if (num_samples > 50000)
num_samples = 50000;
if (isAccuracyRun) {
std::cout << "Accuracy mode." << '\n';
} else {
std::cout << "Performance mode." << '\n';
}
QSL qsl(num_samples);
std::unique_ptr<mlperf::SystemUnderTest> sut;
// Configure the test settings
testSettings.FromConfig("../common/mlperf.conf", "resnet50", arg_scenario == mlperf::TestScenario::SingleStream ? "SingleStream" : "Offline");
testSettings.FromConfig("../common/user.conf", "resnet50", arg_scenario == mlperf::TestScenario::SingleStream ? "SingleStream" : "Offline");
testSettings.scenario = arg_scenario;
testSettings.mode = mlperf::TestMode::PerformanceOnly;
if (isAccuracyRun)
testSettings.mode = mlperf::TestMode::AccuracyOnly;
//testSettings.server_coalesce_queries = server_coalesce_queries;
//std::cout << "testSettings.server_coalesce_queries = "
//<< (server_coalesce_queries ? "True" : "False") << std::endl;
//testSettings.server_num_issue_query_threads = num_issue_threads;
//std::cout << "num_issue_threads = " << num_issue_threads << std::endl;
// Configure the logging settings
mlperf::LogSettings logSettings;
logSettings.log_output.outdir = "build";
logSettings.log_output.prefix = "mlperf_log_";
logSettings.log_output.suffix = "";
logSettings.log_output.prefix_with_datetime = false;
logSettings.log_output.copy_detail_to_stdout = false;
logSettings.log_output.copy_summary_to_stdout = true;
logSettings.log_mode = mlperf::LoggingMode::AsyncPoll;
logSettings.log_mode_async_poll_interval_ms = 1000;
logSettings.enable_trace = false;
// Choose SUT
if (arg_scenario == mlperf::TestScenario::SingleStream) {
// sut.reset(new FuriosaBasicSUT());
sut.reset(new FuriosaSUTAlt(1));
} else {
// sut.reset(new FuriosaQueueSUT(2, 8));
sut.reset(new FuriosaMultiThreadSUT(4));
}
// Start test
std::cout << "Start test..." << std::endl;
mlperf::StartTest(sut.get(), &qsl, testSettings, logSettings);
std::cout << "Test done. Clean up SUT..." << std::endl;
sut.reset();
std::cout << "Done!" << std::endl;
return 0;
}
| 35.354404
| 154
| 0.619427
|
ctuning
|
3735ac75271b959791cd33dbbaa242366ebba1cd
| 1,004
|
cpp
|
C++
|
Paperworks/src/Paperworks/Graphics/Renderer.cpp
|
codenobacon4u/paperworks
|
0e96cd2fb6070a2387ddd36aaa327b04733234fa
|
[
"MIT"
] | 1
|
2019-08-15T18:58:54.000Z
|
2019-08-15T18:58:54.000Z
|
Paperworks/src/Paperworks/Graphics/Renderer.cpp
|
codenobacon4u/paperworks
|
0e96cd2fb6070a2387ddd36aaa327b04733234fa
|
[
"MIT"
] | null | null | null |
Paperworks/src/Paperworks/Graphics/Renderer.cpp
|
codenobacon4u/paperworks
|
0e96cd2fb6070a2387ddd36aaa327b04733234fa
|
[
"MIT"
] | null | null | null |
#include "pwpch.h"
#include "Renderer.h"
#include "Renderer2D.h"
namespace Paperworks {
Unique<Renderer::SceneData> Renderer::s_SceneData = CreateUnique<Renderer::SceneData>();
void Renderer::Init()
{
RenderCmd::Init();
Renderer2D::Init();
}
void Renderer::Shutdown()
{
Renderer2D::Shutdown();
}
void Renderer::Begin()
{
}
void Renderer::Begin(Camera& camera)
{
s_SceneData->Projection = camera.GetProjectionMatrix();
s_SceneData->View = camera.GetViewMatrix();
}
void Renderer::End()
{
}
void Renderer::WindowResized(uint32_t width, uint32_t height)
{
RenderCmd::SetViewport(0, 0, width, height);
}
void Renderer::Submit(const Shared<VertexArray>& vertexArray, const Shared<Shader>& shader, const glm::mat4& transform)
{
shader->Bind();
shader->SetMat4("u_MVP.proj", s_SceneData->Projection);
shader->SetMat4("u_MVP.view", s_SceneData->View);
shader->SetMat4("u_MVP.modl", transform);
vertexArray->Bind();
RenderCmd::DrawIndexed(vertexArray);
}
}
| 20.08
| 120
| 0.703187
|
codenobacon4u
|
37394af6b5687c87eb0fa892766db5a1918223c8
| 1,212
|
cpp
|
C++
|
main/substring-subsequence-problem/substring-subsequence-problem.cpp
|
EliahKagan/old-practice-snapshot
|
1b53897eac6902f8d867c8f154ce2a489abb8133
|
[
"0BSD"
] | null | null | null |
main/substring-subsequence-problem/substring-subsequence-problem.cpp
|
EliahKagan/old-practice-snapshot
|
1b53897eac6902f8d867c8f154ce2a489abb8133
|
[
"0BSD"
] | null | null | null |
main/substring-subsequence-problem/substring-subsequence-problem.cpp
|
EliahKagan/old-practice-snapshot
|
1b53897eac6902f8d867c8f154ce2a489abb8133
|
[
"0BSD"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
namespace {
using It = std::string::const_iterator;
// Helper for common_length(const std::string&, const std::string&).
inline int common_length(const std::string& s,
It t_first, const It& t_last)
{
auto len = 0;
for (const auto c : s) {
if (c == *t_first) {
++len;
if (++t_first == t_last) break;
}
}
return len;
}
// Returns the length of the longest (possibly noncontiguous) subsequence
// of s that is a (contiguous) substring of t.
int common_length(const std::string& s, const std::string& t)
{
auto maxlen = 0;
const auto t_last = t.cend();
for (auto t_first = t.cbegin(); t_first != t_last; ++t_first)
maxlen = std::max(maxlen, common_length(s, t_first, t_last));
return maxlen;
}
}
int main()
{
auto tc = 0;
for (std::cin >> tc; tc > 0; --tc) {
std::string s, t;
std::cin >> s >> t;
std::cout << common_length(s, t) << '\n';
}
}
| 24.734694
| 77
| 0.5033
|
EliahKagan
|
373ebbffb8f88ef7396900b12828429e09e31da4
| 13,748
|
cc
|
C++
|
chrome/browser/chromeos/platform_keys/platform_keys_service_browsertest.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/browser/chromeos/platform_keys/platform_keys_service_browsertest.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/browser/chromeos/platform_keys/platform_keys_service_browsertest.cc
|
sarang-apps/darshan_browser
|
173649bb8a7c656dc60784d19e7bb73e07c20daa
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <type_traits>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/location.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/task/post_task.h"
#include "chrome/browser/chromeos/login/test/device_state_mixin.h"
#include "chrome/browser/chromeos/login/test/login_manager_mixin.h"
#include "chrome/browser/chromeos/login/test/scoped_policy_update.h"
#include "chrome/browser/chromeos/login/test/user_policy_mixin.h"
#include "chrome/browser/chromeos/platform_keys/platform_keys_service.h"
#include "chrome/browser/chromeos/platform_keys/platform_keys_service_factory.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/scoped_test_system_nss_key_slot_mixin.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/constants/chromeos_switches.h"
#include "chromeos/login/auth/user_context.h"
#include "components/policy/core/common/cloud/policy_builder.h"
#include "components/policy/core/common/policy_switches.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "crypto/signature_verifier.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace platform_keys {
namespace {
constexpr char kTestUserEmail[] = "test@example.com";
constexpr char kTestAffiliationId[] = "test_affiliation_id";
enum class ProfileToUse {
// A Profile that belongs to a user that is not affiliated with the device (no
// access to the system token).
kUnaffiliatedUserProfile,
// A Profile that belongs to a user that is affiliated with the device (access
// to the system token).
kAffiliatedUserProfile,
// The sign-in screen profile.
kSigninProfile
};
// Describes a test configuration for the test suite.
struct TestConfig {
// The profile for which PlatformKeysService should be tested.
ProfileToUse profile_to_use;
// The token IDs that are expected to be available. This will be checked by
// the GetTokens test, and operation for these tokens will be performed by the
// other tests.
std::vector<std::string> token_ids;
};
// A helper that waits until execution of an asynchronous PlatformKeysService
// operation has finished and provides access to the results.
// Note: all PlatformKeysService operations have a trailing const std::string&
// error_message argument that is filled in case of an error.
template <typename... ResultCallbackArgs>
class ExecutionWaiter {
public:
ExecutionWaiter() = default;
~ExecutionWaiter() = default;
ExecutionWaiter(const ExecutionWaiter& other) = delete;
ExecutionWaiter& operator=(const ExecutionWaiter& other) = delete;
// Returns the callback to be passed to the PlatformKeysService operation
// invocation.
base::RepeatingCallback<void(ResultCallbackArgs... result_callback_args,
const std::string& error_message)>
GetCallback() {
return base::BindRepeating(&ExecutionWaiter::OnExecutionDone,
weak_ptr_factory_.GetWeakPtr());
}
// Waits until the callback returned by GetCallback() has been called.
void Wait() { run_loop_.Run(); }
// Returns the error message passed to the callback.
const std::string& error_message() {
EXPECT_TRUE(done_);
return error_message_;
}
protected:
// A std::tuple that is capable of storing the arguments passed to the result
// callback.
using ResultCallbackArgsTuple =
std::tuple<std::decay_t<ResultCallbackArgs>...>;
// Access to the arguments passed to the callback.
const ResultCallbackArgsTuple& result_callback_args() const {
EXPECT_TRUE(done_);
return result_callback_args_;
}
private:
void OnExecutionDone(ResultCallbackArgs... result_callback_args,
const std::string& error_message) {
EXPECT_FALSE(done_);
done_ = true;
result_callback_args_ = ResultCallbackArgsTuple(
std::forward<ResultCallbackArgs>(result_callback_args)...);
error_message_ = error_message;
run_loop_.Quit();
}
base::RunLoop run_loop_;
bool done_ = false;
ResultCallbackArgsTuple result_callback_args_;
std::string error_message_;
base::WeakPtrFactory<ExecutionWaiter> weak_ptr_factory_{this};
};
// Supports waiting for the result of PlatformKeysService::GetTokens.
class GetTokensExecutionWaiter
: public ExecutionWaiter<std::unique_ptr<std::vector<std::string>>> {
public:
GetTokensExecutionWaiter() = default;
~GetTokensExecutionWaiter() = default;
const std::unique_ptr<std::vector<std::string>>& token_ids() const {
return std::get<0>(result_callback_args());
}
};
// Supports waiting for the result of the PlatformKeysService::GenerateKey*
// function family.
class GenerateKeyExecutionWaiter : public ExecutionWaiter<const std::string&> {
public:
GenerateKeyExecutionWaiter() = default;
~GenerateKeyExecutionWaiter() = default;
const std::string& public_key_spki_der() const {
return std::get<0>(result_callback_args());
}
};
// Supports waiting for the result of the PlatformKeysService::Sign* function
// family.
class SignExecutionWaiter : public ExecutionWaiter<const std::string&> {
public:
SignExecutionWaiter() = default;
~SignExecutionWaiter() = default;
const std::string& signature() const {
return std::get<0>(result_callback_args());
}
};
class GetAllKeysExecutionWaiter
: public ExecutionWaiter<std::vector<std::string>> {
public:
GetAllKeysExecutionWaiter() = default;
~GetAllKeysExecutionWaiter() = default;
const std::vector<std::string> public_keys() const {
return std::get<0>(result_callback_args());
}
};
} // namespace
class PlatformKeysServiceBrowserTest
: public MixinBasedInProcessBrowserTest,
public ::testing::WithParamInterface<TestConfig> {
public:
PlatformKeysServiceBrowserTest() = default;
~PlatformKeysServiceBrowserTest() override = default;
PlatformKeysServiceBrowserTest(const PlatformKeysServiceBrowserTest& other) =
delete;
PlatformKeysServiceBrowserTest& operator=(
const PlatformKeysServiceBrowserTest& other) = delete;
void SetUpInProcessBrowserTestFixture() override {
MixinBasedInProcessBrowserTest::SetUpInProcessBrowserTestFixture();
// Call |Request*PolicyUpdate| even if not setting affiliation IDs so
// (empty) policy blobs are prepared in FakeSessionManagerClient.
auto user_policy_update = user_policy_mixin_.RequestPolicyUpdate();
auto device_policy_update = device_state_mixin_.RequestDevicePolicyUpdate();
if (GetParam().profile_to_use == ProfileToUse::kAffiliatedUserProfile) {
device_policy_update->policy_data()->add_device_affiliation_ids(
kTestAffiliationId);
user_policy_update->policy_data()->add_user_affiliation_ids(
kTestAffiliationId);
}
}
void SetUpOnMainThread() override {
MixinBasedInProcessBrowserTest::SetUpOnMainThread();
if (GetParam().profile_to_use == ProfileToUse::kSigninProfile) {
profile_ = ProfileHelper::GetSigninProfile();
} else {
ASSERT_TRUE(login_manager_mixin_.LoginAndWaitForActiveSession(
LoginManagerMixin::CreateDefaultUserContext(test_user_info_)));
profile_ = ProfileManager::GetActiveUserProfile();
}
ASSERT_TRUE(profile_);
platform_keys_service_ =
PlatformKeysServiceFactory::GetForBrowserContext(profile_);
ASSERT_TRUE(platform_keys_service_);
}
protected:
PlatformKeysService* platform_keys_service() {
return platform_keys_service_;
}
// Generates a key pair in the given |token_id| using platform keys service
// and returns the SubjectPublicKeyInfo string encoded in DER format.
std::string GenerateKeyPair(const std::string& token_id) {
const unsigned int kKeySize = 2048;
GenerateKeyExecutionWaiter generate_key_waiter;
platform_keys_service()->GenerateRSAKey(token_id, kKeySize,
generate_key_waiter.GetCallback());
generate_key_waiter.Wait();
return generate_key_waiter.public_key_spki_der();
}
private:
const AccountId test_user_account_id_ = AccountId::FromUserEmailGaiaId(
kTestUserEmail,
signin::GetTestGaiaIdForEmail(kTestUserEmail));
const LoginManagerMixin::TestUserInfo test_user_info_{test_user_account_id_};
ScopedTestSystemNSSKeySlotMixin system_nss_key_slot_mixin_{&mixin_host_};
LoginManagerMixin login_manager_mixin_{&mixin_host_, {test_user_info_}};
DeviceStateMixin device_state_mixin_{
&mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED};
UserPolicyMixin user_policy_mixin_{&mixin_host_, test_user_account_id_};
// Unowned pointer to the profile selected by the current TestConfig.
// Valid after SetUpOnMainThread().
Profile* profile_ = nullptr;
// Unowned pointer to the PlatformKeysService for |profile_|. Valid after
// SetUpOnMainThread().
PlatformKeysService* platform_keys_service_ = nullptr;
};
// Tests that GetTokens() is callable and returns the expected tokens.
IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest, GetTokens) {
GetTokensExecutionWaiter get_tokens_waiter;
platform_keys_service()->GetTokens(get_tokens_waiter.GetCallback());
get_tokens_waiter.Wait();
EXPECT_TRUE(get_tokens_waiter.error_message().empty());
ASSERT_TRUE(get_tokens_waiter.token_ids());
EXPECT_THAT(*get_tokens_waiter.token_ids(),
::testing::UnorderedElementsAreArray(GetParam().token_ids));
}
// Generates a Rsa key pair and tests signing using that key pair.
IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest, GenerateRsaAndSign) {
const std::string data_to_sign = "test";
const unsigned int key_size = 2048;
const HashAlgorithm hash_algorithm = HASH_ALGORITHM_SHA256;
const crypto::SignatureVerifier::SignatureAlgorithm signature_algorithm =
crypto::SignatureVerifier::RSA_PKCS1_SHA256;
for (const std::string& token_id : GetParam().token_ids) {
GenerateKeyExecutionWaiter generate_key_waiter;
platform_keys_service()->GenerateRSAKey(token_id, key_size,
generate_key_waiter.GetCallback());
generate_key_waiter.Wait();
EXPECT_TRUE(generate_key_waiter.error_message().empty());
const std::string public_key_spki_der =
generate_key_waiter.public_key_spki_der();
EXPECT_FALSE(public_key_spki_der.empty());
SignExecutionWaiter sign_waiter;
platform_keys_service()->SignRSAPKCS1Digest(
token_id, data_to_sign, public_key_spki_der, hash_algorithm,
sign_waiter.GetCallback());
sign_waiter.Wait();
EXPECT_TRUE(sign_waiter.error_message().empty());
crypto::SignatureVerifier signature_verifier;
ASSERT_TRUE(signature_verifier.VerifyInit(
signature_algorithm,
base::as_bytes(base::make_span(sign_waiter.signature())),
base::as_bytes(base::make_span(public_key_spki_der))));
signature_verifier.VerifyUpdate(
base::as_bytes(base::make_span(data_to_sign)));
EXPECT_TRUE(signature_verifier.VerifyFinal());
}
}
// Generates a key pair in tokens accessible from the profile under test and
// retrieves them.
IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest, GetAllKeys) {
// Generate key pair in every token.
std::map<std::string, std::string> token_key_map;
for (const std::string& token_id : GetParam().token_ids) {
const std::string public_key_spki_der = GenerateKeyPair(token_id);
ASSERT_FALSE(public_key_spki_der.empty());
token_key_map[token_id] = public_key_spki_der;
}
// Only keys in the requested token should be retrieved.
for (const std::string& token_id : GetParam().token_ids) {
GetAllKeysExecutionWaiter get_all_keys_waiter;
platform_keys_service()->GetAllKeys(token_id,
get_all_keys_waiter.GetCallback());
get_all_keys_waiter.Wait();
EXPECT_TRUE(get_all_keys_waiter.error_message().empty());
std::vector<std::string> public_keys = get_all_keys_waiter.public_keys();
EXPECT_EQ(public_keys.size(), 1U);
EXPECT_EQ(public_keys[0], token_key_map[token_id]);
}
}
IN_PROC_BROWSER_TEST_P(PlatformKeysServiceBrowserTest,
GetAllKeysWhenNoKeysGenerated) {
for (const std::string& token_id : GetParam().token_ids) {
GetAllKeysExecutionWaiter get_all_keys_waiter;
platform_keys_service()->GetAllKeys(token_id,
get_all_keys_waiter.GetCallback());
get_all_keys_waiter.Wait();
EXPECT_TRUE(get_all_keys_waiter.error_message().empty());
std::vector<std::string> public_keys = get_all_keys_waiter.public_keys();
EXPECT_EQ(public_keys.size(), 0U);
}
}
INSTANTIATE_TEST_SUITE_P(
AllSupportedProfileTypes,
PlatformKeysServiceBrowserTest,
::testing::Values(
TestConfig{ProfileToUse::kSigninProfile, {"system"}},
TestConfig{ProfileToUse::kUnaffiliatedUserProfile, {"user"}},
TestConfig{ProfileToUse::kAffiliatedUserProfile, {"user", "system"}}));
} // namespace platform_keys
} // namespace chromeos
| 38.188889
| 80
| 0.752109
|
sarang-apps
|
3741ebbac3567d9bd1d0fb3eee75a5c2a9b3a458
| 2,817
|
cpp
|
C++
|
src/input/SDLJoystickInput.cpp
|
benlamonica/tetra-table
|
521082f2a848d04608ef6368004e90e780ef62ea
|
[
"Apache-2.0"
] | null | null | null |
src/input/SDLJoystickInput.cpp
|
benlamonica/tetra-table
|
521082f2a848d04608ef6368004e90e780ef62ea
|
[
"Apache-2.0"
] | null | null | null |
src/input/SDLJoystickInput.cpp
|
benlamonica/tetra-table
|
521082f2a848d04608ef6368004e90e780ef62ea
|
[
"Apache-2.0"
] | null | null | null |
//
// SDLJoystickInput.cpp
// TetraTable
//
// Created by Ben La Monica on 3/23/15.
// Copyright (c) 2015 Benjamin Alan La Monica. All rights reserved.
//
#include "SDLJoystickInput.hpp"
#include "../util/SDLUtil.hpp"
#include <syslog.h>
#include <SDL2/SDL.h>
#include "../util/TimeUtil.hpp"
SDLJoystickInput::SDLJoystickInput(TetraTable *game, TetraTableInput::Ptr delegate) : TetraTableInput(game, delegate), m_direction(pieces::NONE){
}
SDLJoystickInput::~SDLJoystickInput() {
}
void SDLJoystickInput::getNextMove(std::vector<pieces::Move>& moves) {
SDLUtil& sdl = SDLUtil::instance();
using namespace pieces;
using namespace util;
SDLEvent::Ptr event = sdl.getNextEvent();
if (event && event->m_event.type >= 0x600 && event->m_event.type < 0x700) {
switch(event->m_event.type) {
case SDL_JOYAXISMOTION: {
Sint16 x = SDL_JoystickGetAxis(event->joy,0);
Sint16 y = SDL_JoystickGetAxis(event->joy,1);
syslog(LOG_WARNING, "axis event: x,y (%d,%d)", x, y);
if (x < 128) {
m_direction.store(LEFT);
m_repeatingStarts.store(now() + 200000000);
syslog(LOG_WARNING, "LEFT %lld (%lld)", m_repeatingStarts.load(), now());
} else if (x > 128) {
m_direction.store(RIGHT);
m_repeatingStarts.store(now() + 200000000);
syslog(LOG_WARNING, "RIGHT");
} else if (y > 128) {
syslog(LOG_WARNING, "DOWN");
m_repeatingStarts.store(now() + 200000000);
m_direction.store(DOWN);
} else {
m_repeatingStarts.store(INT64_MAX);
m_direction.store(NONE);
}
break;
}
case SDL_JOYBUTTONDOWN: {
Uint8 button = event->m_event.jbutton.button;
syslog(LOG_WARNING, "button %d %s", button, event->m_event.jbutton.state == SDL_PRESSED ? "pressed" : "released");
if (button == 0) {
moves.push_back(ROTATE_LEFT);
} else if (button == 1) {
moves.push_back(DROP);
} else if (button == 2) {
moves.push_back(HOLD_PIECE);
} else if (button == 3) {
moves.push_back(ROTATE_RIGHT);
} else if (button == 4) {
//moves.push_back(QUIT);
}
break;
}
}
moves.push_back(m_direction.load());
} else {
if (m_repeatingStarts.load() <= util::now()) {
moves.push_back(m_direction.load());
}
util::millisleep(30);
}
}
| 36.584416
| 145
| 0.520412
|
benlamonica
|
374816a086693c8e9be578dd2257e444b6fe5ab8
| 506
|
cpp
|
C++
|
Snipets/01_Decisiones/IfeIfAnidado.cpp
|
Gabroide/Learning-C
|
63a89b9b6b84e410756e70e346173d475a1802a6
|
[
"Apache-2.0"
] | null | null | null |
Snipets/01_Decisiones/IfeIfAnidado.cpp
|
Gabroide/Learning-C
|
63a89b9b6b84e410756e70e346173d475a1802a6
|
[
"Apache-2.0"
] | null | null | null |
Snipets/01_Decisiones/IfeIfAnidado.cpp
|
Gabroide/Learning-C
|
63a89b9b6b84e410756e70e346173d475a1802a6
|
[
"Apache-2.0"
] | null | null | null |
// IfeIfAnidado.cpp
// Programa para saber si el numero introducido es par o impar utilizando un bucle if
#include <iostream>
#include <stdlib.h>
int main()
{
int n;
std::cout << "Introduce un numero: ";
std::cin >> n;
if(n%2 == 0) // Calculamos el residuo del numero al dividirlo entre 2. Si el residuo es 0 el numero es par
std::cout << "El numero introducido es par" << std::endl;
else
std::cout << "El numero introducido es impar" << std::endl;
system("pause");
return 0;
}
| 22
| 114
| 0.65415
|
Gabroide
|
374e0ac796062606a9bbe986e290ee0a8b828c29
| 7,883
|
hpp
|
C++
|
Library/include/mavlink/v2.0/matrixpilot/mavlink_msg_serial_udb_extra_f2_a.hpp
|
Dieptranivsr/Ros_Diep
|
d790e75e6f5da916701b11a2fdf3e03b6a47086b
|
[
"MIT"
] | 10
|
2021-03-15T03:58:06.000Z
|
2021-12-30T15:33:38.000Z
|
devel/include/mavlink/v2.0/matrixpilot/mavlink_msg_serial_udb_extra_f2_a.hpp
|
arijitnoobstar/UAVProjectileCatcher
|
3c1bed80df167192cb4b971b58c891187628142e
|
[
"Apache-2.0"
] | 1
|
2021-09-09T15:29:31.000Z
|
2021-09-09T15:29:31.000Z
|
Library/include/mavlink/v2.0/matrixpilot/mavlink_msg_serial_udb_extra_f2_a.hpp
|
Dieptranivsr/Ros_Diep
|
d790e75e6f5da916701b11a2fdf3e03b6a47086b
|
[
"MIT"
] | 4
|
2021-03-06T09:35:58.000Z
|
2021-05-24T14:34:11.000Z
|
// MESSAGE SERIAL_UDB_EXTRA_F2_A support class
#pragma once
namespace mavlink {
namespace matrixpilot {
namespace msg {
/**
* @brief SERIAL_UDB_EXTRA_F2_A message
*
* Backwards compatible MAVLink version of SERIAL_UDB_EXTRA - F2: Format Part A
*/
struct SERIAL_UDB_EXTRA_F2_A : mavlink::Message {
static constexpr msgid_t MSG_ID = 170;
static constexpr size_t LENGTH = 61;
static constexpr size_t MIN_LENGTH = 61;
static constexpr uint8_t CRC_EXTRA = 103;
static constexpr auto NAME = "SERIAL_UDB_EXTRA_F2_A";
uint32_t sue_time; /*< Serial UDB Extra Time */
uint8_t sue_status; /*< Serial UDB Extra Status */
int32_t sue_latitude; /*< Serial UDB Extra Latitude */
int32_t sue_longitude; /*< Serial UDB Extra Longitude */
int32_t sue_altitude; /*< Serial UDB Extra Altitude */
uint16_t sue_waypoint_index; /*< Serial UDB Extra Waypoint Index */
int16_t sue_rmat0; /*< Serial UDB Extra Rmat 0 */
int16_t sue_rmat1; /*< Serial UDB Extra Rmat 1 */
int16_t sue_rmat2; /*< Serial UDB Extra Rmat 2 */
int16_t sue_rmat3; /*< Serial UDB Extra Rmat 3 */
int16_t sue_rmat4; /*< Serial UDB Extra Rmat 4 */
int16_t sue_rmat5; /*< Serial UDB Extra Rmat 5 */
int16_t sue_rmat6; /*< Serial UDB Extra Rmat 6 */
int16_t sue_rmat7; /*< Serial UDB Extra Rmat 7 */
int16_t sue_rmat8; /*< Serial UDB Extra Rmat 8 */
uint16_t sue_cog; /*< Serial UDB Extra GPS Course Over Ground */
int16_t sue_sog; /*< Serial UDB Extra Speed Over Ground */
uint16_t sue_cpu_load; /*< Serial UDB Extra CPU Load */
uint16_t sue_air_speed_3DIMU; /*< Serial UDB Extra 3D IMU Air Speed */
int16_t sue_estimated_wind_0; /*< Serial UDB Extra Estimated Wind 0 */
int16_t sue_estimated_wind_1; /*< Serial UDB Extra Estimated Wind 1 */
int16_t sue_estimated_wind_2; /*< Serial UDB Extra Estimated Wind 2 */
int16_t sue_magFieldEarth0; /*< Serial UDB Extra Magnetic Field Earth 0 */
int16_t sue_magFieldEarth1; /*< Serial UDB Extra Magnetic Field Earth 1 */
int16_t sue_magFieldEarth2; /*< Serial UDB Extra Magnetic Field Earth 2 */
int16_t sue_svs; /*< Serial UDB Extra Number of Sattelites in View */
int16_t sue_hdop; /*< Serial UDB Extra GPS Horizontal Dilution of Precision */
inline std::string get_name(void) const override
{
return NAME;
}
inline Info get_message_info(void) const override
{
return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA };
}
inline std::string to_yaml(void) const override
{
std::stringstream ss;
ss << NAME << ":" << std::endl;
ss << " sue_time: " << sue_time << std::endl;
ss << " sue_status: " << +sue_status << std::endl;
ss << " sue_latitude: " << sue_latitude << std::endl;
ss << " sue_longitude: " << sue_longitude << std::endl;
ss << " sue_altitude: " << sue_altitude << std::endl;
ss << " sue_waypoint_index: " << sue_waypoint_index << std::endl;
ss << " sue_rmat0: " << sue_rmat0 << std::endl;
ss << " sue_rmat1: " << sue_rmat1 << std::endl;
ss << " sue_rmat2: " << sue_rmat2 << std::endl;
ss << " sue_rmat3: " << sue_rmat3 << std::endl;
ss << " sue_rmat4: " << sue_rmat4 << std::endl;
ss << " sue_rmat5: " << sue_rmat5 << std::endl;
ss << " sue_rmat6: " << sue_rmat6 << std::endl;
ss << " sue_rmat7: " << sue_rmat7 << std::endl;
ss << " sue_rmat8: " << sue_rmat8 << std::endl;
ss << " sue_cog: " << sue_cog << std::endl;
ss << " sue_sog: " << sue_sog << std::endl;
ss << " sue_cpu_load: " << sue_cpu_load << std::endl;
ss << " sue_air_speed_3DIMU: " << sue_air_speed_3DIMU << std::endl;
ss << " sue_estimated_wind_0: " << sue_estimated_wind_0 << std::endl;
ss << " sue_estimated_wind_1: " << sue_estimated_wind_1 << std::endl;
ss << " sue_estimated_wind_2: " << sue_estimated_wind_2 << std::endl;
ss << " sue_magFieldEarth0: " << sue_magFieldEarth0 << std::endl;
ss << " sue_magFieldEarth1: " << sue_magFieldEarth1 << std::endl;
ss << " sue_magFieldEarth2: " << sue_magFieldEarth2 << std::endl;
ss << " sue_svs: " << sue_svs << std::endl;
ss << " sue_hdop: " << sue_hdop << std::endl;
return ss.str();
}
inline void serialize(mavlink::MsgMap &map) const override
{
map.reset(MSG_ID, LENGTH);
map << sue_time; // offset: 0
map << sue_latitude; // offset: 4
map << sue_longitude; // offset: 8
map << sue_altitude; // offset: 12
map << sue_waypoint_index; // offset: 16
map << sue_rmat0; // offset: 18
map << sue_rmat1; // offset: 20
map << sue_rmat2; // offset: 22
map << sue_rmat3; // offset: 24
map << sue_rmat4; // offset: 26
map << sue_rmat5; // offset: 28
map << sue_rmat6; // offset: 30
map << sue_rmat7; // offset: 32
map << sue_rmat8; // offset: 34
map << sue_cog; // offset: 36
map << sue_sog; // offset: 38
map << sue_cpu_load; // offset: 40
map << sue_air_speed_3DIMU; // offset: 42
map << sue_estimated_wind_0; // offset: 44
map << sue_estimated_wind_1; // offset: 46
map << sue_estimated_wind_2; // offset: 48
map << sue_magFieldEarth0; // offset: 50
map << sue_magFieldEarth1; // offset: 52
map << sue_magFieldEarth2; // offset: 54
map << sue_svs; // offset: 56
map << sue_hdop; // offset: 58
map << sue_status; // offset: 60
}
inline void deserialize(mavlink::MsgMap &map) override
{
map >> sue_time; // offset: 0
map >> sue_latitude; // offset: 4
map >> sue_longitude; // offset: 8
map >> sue_altitude; // offset: 12
map >> sue_waypoint_index; // offset: 16
map >> sue_rmat0; // offset: 18
map >> sue_rmat1; // offset: 20
map >> sue_rmat2; // offset: 22
map >> sue_rmat3; // offset: 24
map >> sue_rmat4; // offset: 26
map >> sue_rmat5; // offset: 28
map >> sue_rmat6; // offset: 30
map >> sue_rmat7; // offset: 32
map >> sue_rmat8; // offset: 34
map >> sue_cog; // offset: 36
map >> sue_sog; // offset: 38
map >> sue_cpu_load; // offset: 40
map >> sue_air_speed_3DIMU; // offset: 42
map >> sue_estimated_wind_0; // offset: 44
map >> sue_estimated_wind_1; // offset: 46
map >> sue_estimated_wind_2; // offset: 48
map >> sue_magFieldEarth0; // offset: 50
map >> sue_magFieldEarth1; // offset: 52
map >> sue_magFieldEarth2; // offset: 54
map >> sue_svs; // offset: 56
map >> sue_hdop; // offset: 58
map >> sue_status; // offset: 60
}
};
} // namespace msg
} // namespace matrixpilot
} // namespace mavlink
| 47.775758
| 83
| 0.523024
|
Dieptranivsr
|
374ebc05844425a2785be3d7ac1b445de32c8207
| 12,027
|
cpp
|
C++
|
src/mesh/mechanical/plane/fem_submesh.cpp
|
annierhea/neon
|
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
|
[
"MIT"
] | null | null | null |
src/mesh/mechanical/plane/fem_submesh.cpp
|
annierhea/neon
|
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
|
[
"MIT"
] | null | null | null |
src/mesh/mechanical/plane/fem_submesh.cpp
|
annierhea/neon
|
4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1
|
[
"MIT"
] | null | null | null |
#include "fem_submesh.hpp"
#include "exceptions.hpp"
#include "constitutive/constitutive_model_factory.hpp"
#include "geometry/projection.hpp"
#include "interpolations/interpolation_factory.hpp"
#include "material/material_property.hpp"
#include "mesh/material_coordinates.hpp"
#include "mesh/dof_allocator.hpp"
#include "numeric/mechanics"
#include "traits/mechanics.hpp"
#include <cfenv>
#include <chrono>
#include <termcolor/termcolor.hpp>
namespace neon::mechanical::plane
{
fem_submesh::fem_submesh(json const& material_data,
json const& simulation_data,
std::shared_ptr<material_coordinates>& coordinates,
basic_submesh const& submesh)
: detail::fem_submesh<plane::fem_submesh, plane::internal_variables_t>(submesh),
coordinates{coordinates},
sf(make_surface_interpolation(topology(), simulation_data)),
view(sf->quadrature().points()),
variables(std::make_shared<internal_variables_t>(elements() * sf->quadrature().points())),
cm(make_constitutive_model(variables, material_data, simulation_data))
{
// Allocate storage for the displacement gradient
variables->add(variable::second::displacement_gradient,
variable::second::deformation_gradient,
variable::second::cauchy_stress,
variable::scalar::DetF);
// Get the old data to the undeformed configuration
for (auto& F : variables->get(variable::second::deformation_gradient))
{
F = matrix2::Identity();
}
variables->commit();
dof_allocator(node_indices, dof_list, traits::dof_order);
}
void fem_submesh::save_internal_variables(bool const have_converged)
{
if (have_converged)
{
variables->commit();
}
else
{
variables->revert();
}
}
std::pair<index_view, matrix> fem_submesh::tangent_stiffness(std::int64_t const element) const
{
auto const x = geometry::project_to_plane(
coordinates->current_configuration(local_node_view(element)));
matrix ke = material_tangent_stiffness(x, element);
if (!cm->is_finite_deformation()) return {local_dof_view(element), ke};
ke.noalias() += geometric_tangent_stiffness(x, element);
return {local_dof_view(element), ke};
}
std::pair<index_view, vector> fem_submesh::internal_force(std::int64_t const element) const
{
auto const x = geometry::project_to_plane(
coordinates->current_configuration(local_node_view(element)));
return {local_dof_view(element), internal_nodal_force(x, element)};
}
matrix fem_submesh::geometric_tangent_stiffness(matrix2x const& x, std::int64_t const element) const
{
auto const& cauchy_stresses = variables->get(variable::second::cauchy_stress);
auto const n = nodes_per_element();
matrix const kgeo = sf->quadrature()
.integrate(matrix::Zero(n, n).eval(),
[&](auto const& femval, auto const& l) -> matrix {
auto const& [N, rhea] = femval;
matrix2 const Jacobian = local_deformation_gradient(rhea,
x);
auto const cauchy = cauchy_stresses[view(element, l)];
// Compute the symmetric gradient operator
auto const L = (rhea * Jacobian.inverse()).transpose();
return L.transpose() * cauchy * L * Jacobian.determinant();
});
return identity_expansion(kgeo, dofs_per_node());
}
matrix fem_submesh::material_tangent_stiffness(matrix2x const& x, std::int64_t const element) const
{
auto const local_dofs = nodes_per_element() * dofs_per_node();
auto const& tangent_operators = variables->get(variable::fourth::tangent_operator);
return sf->quadrature().integrate(matrix::Zero(local_dofs, local_dofs).eval(),
[&](auto const& femval, auto const& l) -> matrix {
auto const& [N, rhea] = femval;
auto const& D = tangent_operators[view(element, l)];
matrix2 const Jacobian{local_deformation_gradient(rhea, x)};
auto const B = fem::sym_gradient<2>(
(rhea * Jacobian.inverse()).transpose());
return B.transpose() * D * B * Jacobian.determinant();
});
}
vector fem_submesh::internal_nodal_force(matrix2x const& x, std::int64_t const element) const
{
auto const& cauchy_stresses = variables->get(variable::second::cauchy_stress);
auto const [m, n] = std::make_tuple(nodes_per_element(), dofs_per_node());
vector fint = vector::Zero(m * n);
sf->quadrature().integrate(Eigen::Map<row_matrix>(fint.data(), m, n),
[&](auto const& femval, auto const& l) -> row_matrix {
auto const& [N, dN] = femval;
matrix2 const Jacobian = local_deformation_gradient(dN, x);
auto const& cauchy_stress = cauchy_stresses[view(element, l)];
// Compute the symmetric gradient operator
auto const Bt = dN * Jacobian.inverse();
return Bt * cauchy_stress * Jacobian.determinant();
});
return fint;
}
std::pair<index_view, matrix> fem_submesh::consistent_mass(std::int64_t const element) const
{
auto const X = coordinates->initial_configuration(local_node_view(element));
return {local_dof_view(element), X};
// auto const density_0 = cm->intrinsic_material().initial_density();
//
// auto m = sf->quadrature().integrate(matrix::Zero(nodes_per_element(), nodes_per_element()).eval(),
// [&](auto const& femval, auto const& l) -> matrix {
// auto const & [N, dN] = femval;
//
// auto const Jacobian = local_deformation_gradient(dN, X);
//
// return N * density_0 * N.transpose()
// * Jacobian.determinant();
// });
// return {local_dof_view(element), identity_expansion(m, dofs_per_node())};
}
std::pair<index_view, vector> fem_submesh::diagonal_mass(std::int64_t const element) const
{
auto const& [dofs, consistent_m] = this->consistent_mass(element);
vector diagonal_m(consistent_m.rows());
for (auto i = 0; i < consistent_m.rows(); ++i)
{
diagonal_m(i) = consistent_m.row(i).sum();
}
return {local_dof_view(element), diagonal_m};
}
void fem_submesh::update_internal_variables(double const time_step_size)
{
std::feclearexcept(FE_ALL_EXCEPT);
update_deformation_measures();
update_Jacobian_determinants();
cm->update_internal_variables(time_step_size);
if (std::fetestexcept(FE_INVALID))
{
throw computational_error("Floating point error reported\n");
}
}
void fem_submesh::update_deformation_measures()
{
auto& H_list = variables->get(variable::second::displacement_gradient);
auto& F_list = variables->get(variable::second::deformation_gradient);
for (std::int64_t element{0}; element < elements(); ++element)
{
// Gather the material coordinates
auto const X = geometry::project_to_plane(
coordinates->initial_configuration(local_node_view(element)));
auto const x = geometry::project_to_plane(
coordinates->current_configuration(local_node_view(element)));
sf->quadrature().for_each([&](auto const& femval, const auto& l) {
auto const& [N, rhea] = femval;
// Local deformation gradient for the initial configuration
matrix2 const F_0 = local_deformation_gradient(rhea, X);
matrix2 const F = local_deformation_gradient(rhea, x);
// Gradient operator in index notation
auto const& B_0t = rhea * F_0.inverse();
// Displacement gradient
matrix2 const H = (x - X) * B_0t;
H_list[view(element, l)] = H;
F_list[view(element, l)] = F * F_0.inverse();
});
}
}
void fem_submesh::update_Jacobian_determinants()
{
auto const& F = variables->get(variable::second::deformation_gradient);
auto& F_det = variables->get(variable::scalar::DetF);
std::transform(begin(F), end(F), begin(F_det), [](auto const& F) { return F.determinant(); });
auto const found = std::find_if(begin(F_det), end(F_det), [](auto const value) {
return value <= 0.0;
});
if (found != F_det.end())
{
auto const i = std::distance(begin(F_det), found);
auto const [element, quadrature_point] = std::div(i, sf->quadrature().points());
throw computational_error("Positive Jacobian assumption violated at element "
+ std::to_string(element) + " and local quadrature point "
+ std::to_string(quadrature_point) + " (" + std::to_string(*found)
+ ")");
}
}
std::pair<vector, vector> fem_submesh::nodal_averaged_variable(variable::scalar const scalar_name) const
{
vector count = vector::Zero(coordinates->size());
vector value = count;
auto const& scalar_list = variables->get(scalar_name);
auto const& E = sf->local_quadrature_extrapolation();
// vector format of values
vector component = vector::Zero(sf->quadrature().points());
for (std::int64_t element{0}; element < elements(); ++element)
{
for (std::size_t l{0}; l < sf->quadrature().points(); ++l)
{
component(l) = scalar_list[view(element, l)];
}
// Local extrapolation to the nodes
vector const nodal_component = E * component;
// Assemble these into the global value vector
auto const& node_list = local_node_view(element);
for (auto n = 0; n < nodal_component.rows(); n++)
{
value(node_list[n]) += nodal_component(n);
count(node_list[n]) += 1.0;
}
}
return {value, count};
}
std::pair<vector, vector> fem_submesh::nodal_averaged_variable(variable::second const tensor_name) const
{
vector count = vector::Zero(coordinates->size() * 4);
vector value = count;
auto const& tensor_list = variables->get(tensor_name);
matrix const E = sf->local_quadrature_extrapolation();
// vector format of values
vector component(sf->quadrature().points());
for (std::int64_t element{0}; element < elements(); ++element)
{
// Assemble these into the global value vector
auto const& node_list = local_node_view(element);
for (auto ci = 0; ci < 2; ++ci)
{
for (auto cj = 0; cj < 2; ++cj)
{
for (std::size_t l{0}; l < sf->quadrature().points(); ++l)
{
component(l) = tensor_list[view(element, l)](ci, cj);
}
// Local extrapolation to the nodes
vector const nodal_component = E * component;
for (auto n = 0; n < nodal_component.rows(); n++)
{
value(node_list[n] * 4 + ci * 2 + cj) += nodal_component(n);
count(node_list[n] * 4 + ci * 2 + cj) += 1.0;
}
}
}
}
return {value, count};
}
}
| 36.445455
| 105
| 0.579529
|
annierhea
|
3753e8029f41cd6f3f89d6a217e100fa572871af
| 20,003
|
cpp
|
C++
|
src/zutil/conn.cpp
|
mgwoo/OpenDB
|
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
|
[
"BSD-3-Clause"
] | 1
|
2021-03-04T02:35:47.000Z
|
2021-03-04T02:35:47.000Z
|
src/zutil/conn.cpp
|
mgwoo/OpenDB
|
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
|
[
"BSD-3-Clause"
] | null | null | null |
src/zutil/conn.cpp
|
mgwoo/OpenDB
|
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, Nefelus Inc
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "conn.h"
#include "wire.h"
#include "zui.h"
Ath__connWord::Ath__connWord(uint r1, uint c1)
{
_conn._fromRow= r1;
_conn._fromCol= c1;
_conn._toRow= 0;
_conn._toCol= 0;
_conn._ordered= 0;
_conn._placed= 0;
_conn._posFlow= 0;
_conn._corner= 0;
_conn._straight= 0;
_conn._dir= 0;
}
Ath__connWord::Ath__connWord(uint r1, uint c1, uint type)
{
_conn._fromRow= r1;
_conn._fromCol= c1;
_conn._toRow= type;
_conn._toCol= type;
_conn._ordered= 0;
_conn._placed= 0;
_conn._posFlow= 0;
_conn._corner= 0;
_conn._straight= 0;
_conn._dir= 0;
}
bool Ath__connWord::ordered()
{
return (_conn._ordered>0) ? true : false;
}
void Ath__connWord::orderByRow(uint r1, uint c1, uint r2, uint c2, uint colCnt)
{
if (r1>r2) {
set(r2, c2, r1, c1, colCnt);
_conn._ordered= 1;
}
else {
set(r1, c1, r2, c2, colCnt);
}
}
Ath__connWord::Ath__connWord(uint r1, uint c1, uint r2, uint c2, uint colCnt)
{
set(r1, c1, r2, c2, colCnt);
_conn._ordered= 0;
_conn._placed= 0;
_conn._posFlow= 0;
_conn._corner= 0;
_conn._straight= 0;
_conn._dir= 0;
if (getRowDist()==0) {
_conn._straight= 1;
if (c1>c2) {
set(r1, c1, r2, c2, colCnt);
_conn._fromCol= c2;
_conn._toCol= c1;
_conn._ordered= 1;
}
}
else if (getColDist()==0) {
_conn._straight= 1;
_conn._dir= 1;
if (r1>r2) {
_conn._fromRow= r2;
_conn._toRow= r1;
_conn._ordered= 1;
}
}
else {
orderByRow(r1, c1, r2, c2, colCnt);
_conn._corner= 1;
}
}
int Ath__connWord::getStraight()
{
if (_conn._straight>0)
return _conn._dir;
else
return -1;
}
int Ath__connWord::getRowDist()
{
return _conn._toRow - _conn._fromRow;
}
int Ath__connWord::getColDist()
{
return _conn._toCol - _conn._fromCol;
}
uint Ath__connWord::getDist()
{
return ath__max(getRowDistAbs(), getColDistAbs()) ;
}
uint Ath__connWord::getMinDist()
{
return ath__min(getRowDistAbs(), getColDistAbs()) ;
}
uint Ath__connWord::getMaxDist()
{
return ath__max(getRowDistAbs(), getColDistAbs()) ;
}
uint Ath__connWord::getRowDistAbs()
{
int dist= getRowDist();
if (dist<0)
return -dist;
else
return dist;
}
uint Ath__connWord::getSeg(uint *c1, uint *c2)
{
if (_conn._straight==0)
return 0;
if (_conn._dir==0) {
*c2= _conn._toCol;
*c1= _conn._fromCol;
return _conn._fromRow;
}
else {
*c2= _conn._toRow;
*c1= _conn._fromRow;
return _conn._fromCol;
}
}
uint Ath__connWord::getColDistAbs()
{
int dist= getColDist();
if (dist<0)
return -dist;
else
return dist;
}
Ath__connWord::Ath__connWord(uint v)
{
setAll(v);
}
uint Ath__connWord::getAll()
{
return _all;
}
void Ath__connWord::setAll(uint v)
{
_all= v;
}
uint Ath__connWord::getFromRowCol(uint *col)
{
*col= _conn._fromCol;
return _conn._fromRow;
}
uint Ath__connWord::getToRowCol(uint *col)
{
*col= _conn._toCol;
return _conn._toRow;
}
uint Ath__connWord::getFrom()
{
return _conn._colCnt * _conn._fromRow + _conn._fromCol;
}
uint Ath__connWord::getTo()
{
return _conn._colCnt * _conn._toRow + _conn._toCol;
}
uint Ath__connWord::set(uint x1, uint y1, uint x2, uint y2, uint colCnt)
{
_conn._fromRow= x1;
_conn._fromCol= y1;
_conn._toRow= x2;
_conn._toCol= y2;
_conn._colCnt= colCnt;
return _all;
}
void Ath__p2pConn::setNext(Ath__p2pConn *v)
{
_next= v;
}
void Ath__p2pConn::setPin(Ath__qPin *q)
{
_srcPin= q;
}
Ath__qPin *Ath__p2pConn::getSrcPin()
{
return _srcPin;
}
Ath__connTable::Ath__connTable(AthPool<Ath__p2pConn> *pool, uint n,
uint pinLength, uint tileSize)
{
if (n==0)
n=32;
_nextSegCnt= 2;
_tileSize= 0;
_pinLength= 0;
if (tileSize>0) {
_nextSegCnt= tileSize/pinLength+1;
_tileSize= tileSize;
_pinLength= pinLength;
}
_maxBankCnt= n;
_straightTable[0]= new Ath__array2d<Ath__p2pConn*>(n, true);
_straightTable[1]= new Ath__array2d<Ath__p2pConn*>(n, true);
_nextTable[0]= new Ath__array2d<Ath__p2pConn*>(_nextSegCnt);
_nextTable[1]= new Ath__array2d<Ath__p2pConn*>(_nextSegCnt);
_cornerTable= new Ath__array2d<Ath__p2pConn*>(2*n, true);
_tmpTablePtr= NULL;
_tmpArrayPtr= NULL;
_poolPtr= pool;
//_poolPtr= new AthPool<Ath__p2pConn>(1024);
}
uint Ath__connTable::getSegmentIndex(uint dir, uint dx, uint dy)
{
if (_pinLength==0)
return 0;
if (dir>0) { // vertical
return dy/_pinLength;
}
else {
return dx/_pinLength;
}
}
Ath__p2pConn* Ath__connTable::addConn(uint netId, Ath__connWord w, uint dx, uint dy)
{
Ath__p2pConn* conn= _poolPtr->alloc();
conn->_netId= netId;
conn->_conn= w;
uint dist= w.getDist();
int dir= w.getStraight();
if (dir<0) {
_cornerTable->add(dist, conn);
}
else {
if (dist>1) {
_straightTable[dir]->add(dist, conn);
}
else {
if (dy==0) { // default
_nextTable[dir]->add(0, conn);
}
else {
uint kk= getSegmentIndex(dir, dx, dy);
_nextTable[dir]->add(kk, conn);
}
}
}
return conn;
}
uint Ath__connTable::addStraightConn(uint dir, uint dist, Ath__p2pConn* p2p)
{
return _straightTable[dir]->add(dist, p2p);
}
uint Ath__connTable::addCornerConn2(uint type, Ath__p2pConn* p2p, uint ii, uint jj)
{
Ath__connWord w(ii, jj, type);
p2p->_conn= w;
return _cornerTable->add(type, p2p);
}
void Ath__connTable::printConnStats(FILE *fp)
{
fprintf(fp, "\n\nNet length distribution per tile unit length\n");
fprintf(fp, "--------------------------------------------\n");
char buff[128];
for (uint ii= 0; ii<_nextSegCnt; ii++) {
sprintf(buff, " next tile HORIZONTAL conns - Length= %7d", (ii+1)*_pinLength);
_nextTable[0]->printCnt(fp, ii, buff);
}
fprintf(fp, "\n");
for (uint jj= 0; jj<_nextSegCnt; jj++) {
sprintf(buff, " next tile VERTICAL conns - Length= %7d", (jj+1)*_pinLength);
_nextTable[1]->printCnt(fp, jj, buff);
}
fprintf(fp, "\n\n--------- straight tile-feedthru's\n");
_straightTable[0]->printAllCnts(fp, "tile-dist", " HORIZONTAL");
_straightTable[1]->printAllCnts(fp, "tile-dist", " VERTICAL");
fprintf(fp, "\n\n--------- corner tile-feedthru's\n");
_cornerTable->printAllCnts(fp, "tile-dist", "CORNER");
}
uint Ath__connTable::startNextIterator(uint dir, uint seg)
{
_tmpTablePtr= _nextTable[dir];
return _tmpTablePtr->startIterator(seg);
}
uint Ath__connTable::startCornerIterator(uint dist)
{
_tmpTablePtr= _cornerTable;
return _tmpTablePtr->startIterator(dist);
}
uint Ath__connTable::startStraightIterator(uint dir, uint dist)
{
_tmpTablePtr= _straightTable[dir];
return _tmpTablePtr->startIterator(dist);
}
int Ath__connTable::getNextConn(Ath__connWord *conn, uint *netId)
{
Ath__p2pConn* p2p= NULL;
uint next= _tmpTablePtr->getNext(&p2p);
if (next==0)
return 0;
*netId= p2p->_netId;
*conn= p2p->_conn;
return next;
}
Ath__p2pConn* Ath__connTable::getNextConn()
{
Ath__p2pConn* p2p= NULL;
if (_tmpTablePtr->getNext(&p2p)==0)
return NULL;
return p2p;
}
Ath__array2d<Ath__p2pConn*>* Ath__connTable::startStraightArrayIterator(uint dir)
{
_tmpArrayPtr= _straightTable[dir];
for (uint ii= 0; ii<_maxBankCnt; ii++) {
_tmpCurrentIndex[ii]= 0;
_tmpCnt[ii]= _tmpArrayPtr->getCnt(ii);
}
return _tmpArrayPtr;
}
bool Ath__connTable::getNextArrayConn(uint ii, Ath__connWord *conn, uint *netId)
{
if (_tmpCurrentIndex[ii]>=_tmpCnt[ii])
return false;
Ath__p2pConn* p2p= _tmpArrayPtr->get(ii, _tmpCurrentIndex[ii]);
_tmpCurrentIndex[ii] ++;
*netId= p2p->_netId;
*conn= p2p->_conn;
return true;
}
uint Ath__qPin::getToRowCol(uint *col)
{
return _conn.getToRowCol(col);
}
uint Ath__qPin::getTurnRowCol(uint *row, uint *col)
{
Ath__qPin* src= getSrcPin();
*row= src->_head->_conn.getFromRowCol(col);
uint tmp1; //TODO
return src->_head->_conn.getToRowCol(&tmp1);
}
int Ath__qPin::getTurnDist(uint *row, uint *col, int *dir)
{
uint turnRow, turnCol;
getTurnRowCol(&turnRow, &turnCol);
int rowDist= turnRow - *row;
int colDist= turnCol - *col;
if (rowDist==0) // horizontal
{
*dir= 1;
if (colDist<0)
{
*col= turnCol;
return -colDist;
}
return colDist;
}
if (colDist==0) // vertical
{
*dir= 0;
if (rowDist<0)
{
*row= turnRow;
return -rowDist;
}
return rowDist;
}
*dir= -1;
return -1;
}
bool Ath__qPin::isTargeted()
{
return (_targeted>0) ? true : false;
}
bool Ath__qPin::isAssigned()
{
return (_assigned>0) ? true : false;
}
void Ath__qPin::setTargeted()
{
_targeted= 1;
}
void Ath__qPin::setPlaced()
{
_placed= 1;
}
bool Ath__qPin::isPlaced()
{
return (_placed>0) ? true : false;
}
bool Ath__qPin::isSrc()
{
return (_src>0) ? true : false;
}
Ath__qPin* Ath__qPin::getSrcPin()
{
if (_src>0)
return this;
else
return _head->getSrcPin();
}
Ath__qPin* Ath__qPin::getDstPin()
{
if (_src>0)
return _next;
else
return this;
}
Ath__box *Ath__qPin::getInstBox()
{
return _instBB;
}
uint Ath__qPin::getLayer()
{
if (_portBB!=NULL)
return _portBB->_layer;
if (_targetBB!=NULL)
return _targetBB->_layer;
if (_instBB!=NULL)
return _instBB->_layer;
return 0;
}
void Ath__qPin::addBusBox(Ath__box *bb)
{
bb->_next= _busList;
_busList= bb;
}
void Ath__qPin::setInstBox(Ath__box *bb)
{
_instBB= bb;
}
void Ath__qPin::getNextObsBox(Ath__searchBox *sbb)
{
Ath__box *bb= _obsList;
if (_obsList->_next!=NULL)
bb= _obsList->_next;
sbb->set(bb->_xlo, bb->_ylo, bb->_xhi, bb->_yhi, bb->_layer, 0);
}
void Ath__qPin::getObsBox(Ath__searchBox *sbb)
{
Ath__box *bb= _obsList;
sbb->set(bb->_xlo, bb->_ylo, bb->_xhi, bb->_yhi, bb->_layer, 0);
}
void Ath__qPin::getTargetBox(Ath__searchBox *bb)
{
bb->set(_targetBB->_xlo, _targetBB->_ylo,
_targetBB->_xhi, _targetBB->_yhi, _targetBB->_layer, 0);
}
uint Ath__qPin::makeZuiObject(Ath__zui *zui, uint width, bool actual, bool instFlag)
{
if (width<=0)
width= 1000;
if (instFlag) {
uint w2= width/2;
zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _instBB->_layer,
_instBB->getMidX()-w2, _instBB->getMidY()-w2,
_instBB->getMidX()+w2, _instBB->getMidY()+w2);
return _instBB->_layer;
}
if (actual && (_portBB!=NULL))
{
int x1= _portBB->_xlo;
int y1= _portBB->_ylo;
int x2= _portBB->_xhi;
int y2= _portBB->_yhi;
zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _portBB->_layer,
x1, y1, x2, y2);
return _portBB->_layer;
}
if (_targetBB!=NULL)
{
uint w2= width/2;
int x1= _targetBB->_xlo;
int y1= _targetBB->_ylo;
int x2= _targetBB->_xhi;
int y2= _targetBB->_yhi;
if (x1==x2)
{
x1 -= w2;
x2 += w2;
}
else if (y1==y2)
{
y1 -= w2;
y2 += w2;
}
zui->addBox(_nameId, Ath_box__pin, Ath_hier__tile, _targetBB->_layer,
x1, y1, x2, y2);
return _targetBB->_layer;
}
}
Ath__box* Ath__qPin::getPortCoords(int *x1, int *y1, int *x2, int *y2, uint *layer)
{
if (_portBB==NULL)
return NULL;
*x1= _portBB->_xlo;
*y1= _portBB->_ylo;
*x2= _portBB->_xhi;
*y2= _portBB->_yhi;
*layer= _portBB->_layer;
return _portBB;
}
Ath__box* Ath__qPin::getBusList()
{
return _busList;
}
uint Ath__qPin::makePinObsZui(Ath__zui *zui, int width, int x1, int y1, int x2, int y2, int layer)
{
uint w2= width/2;
if (x1==x2)
{
x1 -= w2;
x2 += w2;
}
else if (y1==y2)
{
y1 -= w2;
y2 += w2;
}
return zui->addBox(_nameId, Ath_box__bus, Ath_hier__tile, layer,
x1, y1, x2, y2);
}
uint Ath__qPin::makeBusZuiObject(Ath__zui *zui, uint width)
{
uint cnt= 0;
// if (obs==NULL) // nextTile shapes don't have shapes
for (Ath__box *obs= _obsList; obs!=NULL; obs= obs->_next)
{
cnt += makePinObsZui(zui, width,
obs->_xlo, obs->_ylo, obs->_xhi, obs->_yhi, obs->_layer);
}
return cnt;
}
void Ath__qPin::reset()
{
_src= 0;
_tjunction= 0;
_placed= 0;
_fixed= 0;
_assigned= 0;
_targeted= 0;
_nameId= 0;
_instBB= NULL;
_targetBB= NULL;
_portBB= NULL;
_portWireId= 0;
_obsList= NULL;
_busList= NULL;
}
void Ath__qPin::setPortWireId(uint id)
{
_portWireId= id;
}
void Ath__qPin::pinBoxDef(FILE *fp, char *layerName, char *orient, int defUnits)
{
fprintf(stdout, "TODO: pinBoxDef\n");
return;
/*
fprintf(fp, " ( %d %d ) %s ", _bb->_xlo/defUnits, _bb->_ylo/defUnits, orient);
fprintf(fp, " + LAYER %s ( %d %d ) ( %d %d ) ", layerName,
0, 0, _bb->getDX()/defUnits, _bb->getDY()/defUnits);
*/
}
Ath__qPinTable::Ath__qPinTable(AthPool<Ath__qPin> *qPinPool, AthPool<Ath__box> *boxPool, uint n)
{
_table= new Ath__array1D<Ath__qPin*>(n);
for (uint jj= 0; jj<2; jj++) {
_nextPinShape[jj]= NULL;
_straightPinShape[jj]= NULL;
_thruObsShape[jj]= NULL;
}
for (uint ii= 0; ii<4; ii++) {
_cornerPinShape[ii]= NULL;
_cornerObsShape[ii]= NULL;
}
_pool= qPinPool;
//_pool->setDbg(1);
_pinBoxPool= boxPool;
}
Ath__box* Ath__qPinTable::getHeadStraightPinShape(uint dir)
{
return _straightPinShape[dir];
}
Ath__box* Ath__qPinTable::getHeadNextPinShape(uint dir)
{
return _nextPinShape[dir];
}
Ath__box* Ath__qPinTable::getHeadCornerPinShape(uint type)
{
return _cornerPinShape[type];
}
Ath__box* Ath__qPinTable::getHeadCornerObsShape(uint type)
{
return _cornerObsShape[type];
}
Ath__box* Ath__qPinTable::getHeadObsShape(uint dir)
{
return _thruObsShape[dir];
}
void Ath__qPinTable::freeBoxes(Ath__box *head)
{
Ath__box *e= head;
while (e!=NULL) {
Ath__box *f= e->_next;
_pinBoxPool->free(e);
e= f;
}
}
void Ath__qPinTable::freeNextPinShapes()
{
freeBoxes(_nextPinShape[0]);
freeBoxes(_nextPinShape[1]);
_nextPinShape[0]= NULL;
_nextPinShape[1]= NULL;
}
Ath__box* Ath__qPinTable::newPinBox(uint layer, int x1, int y1, int x2, int y2)
{
uint n;
Ath__box *a= _pinBoxPool->alloc(NULL, &n);
a->set(x1, y1, x2, y2);
a->_id= n;
a->_layer= layer;
return a;
}
Ath__box* Ath__qPinTable::addPinBox(Ath__box *e, Ath__box *head)
{
e->_next= head;
return e;
}
Ath__box* Ath__qPinTable::addNextPinBox(uint pinId, uint dir, uint layer, int x1, int y1, int x2, int y2)
{
Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2);
bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile);
_nextPinShape[dir]= addPinBox(bbPin, _nextPinShape[dir]);
return bbPin;
}
Ath__box* Ath__qPinTable::addThruObsBox(uint netId, uint dir, uint layer, int x1, int y1, int x2, int y2)
{
Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2);
bbPin->setIdentity(Ath_box__bus, netId, Ath_hier__tile);
_thruObsShape[dir]= addPinBox(bbPin, _thruObsShape[dir]);
return _thruObsShape[dir];
}
Ath__box* Ath__qPinTable::addCornerPinBox(uint pinId, uint type, uint layer, int x1, int y1, int x2, int y2)
{
Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2);
bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile);
_cornerPinShape[type]= addPinBox(bbPin, _cornerPinShape[type]);
return _cornerPinShape[type];
}
Ath__box* Ath__qPinTable::addCornerObsBox(uint netId, uint type, uint layer, int x1, int y1, int x2, int y2)
{
Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2);
bbPin->setIdentity(Ath_box__bus, netId, Ath_hier__tile);
_cornerObsShape[type]= addPinBox(bbPin, _cornerObsShape[type]);
return bbPin;
}
Ath__box* Ath__qPinTable::addStraightPinBox(uint pinId, uint dir, uint layer, int x1, int y1, int x2, int y2)
{
Ath__box* bbPin= newPinBox(layer, x1, y1, x2, y2);
bbPin->setIdentity(Ath_box__pin, pinId, Ath_hier__tile);
_straightPinShape[dir]= addPinBox(bbPin, _straightPinShape[dir]);
return bbPin;
}
Ath__qPinTable::~Ath__qPinTable()
{
for (uint jj= 0; jj<2; jj++) {
freeBoxes(_nextPinShape[jj]);
freeBoxes(_straightPinShape[jj]);
freeBoxes(_thruObsShape[jj]);
freeBoxes(_cornerPinShape[jj]);
}
freeBoxes(_cornerPinShape[2]);
freeBoxes(_cornerPinShape[3]);
}
Ath__qPin* Ath__qPinTable::addPin(Ath__qPin* next, uint netId, uint ioNetId, Ath__connWord w, AthPool<Ath__qPin> *pool)
{
uint id;
Ath__qPin* pin= _pool->alloc(NULL, &id);
pin->_conn= w;
pin->reset();
pin->_netId= netId;
pin->_ioNetId= ioNetId;
pin->_nameId= id;
pin->_next= NULL;
if (next!=NULL) {
next->_next= pin;
pin->_src= 0;
}
else {
_table->add(pin);
pin->_src= 1;
}
return pin;
}
Ath__qPin *Ath__qPinTable::getNextSrcPin_next()
{
Ath__qPin *srcPin;
while (_table->getNext(srcPin)) {
if (srcPin->_src==0)
continue;
int cornerFlag= srcPin->_conn.getStraight();
if (cornerFlag<0)
continue;
if (srcPin->_conn.getDist()>1)
continue;
return srcPin;
}
return NULL;
}
Ath__qPin *Ath__qPinTable::getNextSrcPin_thru()
{
Ath__qPin *srcPin;
while (_table->getNext(srcPin)) {
if (srcPin->_src==0)
continue;
if (srcPin->_conn.getStraight()<0)
continue;
if (srcPin->_conn.getDist()<2)
continue;
return srcPin;
}
return NULL;
}
Ath__qPin *Ath__qPinTable::getNextSrcPin_corner()
{
Ath__qPin *srcPin;
while (_table->getNext(srcPin)) {
if (srcPin->_src==0)
continue;
int cornerFlag= srcPin->_conn.getStraight();
if (cornerFlag>=0)
continue;
// if (srcPin->_conn.getDist()>1)
// continue;
if (srcPin->_assigned==0)
continue;
return srcPin;
}
return NULL;
}
Ath__qPin *Ath__qPinTable::getNextSrcPin_all()
{
Ath__qPin *srcPin;
while (_table->getNext(srcPin)) {
if (srcPin->_src==0)
continue;
return srcPin;
}
return NULL;
}
bool Ath__qPinTable::startIterator()
{
if (_table->getCnt()<=0)
return false;
_table->resetIterator();
return true;
}
uint Ath__qPinTable::getCnt()
{
return _table->getCnt();
}
Ath__qPin *Ath__qPinTable::get(uint ii)
{
return _table->get(ii);
}
Ath__qBus::Ath__qBus(uint n)
{
_table= new Ath__array1D<Ath__p2pConn*>(n);
}
void Ath__qBus::addConn(Ath__p2pConn *conn)
{
_table->add(conn);
}
uint Ath__qBus::getCnt()
{
return _table->getCnt();
}
Ath__p2pConn *Ath__qBus::get(uint ii)
{
return _table->get(ii);
}
| 22.399776
| 120
| 0.653602
|
mgwoo
|
375eaa78b581f84c658ae81f2e900ae9266ba765
| 212
|
hpp
|
C++
|
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
archive/stan/src/stan/lang/ast/node/omni_idx_def.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_LANG_AST_NODE_OMNI_IDX_DEF_HPP
#define STAN_LANG_AST_NODE_OMNI_IDX_DEF_HPP
#include <stan/lang/ast.hpp>
namespace stan {
namespace lang {
omni_idx::omni_idx() { }
}
}
#endif
| 15.142857
| 44
| 0.707547
|
alashworth
|
37614210247916dca3bae49177d706bb01b9dda6
| 886
|
cc
|
C++
|
test/unit/logging_test.cc
|
onedata/helpers
|
bf14082d5a8de384c1f126b2fa522c3b360ad500
|
[
"MIT"
] | 1
|
2018-06-04T08:08:11.000Z
|
2018-06-04T08:08:11.000Z
|
test/unit/logging_test.cc
|
onedata/helpers
|
bf14082d5a8de384c1f126b2fa522c3b360ad500
|
[
"MIT"
] | 1
|
2019-03-26T11:15:13.000Z
|
2019-03-26T11:15:13.000Z
|
test/unit/logging_test.cc
|
onedata/helpers
|
bf14082d5a8de384c1f126b2fa522c3b360ad500
|
[
"MIT"
] | 1
|
2018-02-05T09:19:45.000Z
|
2018-02-05T09:19:45.000Z
|
/**
* @file logging_test.cc
* @author Bartek Kryza
* @copyright (C) 2018 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "helpers/logging.h"
#include "testUtils.h"
#include "boost/algorithm/string.hpp"
#include <gtest/gtest.h>
#include <sstream>
#include <string>
using namespace ::testing;
using namespace one;
using namespace one::logging;
struct LoggingTest : public ::testing::Test {
LoggingTest() { }
~LoggingTest() { }
void SetUp() override { }
void TearDown() override { }
};
std::string function2() { return one::logging::print_stacktrace(); }
std::string function1() { return function2(); }
TEST_F(LoggingTest, loggingStackTraceShouldWork)
{
auto log = function1();
ASSERT_TRUE(boost::contains(log, "function1"));
ASSERT_TRUE(boost::contains(log, "function2"));
}
| 20.604651
| 70
| 0.691874
|
onedata
|