<commit_before>// BEGIN CUT HERE

// END CUT HERE
#line 5 "TorusSailingEasy.cpp"
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <ctime>
using namespace std;
typedef long long ll;
#define clr(x,a) memset(x,a,sizeof(x))
#define sz(x) (int)x.size()
#define see(x) cerr<<#x<<" "<<x<<endl
#define se(x) cerr<<" "<<x
#define pb push_back
#define mp make_pair
const double eps=1e-5;

int n,m;
const int MAX_DAYS = 11*11;
const int MAX_I = 1000;
class TorusSailingEasy
{
        public:
        double expectedTime(int N, int M, int goalX, int goalY)
        {
			int xPos=0;
			int yPos=0;
			int i=0;
			int x=-1;
			bool passFlag=false;
			for (;;i++){
				xPos=i%N;
				yPos=i%M;
				if (xPos==0 && yPos==0 ){
					if (!passFlag){
						passFlag=true;
					}
					else{
						break;
					}
				}
				else if (xPos==goalX && yPos==goalY){
					x=i;
				}
			}
			if (x==-1){
				return -1.0f;
			}
			int y=i-x;
			if (y>x){
				swap(x,y);
			}
			int c[MAX_I+1][MAX_DAYS];
			for (int i=0;i<=MAX_DAYS;i++){
				c[0][i]=0;
			}
			c[0][y]=1;
			for (int i=1;i<=MAX_I;i++){
				for (int j=0;j<=x+y;j++){
					if (j<=0 && j<=x-2){
						c[i][j]=
					}
				}
			}

			return ;
        }

// 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 double &Expected, const double &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() { int Arg0 = 2; int Arg1 = 2; int Arg2 = 1; int Arg3 = 1; double Arg4 = 1.0; verify_case(0, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }
	void test_case_1() { int Arg0 = 2; int Arg1 = 2; int Arg2 = 0; int Arg3 = 1; double Arg4 = -1.0; verify_case(1, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }
	void test_case_2() { int Arg0 = 3; int Arg1 = 3; int Arg2 = 1; int Arg3 = 1; double Arg4 = 2.0; verify_case(2, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }
	void test_case_3() { int Arg0 = 4; int Arg1 = 6; int Arg2 = 1; int Arg3 = 3; double Arg4 = 27.0; verify_case(3, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }

// END CUT HERE

};
// BEGIN CUT HERE
int main()
{
        TorusSailingEasy ___test;
        //___test.run_test(-1);
		___test.run_test(2);
        system("pause");
        return 0;
}
// END CUT HERE
<commit_msg>new sol<commit_after>// BEGIN CUT HERE

// END CUT HERE
#line 5 "TorusSailingEasy.cpp"
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <ctime>
using namespace std;
typedef long long ll;
#define clr(x,a) memset(x,a,sizeof(x))
#define sz(x) (int)x.size()
#define see(x) cerr<<#x<<" "<<x<<endl
#define se(x) cerr<<" "<<x
#define pb push_back
#define mp make_pair
const double eps=1e-5;

int n,m;
const int MAX_DAYS = 11*11;
const int MAX_I = 1000;
class TorusSailingEasy
{
        public:
        double expectedTime(int N, int M, int goalX, int goalY)
        {
			int xPos=0;
			int yPos=0;
			int i=0;
			int x=-1;
			bool passFlag=false;
			for (;;i++){
				xPos=i%N;
				yPos=i%M;
				if (xPos==0 && yPos==0 ){
					if (!passFlag){
						passFlag=true;
					}
					else{
						break;
					}
				}
				else if (xPos==goalX && yPos==goalY){
					x=i;
				}
			}
			if (x==-1){
				return -1.0f;
			}
			int y=i-x;
			if (y>x){
				swap(x,y);
			}
			int c[MAX_I+1][MAX_DAYS];
			for (int i=0;i<=MAX_DAYS;i++){
				c[0][i]=0;
			}
			c[0][y]=1;
			for (int i=1;i<=MAX_I;i++){
				for (int j=0;j<=x+y;j++){
					c[i][j]=0;
					if (j<=x+y-2){
						c[i][j]+=c[i-1][j+1];
					}
					if (j>=2){
						c[i][j]+=c[i-1][j-1];
					}
				}
			}
			double possib=0.0f;
			for (int i=1;i<=MAX_I;i++){
				double curPossib=double(c[i][0]+c[i][x+y]);
				possib+=double(i)*curPossib/pow(2.0,double(i));
			}
			return possib;
        }

// 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 double &Expected, const double &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() { int Arg0 = 2; int Arg1 = 2; int Arg2 = 1; int Arg3 = 1; double Arg4 = 1.0; verify_case(0, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }
	void test_case_1() { int Arg0 = 2; int Arg1 = 2; int Arg2 = 0; int Arg3 = 1; double Arg4 = -1.0; verify_case(1, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }
	void test_case_2() { int Arg0 = 3; int Arg1 = 3; int Arg2 = 1; int Arg3 = 1; double Arg4 = 2.0; verify_case(2, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }
	void test_case_3() { int Arg0 = 4; int Arg1 = 6; int Arg2 = 1; int Arg3 = 3; double Arg4 = 27.0; verify_case(3, Arg4, expectedTime(Arg0, Arg1, Arg2, Arg3)); }

// END CUT HERE

};
// BEGIN CUT HERE
int main()
{
        TorusSailingEasy ___test;
        //___test.run_test(-1);
		___test.run_test(2);
        system("pause");
        return 0;
}
// END CUT HERE
<|endoftext|>


<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <CommandLine.hpp>

void processCommandLineOptions(isa::utils::ArgumentList &argumentList, Options &options, DeviceOptions &deviceOptions, DataOptions &dataOptions, HostMemoryDumpFiles & hostMemoryDumpFiles, KernelConfigurations &kernelConfigurations, GeneratorOptions &generatorOptions, AstroData::Observation &observation)
{
    try
    {
        options.debug = argumentList.getSwitch("-debug");
        options.print = argumentList.getSwitch("-print");
        options.dataDump = argumentList.getSwitch("-data_dump");
        if (options.dataDump)
        {
            hostMemoryDumpFiles.dumpFilesPrefix = argumentList.getSwitchArgument<std::string>("-dump_prefix");
        }
        options.splitBatchesDedispersion = argumentList.getSwitch("-splitbatches_dedispersion");
        options.subbandDedispersion = argumentList.getSwitch("-subband_dedispersion");
        options.compactResults = argumentList.getSwitch("-compact_results");
        options.threshold = argumentList.getSwitchArgument<float>("-threshold");
        deviceOptions.platformID = argumentList.getSwitchArgument<unsigned int>("-opencl_platform");
        deviceOptions.deviceID = argumentList.getSwitchArgument<unsigned int>("-opencl_device");
        deviceOptions.deviceName = argumentList.getSwitchArgument<std::string>("-device_name");
        deviceOptions.synchronized = argumentList.getSwitch("-sync");
        AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument<std::string>("-padding_file"));
        if (argumentList.getSwitch("-snr_standard"))
        {
            options.snrMode = SNRMode::Standard;
        }
        else if (argumentList.getSwitch("-snr_momad"))
        {
            options.snrMode = SNRMode::Momad;
        }
        else
        {
            // Default option right now is to use the standard mode.
            options.snrMode = SNRMode::Standard;
        }
        if ( inputBits >= 8 )
        {
            try
            {
                options.downsamplingFactor = argumentList.getSwitchArgument<unsigned int>("-downsampling");
            }
            catch ( isa::utils::SwitchNotFound &err )
            {
                // Default option is to not downsample input data.
                options.downsamplingFactor = 1;
            }
        }
        else
        {
            options.downsamplingFactor = 1;
        }
        dataOptions.dataLOFAR = argumentList.getSwitch("-lofar");
#ifndef HAVE_HDF5
        if (dataOptions.dataLOFAR)
        {
            std::cerr << "Not compiled with HDF5 support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_HDF5
        dataOptions.dataPSRDADA = argumentList.getSwitch("-dada");
#ifndef HAVE_PSRDADA
        if (dataOptions.dataPSRDADA)
        {
            std::cerr << "Not compiled with PSRDADA support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_PSRDADA
        dataOptions.dataSIGPROC = argumentList.getSwitch("-sigproc");
        if (!((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA) || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC)) || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR)) || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)))
        {
            std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl;
            throw std::exception();
        }
        dataOptions.channelsFile = argumentList.getSwitchArgument<std::string>("-zapped_channels");
        dataOptions.integrationFile = argumentList.getSwitchArgument<std::string>("-integration_steps");
        if (!options.subbandDedispersion)
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_file"));
        }
        else
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_stepone_file"));
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_steptwo_file"));
        }
        Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters, argumentList.getSwitchArgument<std::string>("-integration_file"));
        if (options.snrMode == SNRMode::Standard)
        {
            SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument<std::string>("-snr_file"));
        }
        else if (options.snrMode == SNRMode::Momad)
        {
            SNR::readTunedSNRConf(kernelConfigurations.maxParameters, argumentList.getSwitchArgument<std::string>("-max_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansAbsoluteDeviationParameters, argumentList.getSwitchArgument<std::string>("-momad_file"));
        }
        if (dataOptions.dataLOFAR)
        {
#ifdef HAVE_HDF5
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.headerFile = argumentList.getSwitchArgument<std::string>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            dataOptions.limit = argumentList.getSwitch("-limit");
            if (dataOptions.limit)
            {
                observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            }
#endif // HAVE_HDF5
        }
        else if (dataOptions.dataSIGPROC)
        {
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.streamingMode = argumentList.getSwitch("-stream");
            dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument<unsigned int>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
        }
        else if (dataOptions.dataPSRDADA)
        {
#ifdef HAVE_PSRDADA
            dataOptions.dadaKey = std::stoi("0x" + argumentList.getSwitchArgument<std::string>("-dada_key"), 0, 16);
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), 1, 1.0f, 1.0f);
            }
            else
            {
                observation.setFrequencyRange(1, 1, 1.0f, 1.0f);
            }
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
#endif // HAVE_PSRDADA
        }
        else
        {
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
            generatorOptions.random = argumentList.getSwitch("-random");
            generatorOptions.width = argumentList.getSwitchArgument<unsigned int>("-width");
            generatorOptions.DM = argumentList.getSwitchArgument<float>("-dm");
        }
        dataOptions.outputFile = argumentList.getSwitchArgument<std::string>("-output");
        if (options.subbandDedispersion)
        {
            observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-subbanding_dms"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_first"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_step"), true);
        }
        observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-dms"),
                               argumentList.getSwitchArgument<float>("-dm_first"),
                               argumentList.getSwitchArgument<float>("-dm_step"));
    }
    catch (isa::utils::EmptyCommandLine &err)
    {
        usage(argumentList.getName());
        throw;
    }
    catch (isa::utils::SwitchNotFound &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
}

void usage(const std::string &program)
{
    std::cerr << program << " [-debug] [-print] [-data_dump] -opencl_platform ... -opencl_device ... -device_name ... [-sync]";
    std::cerr << "  -padding_file ... -zapped_channels ... -integration_steps ... -integration_file ...";
    std::cerr << " [-splitbatches_dedispersion] [-subband_dedispersion] [-snr_standard | -snr_momad] [-downsampling ...]";
    std::cerr << " [-compact_results] -output ... -dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]";
#ifdef HAVE_HDF5
    std::cerr << " [-lofar]";
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    std::cerr << " [-dada]";
#endif // HAVE_PSRDADA
    std::cerr << std::endl;
    std::cerr << "\tData dump: -dump_prefix ..." << std::endl;
    std::cerr << "\tDedispersion: -dedispersion_file ..." << std::endl;
    std::cerr << "\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...";
    std::cerr << "-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...";
    std::cerr << "-subbanding_dm_step ..." << std::endl;
    std::cerr << "\tStandard SNR: -snr_file" << std::endl;
    std::cerr << "\tMOMAD SNR: -max_file ... -mom_stepone_file ... -mom_steptwo_file ... -momad_file ..." << std::endl;
#ifdef HAVE_HDF5
    std::cerr << "\tLOFAR: -lofar -header ... -data ... [-limit]" << std::endl;
    std::cerr << "\t\t -limit -batches ..." << std::endl;
#endif // HAVE_HDF5
    std::cerr << "\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...";
    std::cerr << "-channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
#ifdef HAVE_PSRDADA
    std::cerr << "\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ..." << std::endl;
#endif // HAVE_PSRDADA
    std::cerr << "\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...";
    std::cerr << "-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
}
<commit_msg>Read configuration file for downsampling kernel.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <CommandLine.hpp>

void processCommandLineOptions(isa::utils::ArgumentList &argumentList, Options &options, DeviceOptions &deviceOptions, DataOptions &dataOptions, HostMemoryDumpFiles & hostMemoryDumpFiles, KernelConfigurations &kernelConfigurations, GeneratorOptions &generatorOptions, AstroData::Observation &observation)
{
    try
    {
        options.debug = argumentList.getSwitch("-debug");
        options.print = argumentList.getSwitch("-print");
        options.dataDump = argumentList.getSwitch("-data_dump");
        if (options.dataDump)
        {
            hostMemoryDumpFiles.dumpFilesPrefix = argumentList.getSwitchArgument<std::string>("-dump_prefix");
        }
        options.splitBatchesDedispersion = argumentList.getSwitch("-splitbatches_dedispersion");
        options.subbandDedispersion = argumentList.getSwitch("-subband_dedispersion");
        options.compactResults = argumentList.getSwitch("-compact_results");
        options.threshold = argumentList.getSwitchArgument<float>("-threshold");
        deviceOptions.platformID = argumentList.getSwitchArgument<unsigned int>("-opencl_platform");
        deviceOptions.deviceID = argumentList.getSwitchArgument<unsigned int>("-opencl_device");
        deviceOptions.deviceName = argumentList.getSwitchArgument<std::string>("-device_name");
        deviceOptions.synchronized = argumentList.getSwitch("-sync");
        AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument<std::string>("-padding_file"));
        if (argumentList.getSwitch("-snr_standard"))
        {
            options.snrMode = SNRMode::Standard;
        }
        else if (argumentList.getSwitch("-snr_momad"))
        {
            options.snrMode = SNRMode::Momad;
        }
        else
        {
            // Default option right now is to use the standard mode.
            options.snrMode = SNRMode::Standard;
        }
        if ( inputBits >= 8 )
        {
            try
            {
                options.downsamplingFactor = argumentList.getSwitchArgument<unsigned int>("-downsampling");
                Integration::readTunedIntegrationConf(kernelConfigurations.downsamplingParameters, argumentList.getSwitchArgument<std::string>("-downsampling_configuration"));
            }
            catch ( isa::utils::SwitchNotFound &err )
            {
                // Default option is to not downsample input data.
                options.downsamplingFactor = 1;
            }
        }
        else
        {
            options.downsamplingFactor = 1;
        }
        dataOptions.dataLOFAR = argumentList.getSwitch("-lofar");
#ifndef HAVE_HDF5
        if (dataOptions.dataLOFAR)
        {
            std::cerr << "Not compiled with HDF5 support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_HDF5
        dataOptions.dataPSRDADA = argumentList.getSwitch("-dada");
#ifndef HAVE_PSRDADA
        if (dataOptions.dataPSRDADA)
        {
            std::cerr << "Not compiled with PSRDADA support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_PSRDADA
        dataOptions.dataSIGPROC = argumentList.getSwitch("-sigproc");
        if (!((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA) || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC)) || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR)) || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)))
        {
            std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl;
            throw std::exception();
        }
        dataOptions.channelsFile = argumentList.getSwitchArgument<std::string>("-zapped_channels");
        dataOptions.integrationFile = argumentList.getSwitchArgument<std::string>("-integration_steps");
        if (!options.subbandDedispersion)
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_file"));
        }
        else
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_stepone_file"));
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_steptwo_file"));
        }
        Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters, argumentList.getSwitchArgument<std::string>("-integration_file"));
        if (options.snrMode == SNRMode::Standard)
        {
            SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument<std::string>("-snr_file"));
        }
        else if (options.snrMode == SNRMode::Momad)
        {
            SNR::readTunedSNRConf(kernelConfigurations.maxParameters, argumentList.getSwitchArgument<std::string>("-max_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansAbsoluteDeviationParameters, argumentList.getSwitchArgument<std::string>("-momad_file"));
        }
        if (dataOptions.dataLOFAR)
        {
#ifdef HAVE_HDF5
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.headerFile = argumentList.getSwitchArgument<std::string>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            dataOptions.limit = argumentList.getSwitch("-limit");
            if (dataOptions.limit)
            {
                observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            }
#endif // HAVE_HDF5
        }
        else if (dataOptions.dataSIGPROC)
        {
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.streamingMode = argumentList.getSwitch("-stream");
            dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument<unsigned int>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
        }
        else if (dataOptions.dataPSRDADA)
        {
#ifdef HAVE_PSRDADA
            dataOptions.dadaKey = std::stoi("0x" + argumentList.getSwitchArgument<std::string>("-dada_key"), 0, 16);
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), 1, 1.0f, 1.0f);
            }
            else
            {
                observation.setFrequencyRange(1, 1, 1.0f, 1.0f);
            }
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
#endif // HAVE_PSRDADA
        }
        else
        {
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
            generatorOptions.random = argumentList.getSwitch("-random");
            generatorOptions.width = argumentList.getSwitchArgument<unsigned int>("-width");
            generatorOptions.DM = argumentList.getSwitchArgument<float>("-dm");
        }
        dataOptions.outputFile = argumentList.getSwitchArgument<std::string>("-output");
        if (options.subbandDedispersion)
        {
            observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-subbanding_dms"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_first"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_step"), true);
        }
        observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-dms"),
                               argumentList.getSwitchArgument<float>("-dm_first"),
                               argumentList.getSwitchArgument<float>("-dm_step"));
    }
    catch (isa::utils::EmptyCommandLine &err)
    {
        usage(argumentList.getName());
        throw;
    }
    catch (isa::utils::SwitchNotFound &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
}

void usage(const std::string &program)
{
    std::cerr << program << " [-debug] [-print] [-data_dump] -opencl_platform ... -opencl_device ... -device_name ... [-sync]";
    std::cerr << "  -padding_file ... -zapped_channels ... -integration_steps ... -integration_file ...";
    std::cerr << " [-splitbatches_dedispersion] [-subband_dedispersion] [-snr_standard | -snr_momad] [-downsampling ...]";
    std::cerr << " [-compact_results] -output ... -dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]";
#ifdef HAVE_HDF5
    std::cerr << " [-lofar]";
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    std::cerr << " [-dada]";
#endif // HAVE_PSRDADA
    std::cerr << std::endl;
    std::cerr << "\tData dump: -dump_prefix ..." << std::endl;
    std::cerr << "\tDownsampling: -downsampling_configuration ..." << std::endl;
    std::cerr << "\tDedispersion: -dedispersion_file ..." << std::endl;
    std::cerr << "\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...";
    std::cerr << "-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...";
    std::cerr << "-subbanding_dm_step ..." << std::endl;
    std::cerr << "\tStandard SNR: -snr_file" << std::endl;
    std::cerr << "\tMOMAD SNR: -max_file ... -mom_stepone_file ... -mom_steptwo_file ... -momad_file ..." << std::endl;
#ifdef HAVE_HDF5
    std::cerr << "\tLOFAR: -lofar -header ... -data ... [-limit]" << std::endl;
    std::cerr << "\t\t -limit -batches ..." << std::endl;
#endif // HAVE_HDF5
    std::cerr << "\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...";
    std::cerr << "-channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
#ifdef HAVE_PSRDADA
    std::cerr << "\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ..." << std::endl;
#endif // HAVE_PSRDADA
    std::cerr << "\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...";
    std::cerr << "-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
}
<|endoftext|>


<commit_before>/****************************************************************************
 Wyatt Technology Corporation
 6300 Hollister Avenue
 Goleta, CA 93117

 Copyright (c) 2002-2013. All rights reserved.
****************************************************************************/

#include "exception_capture.h"
using namespace WSTM;

#include <boost/test/unit_test.hpp>

namespace
{
	struct WTestExc
	{
		WTestExc (const std::string& msg):
			m_msg (msg)
		{}

		const std::string m_msg;

   private:
      WTestExc& operator= (const WTestExc&) { return *this; }
	};
}

BOOST_AUTO_TEST_SUITE (ExceptionCapture)

BOOST_AUTO_TEST_CASE (test_throw_empty)
{
	WExceptionCapture empty;
	BOOST_CHECK_NO_THROW(empty.ThrowCaptured());
}

BOOST_AUTO_TEST_CASE (test_capture_by_ctor)
{
	const std::string testMsg = "testing 1 2 3";
   WTestExc captured (testMsg);
   WExceptionCapture exc (captured);
	bool gotExc = false;
	std::string excMsg;
	try
	{
		exc.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);
}

BOOST_AUTO_TEST_CASE (test_captured_by_method)
{
	const std::string testMsg = "testing 1 2 3";
   WExceptionCapture exc;
   exc.Capture(WTestExc(testMsg));
	bool gotExc = false;
	std::string excMsg;
	try
	{
		exc.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);

	WExceptionCapture empty;
	BOOST_CHECK_NO_THROW(empty.ThrowCaptured());
}

BOOST_AUTO_TEST_CASE (test_copy)
{
	const std::string testMsg = "testing 1 2 3";
   WTestExc captured (testMsg);
   WExceptionCapture exc (captured);
	WExceptionCapture exc2(exc);
   bool gotExc = false;
	std::string excMsg;
	try
	{
		exc2.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);
}

BOOST_AUTO_TEST_CASE (test_operator_bool)
{
	WExceptionCapture w;
	BOOST_CHECK(!w);
	w.Capture(WTestExc("123"));
	BOOST_CHECK(w);
}

BOOST_AUTO_TEST_CASE (test_has_captured)
{
	WExceptionCapture w;
	BOOST_CHECK(!Atomically ([&](WAtomic& at){return w.HasCaptured (at);}));
	w.Capture(WTestExc("123"));
   BOOST_CHECK(Atomically ([&](WAtomic& at){return w.HasCaptured (at);}));
}

BOOST_AUTO_TEST_CASE (capture_another_capture)
{
   WExceptionCapture w1;
   WExceptionCapture w2;
   const std::string val = "612748";
   w1.Capture (WTestExc (val));
   w2.Capture (w1);
	bool gotExc = false;
	try
	{
		w2.ThrowCaptured();
	}
	catch(WTestExc& exc)
	{
		BOOST_CHECK_EQUAL(val, exc.m_msg);
		gotExc = true;
	}
	BOOST_CHECK(gotExc);
}

BOOST_AUTO_TEST_CASE (capture_another_capture_non_atomic)
{
   WExceptionCapture w1;
   WExceptionCapture w2;
   const std::string val = "612748";
   w1.Capture (WTestExc (val));
   w2.Capture (w1);
	bool gotExc = false;
	try
	{
		w2.ThrowCaptured();
	}
	catch(WTestExc& exc)
	{
		BOOST_CHECK_EQUAL(val, exc.m_msg);
		gotExc = true;
	}
	BOOST_CHECK(gotExc);
}

BOOST_AUTO_TEST_CASE (reset)
{
   WTestExc captured ("959106");
   WExceptionCapture w (captured);
   w.Reset ();
   BOOST_CHECK (!w);

   //make sure that resetting an empty capture is OK
   BOOST_CHECK_NO_THROW (w.Reset ());
}

BOOST_AUTO_TEST_CASE (CaptureInsideVar)
{
   //boost::thread_specific_ptr can have issues when crossing the
   //boudnary from main program code into DLL code. Storing a
   //WExceptionCapture inside of an object that is itself stored
   //in a WVar has caused this problem to surface in the past. If the
   //problem is occuring you will get an assertion (not boost test
   //assertion) when the transaction within which the exception is
   //captured commits.
   struct WTestObject
   {
      WExceptionCapture m_cap;
   };
   WVar<std::shared_ptr<WTestObject> > obj_v (
      std::shared_ptr<WTestObject>(new WTestObject));

   struct WTestError
   {
      WTestError (const int val) :
         m_val (val)
      {}
      int m_val;
   };
   static const int VALUE = 979222;
   Atomically ([&](WAtomic& at)
               {
                  std::shared_ptr<WTestObject> obj_p = obj_v.Get (at);
                  obj_p->m_cap.Capture (WTestError (VALUE), at);
               });
   bool gotExc = false;
   try
   {
      obj_v.GetReadOnly ()->m_cap.ThrowCaptured ();
   }
   catch (WTestError& exc)
   {
      gotExc = true;
      BOOST_CHECK_EQUAL (VALUE, exc.m_val);
   }
   BOOST_CHECK (gotExc);
}

BOOST_AUTO_TEST_SUITE_END (/*ExceptionCaptureAtomic*/)
<commit_msg>Added move tests for WExceptionCapture<commit_after>/****************************************************************************
 Wyatt Technology Corporation
 6300 Hollister Avenue
 Goleta, CA 93117

 Copyright (c) 2002-2013. All rights reserved.
****************************************************************************/

#include "exception_capture.h"
using namespace WSTM;

#include <boost/test/unit_test.hpp>

namespace
{
	struct WTestExc
	{
		WTestExc (const std::string& msg):
			m_msg (msg)
		{}

		const std::string m_msg;

   private:
      WTestExc& operator= (const WTestExc&) { return *this; }
	};
}

BOOST_AUTO_TEST_SUITE (ExceptionCapture)

BOOST_AUTO_TEST_CASE (test_throw_empty)
{
	WExceptionCapture empty;
	BOOST_CHECK_NO_THROW(empty.ThrowCaptured());
}

BOOST_AUTO_TEST_CASE (test_capture_by_ctor)
{
	const std::string testMsg = "testing 1 2 3";
   WTestExc captured (testMsg);
   WExceptionCapture exc (captured);
	bool gotExc = false;
	std::string excMsg;
	try
	{
		exc.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);
}

BOOST_AUTO_TEST_CASE (test_captured_by_method)
{
	const std::string testMsg = "testing 1 2 3";
   WExceptionCapture exc;
   exc.Capture(WTestExc(testMsg));
	bool gotExc = false;
	std::string excMsg;
	try
	{
		exc.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);

	WExceptionCapture empty;
	BOOST_CHECK_NO_THROW(empty.ThrowCaptured());
}

BOOST_AUTO_TEST_CASE (test_copy)
{
	const std::string testMsg = "testing 1 2 3";
   WTestExc captured (testMsg);
   WExceptionCapture exc (captured);
	WExceptionCapture exc2(exc);
   bool gotExc = false;
	std::string excMsg;
	try
	{
		exc2.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);
}

BOOST_AUTO_TEST_CASE (test_assign)
{
	const std::string testMsg = "testing 1 2 3";
   WTestExc captured (testMsg);
   WExceptionCapture exc (captured);
	WExceptionCapture exc2;
   exc2 = exc;
   bool gotExc = false;
	std::string excMsg;
	try
	{
		exc2.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);
}

BOOST_AUTO_TEST_CASE (test_move)
{
	const std::string testMsg = "testing 1 2 3";
   WTestExc captured (testMsg);
   WExceptionCapture exc (captured);
	WExceptionCapture exc2(std::move (exc));
   bool gotExc = false;
	std::string excMsg;
	try
	{
		exc2.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);
}

BOOST_AUTO_TEST_CASE (test_move_assign)
{
	const std::string testMsg = "testing 1 2 3";
   WTestExc captured (testMsg);
   WExceptionCapture exc (captured);
	WExceptionCapture exc2;
   exc2 = std::move (exc);
   bool gotExc = false;
	std::string excMsg;
	try
	{
		exc2.ThrowCaptured();
	}
	catch(WTestExc& testExc)
	{
		gotExc = true;
		excMsg = testExc.m_msg;
	}
	BOOST_CHECK(gotExc);
	BOOST_CHECK_EQUAL(testMsg, excMsg);
}

BOOST_AUTO_TEST_CASE (test_operator_bool)
{
	WExceptionCapture w;
	BOOST_CHECK(!w);
	w.Capture(WTestExc("123"));
	BOOST_CHECK(w);
}

BOOST_AUTO_TEST_CASE (test_has_captured)
{
	WExceptionCapture w;
	BOOST_CHECK(!Atomically ([&](WAtomic& at){return w.HasCaptured (at);}));
	w.Capture(WTestExc("123"));
   BOOST_CHECK(Atomically ([&](WAtomic& at){return w.HasCaptured (at);}));
}

BOOST_AUTO_TEST_CASE (capture_another_capture)
{
   WExceptionCapture w1;
   WExceptionCapture w2;
   const std::string val = "612748";
   w1.Capture (WTestExc (val));
   w2.Capture (w1);
	bool gotExc = false;
	try
	{
		w2.ThrowCaptured();
	}
	catch(WTestExc& exc)
	{
		BOOST_CHECK_EQUAL(val, exc.m_msg);
		gotExc = true;
	}
	BOOST_CHECK(gotExc);
}

BOOST_AUTO_TEST_CASE (capture_another_capture_non_atomic)
{
   WExceptionCapture w1;
   WExceptionCapture w2;
   const std::string val = "612748";
   w1.Capture (WTestExc (val));
   w2.Capture (w1);
	bool gotExc = false;
	try
	{
		w2.ThrowCaptured();
	}
	catch(WTestExc& exc)
	{
		BOOST_CHECK_EQUAL(val, exc.m_msg);
		gotExc = true;
	}
	BOOST_CHECK(gotExc);
}

BOOST_AUTO_TEST_CASE (reset)
{
   WTestExc captured ("959106");
   WExceptionCapture w (captured);
   w.Reset ();
   BOOST_CHECK (!w);

   //make sure that resetting an empty capture is OK
   BOOST_CHECK_NO_THROW (w.Reset ());
}

BOOST_AUTO_TEST_CASE (CaptureInsideVar)
{
   //boost::thread_specific_ptr can have issues when crossing the
   //boudnary from main program code into DLL code. Storing a
   //WExceptionCapture inside of an object that is itself stored
   //in a WVar has caused this problem to surface in the past. If the
   //problem is occuring you will get an assertion (not boost test
   //assertion) when the transaction within which the exception is
   //captured commits.
   struct WTestObject
   {
      WExceptionCapture m_cap;
   };
   WVar<std::shared_ptr<WTestObject> > obj_v (
      std::shared_ptr<WTestObject>(new WTestObject));

   struct WTestError
   {
      WTestError (const int val) :
         m_val (val)
      {}
      int m_val;
   };
   static const int VALUE = 979222;
   Atomically ([&](WAtomic& at)
               {
                  std::shared_ptr<WTestObject> obj_p = obj_v.Get (at);
                  obj_p->m_cap.Capture (WTestError (VALUE), at);
               });
   bool gotExc = false;
   try
   {
      obj_v.GetReadOnly ()->m_cap.ThrowCaptured ();
   }
   catch (WTestError& exc)
   {
      gotExc = true;
      BOOST_CHECK_EQUAL (VALUE, exc.m_val);
   }
   BOOST_CHECK (gotExc);
}

BOOST_AUTO_TEST_SUITE_END (/*ExceptionCaptureAtomic*/)
<|endoftext|>


<commit_before>/* Copyright (c) 2013, Devin Matthews
 * 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.
 *
 * 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 DEVIN MATTHEWS 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 "tda.hpp"
#include "util/lapack.h"

using namespace std;
using namespace aquarius;
using namespace aquarius::op;
using namespace aquarius::cc;
using namespace aquarius::input;
using namespace aquarius::tensor;
using namespace aquarius::task;
using namespace aquarius::symmetry;

template <typename U>
TDA<U>::TDA(const std::string& name, const Config& config)
: Task("tda", name)
{
    vector<Requirement> reqs;
    reqs.push_back(Requirement("molecule", "molecule"));
    reqs.push_back(Requirement("moints", "H"));
    addProduct(Product("tda.TDAevals", "TDAevals", reqs));
    addProduct(Product("tda.TDAevecs", "TDAevecs", reqs));
}

template <typename U>
void TDA<U>::run(TaskDAG& dag, const Arena& arena)
{
    TwoElectronOperator<U>& W = get<TwoElectronOperator<U> >("H");
    const Space& occ = W.occ;
    const Space& vrt = W.vrt;

    SpinorbitalTensor<U> Hguess("Hguess", W.getAIBJ());
    Hguess = 0;

    SpinorbitalTensor<U>& FAB = W.getAB();
    SpinorbitalTensor<U>& FIJ = W.getIJ();
    SpinorbitalTensor<U>& WAIBJ = W.getAIBJ();

    Hguess["aiaj"] -= FIJ["ij"];
    Hguess["aibi"] += FAB["ab"];
    Hguess["aibj"] -= WAIBJ["aibj"];

    const Molecule& molecule = get<Molecule>("molecule");
    const PointGroup& group = molecule.getGroup();
    int nirrep = group.getNumIrreps();

    auto& TDAevecs = put("TDAevecs", new vector<unique_vector<SpinorbitalTensor<U>>>(nirrep));
    auto& TDAevals = put("TDAevals", new vector<vector<U>>(nirrep));

    for (int R = 0;R < nirrep;R++)
    {
        const Representation& irr_R = group.getIrrep(R);

        int ntot = 0;
        for (int i = 0, count = 0;i < nirrep;i++)
        {
            const Representation& irr_i = group.getIrrep(i);
            for (int a = 0;a < nirrep;a++)
            {
                const Representation& irr_a = group.getIrrep(a);
                if (!(irr_a*irr_i*irr_R).isTotallySymmetric()) continue;
                ntot += vrt.nalpha[a]*occ.nalpha[i];
                ntot += vrt.nbeta [a]*occ.nbeta [i];
                assert(count++ < nirrep);
            }
            assert(i < nirrep-1 || count == nirrep);
        }

        vector<U> data(ntot*ntot);

        int offbj = 0;
        for (int spin_bj = 1;spin_bj >= 0;spin_bj--)
        {
            for (int j = 0;j < nirrep;j++)
            {
                const Representation& irr_j = group.getIrrep(j);
                for (int b = 0;b < nirrep;b++)
                {
                    const Representation& irr_b = group.getIrrep(b);
                    if (!(irr_b*irr_j*irr_R).isTotallySymmetric()) continue;

                    int nbj = (spin_bj == 1 ? vrt.nalpha[b] : vrt.nbeta[b])*
                              (spin_bj == 1 ? occ.nalpha[j] : occ.nbeta[j]);

                    int offai = 0;
                    for (int spin_ai = 1;spin_ai >= 0;spin_ai--)
                    {
                        for (int i = 0;i < nirrep;i++)
                        {
                            const Representation& irr_i = group.getIrrep(i);
                            for (int a = 0;a < nirrep;a++)
                            {
                                const Representation& irr_a = group.getIrrep(a);
                                if (!(irr_a*irr_i*irr_R).isTotallySymmetric()) continue;

                                int nai = (spin_ai == 1 ? vrt.nalpha[a] : vrt.nbeta[a])*
                                          (spin_ai == 1 ? occ.nalpha[i] : occ.nbeta[i]);

                                CTFTensor<U>& this_tensor = Hguess({spin_ai,spin_bj},{spin_bj,spin_ai})({a,j,b,i});
                                CTFTensor<U> trans_tensor("trans_tensor", arena, 4, {vrt.nalpha[a],occ.nalpha[i],vrt.nbeta[b],occ.nbeta[j]}, {NS,NS,NS,NS}, true);
                                trans_tensor["ajbi"] = this_tensor["aibj"];
                                vector<U> tempdata;
                                trans_tensor.getAllData(tempdata);
                                assert(tempdata.size() == nai*nbj);
                                for (int bj = 0, aibj = 0;bj < nbj;bj++)
                                {
                                    for (int ai = 0;ai < nai;ai++, aibj++)
                                    {
                                        data[offai+ai+(offbj+bj)*ntot] = tempdata[aibj];
                                    }
                                }

                                offai += nai;
                            }
                        }
                    }

                    offbj += nbj;
                }
            }
        }

        TDAevals[R].resize(ntot);
        heev('V','U',ntot,data.data(),ntot,TDAevals[R].data());

        cout << TDAevals[R] << endl;

        for (int root = 0;root < ntot;root++)
        {
            TDAevecs[R].emplace_back("R", arena, occ.group, irr_R, vec(vrt, occ), vec(1,0), vec(0,1));
            SpinorbitalTensor<U>& evec = TDAevecs[R][root];

            int offai = 0;
            for (int spin_ai = 1;spin_ai >= 0;spin_ai--)
            {
                for (int i = 0;i < nirrep;i++)
                {
                    const Representation& irr_i = group.getIrrep(i);
                    for (int a = 0;a < nirrep;a++)
                    {
                        const Representation& irr_a = group.getIrrep(a);
                        if (!(irr_a*irr_i*irr_R).isTotallySymmetric()) continue;

                        int nai = (spin_ai == 1 ? vrt.nalpha[a] : vrt.nbeta[a])*
                                  (spin_ai == 1 ? occ.nalpha[i] : occ.nbeta[i]);

                        vector<tkv_pair<U> > pairs(nai);
                        for (int ai = 0;ai < nai;ai++)
                        {
                            pairs[ai].k = ai;
                            pairs[ai].d = data[offai+ai+root*ntot];
                        }

                        evec({spin_ai,0},{0,spin_ai})({a,i}).writeRemoteData(pairs);

                        offai += nai;
                    }
                }
            }
        }

        cosort(TDAevals[R].begin() , TDAevals[R].end(),
               TDAevecs[R].pbegin(), TDAevecs[R].pend());
    }
}

INSTANTIATE_SPECIALIZATIONS(TDA);
REGISTER_TASK(TDA<double>, "tda");
<commit_msg>Working on MPI TDA<commit_after>/* Copyright (c) 2013, Devin Matthews
 * 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.
 *
 * 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 DEVIN MATTHEWS 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 "tda.hpp"
#include "util/lapack.h"

using namespace std;
using namespace aquarius;
using namespace aquarius::op;
using namespace aquarius::cc;
using namespace aquarius::input;
using namespace aquarius::tensor;
using namespace aquarius::task;
using namespace aquarius::symmetry;

template <typename U>
TDA<U>::TDA(const std::string& name, const Config& config)
: Task("tda", name)
{
    vector<Requirement> reqs;
    reqs.push_back(Requirement("molecule", "molecule"));
    reqs.push_back(Requirement("moints", "H"));
    addProduct(Product("tda.TDAevals", "TDAevals", reqs));
    addProduct(Product("tda.TDAevecs", "TDAevecs", reqs));
}

template <typename U>
void TDA<U>::run(TaskDAG& dag, const Arena& arena)
{
    TwoElectronOperator<U>& W = get<TwoElectronOperator<U> >("H");
    const Space& occ = W.occ;
    const Space& vrt = W.vrt;

    SpinorbitalTensor<U> Hguess("Hguess", W.getAIBJ());
    Hguess = 0;

    SpinorbitalTensor<U>& FAB = W.getAB();
    SpinorbitalTensor<U>& FIJ = W.getIJ();
    SpinorbitalTensor<U>& WAIBJ = W.getAIBJ();

    Hguess["aiaj"] -= FIJ["ij"];
    Hguess["aibi"] += FAB["ab"];
    Hguess["aibj"] -= WAIBJ["aibj"];

    const Molecule& molecule = get<Molecule>("molecule");
    const PointGroup& group = molecule.getGroup();
    int nirrep = group.getNumIrreps();

    auto& TDAevecs = put("TDAevecs", new vector<unique_vector<SpinorbitalTensor<U>>>(nirrep));
    auto& TDAevals = put("TDAevals", new vector<vector<U>>(nirrep));

    for (int R = 0;R < nirrep;R++)
    {
        const Representation& irr_R = group.getIrrep(R);

        int ntot = 0;
        for (int i = 0, count = 0;i < nirrep;i++)
        {
            const Representation& irr_i = group.getIrrep(i);
            for (int a = 0;a < nirrep;a++)
            {
                const Representation& irr_a = group.getIrrep(a);
                if (!(irr_a*irr_i*irr_R).isTotallySymmetric()) continue;
                ntot += vrt.nalpha[a]*occ.nalpha[i];
                ntot += vrt.nbeta [a]*occ.nbeta [i];
                assert(count++ < nirrep);
            }
            assert(i < nirrep-1 || count == nirrep);
        }

        vector<U> data(ntot*ntot);

        int offbj = 0;
        for (int spin_bj = 1;spin_bj >= 0;spin_bj--)
        {
            for (int j = 0;j < nirrep;j++)
            {
                const Representation& irr_j = group.getIrrep(j);
                for (int b = 0;b < nirrep;b++)
                {
                    const Representation& irr_b = group.getIrrep(b);
                    if (!(irr_b*irr_j*irr_R).isTotallySymmetric()) continue;

                    int nbj = (spin_bj == 1 ? vrt.nalpha[b] : vrt.nbeta[b])*
                              (spin_bj == 1 ? occ.nalpha[j] : occ.nbeta[j]);

                    int offai = 0;
                    for (int spin_ai = 1;spin_ai >= 0;spin_ai--)
                    {
                        for (int i = 0;i < nirrep;i++)
                        {
                            const Representation& irr_i = group.getIrrep(i);
                            for (int a = 0;a < nirrep;a++)
                            {
                                const Representation& irr_a = group.getIrrep(a);
                                if (!(irr_a*irr_i*irr_R).isTotallySymmetric()) continue;

                                int nai = (spin_ai == 1 ? vrt.nalpha[a] : vrt.nbeta[a])*
                                          (spin_ai == 1 ? occ.nalpha[i] : occ.nbeta[i]);

                                CTFTensor<U>& this_tensor = Hguess({spin_ai,spin_bj},{spin_bj,spin_ai})({a,j,b,i});
                                CTFTensor<U> trans_tensor("trans_tensor", arena, 4, {vrt.nalpha[a],occ.nalpha[i],vrt.nbeta[b],occ.nbeta[j]}, {NS,NS,NS,NS}, true);
                                trans_tensor["ajbi"] = this_tensor["aibj"];
                                vector<U> tempdata;
                                trans_tensor.getAllData(tempdata);
                                assert(tempdata.size() == nai*nbj);
                                for (int bj = 0, aibj = 0;bj < nbj;bj++)
                                {
                                    for (int ai = 0;ai < nai;ai++, aibj++)
                                    {
                                        data[offai+ai+(offbj+bj)*ntot] = tempdata[aibj];
                                    }
                                }

                                offai += nai;
                            }
                        }
                    }

                    offbj += nbj;
                }
            }
        }

        cout << "test1" << endl;

        TDAevals[R].resize(ntot);
        heev('V','U',ntot,data.data(),ntot,TDAevals[R].data());

        cout << "test2" << endl;

        cout << TDAevals[R] << endl;

        for (int root = 0;root < ntot;root++)
        {
            TDAevecs[R].emplace_back("R", arena, occ.group, irr_R, vec(vrt, occ), vec(1,0), vec(0,1));
            SpinorbitalTensor<U>& evec = TDAevecs[R][root];

            int offai = 0;
            for (int spin_ai = 1;spin_ai >= 0;spin_ai--)
            {
                for (int i = 0;i < nirrep;i++)
                {
                    const Representation& irr_i = group.getIrrep(i);
                    for (int a = 0;a < nirrep;a++)
                    {
                        const Representation& irr_a = group.getIrrep(a);
                        if (!(irr_a*irr_i*irr_R).isTotallySymmetric()) continue;

                        int nai = (spin_ai == 1 ? vrt.nalpha[a] : vrt.nbeta[a])*
                                  (spin_ai == 1 ? occ.nalpha[i] : occ.nbeta[i]);

                        vector<tkv_pair<U> > pairs(nai);
                        for (int ai = 0;ai < nai;ai++)
                        {
                            pairs[ai].k = ai;
                            pairs[ai].d = data[offai+ai+root*ntot];
                        }

                        evec({spin_ai,0},{0,spin_ai})({a,i}).writeRemoteData(pairs);

                        offai += nai;
                    }
                }
            }
        }

        cosort(TDAevals[R].begin() , TDAevals[R].end(),
               TDAevecs[R].pbegin(), TDAevecs[R].pend());
    }
}

INSTANTIATE_SPECIALIZATIONS(TDA);
REGISTER_TASK(TDA<double>, "tda");
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUI/NamedElement.cpp
    created:    30/10/2011
    author:     Martin Preisler

    purpose:    Implements the NamedElement class
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif

#include "CEGUI/NamedElement.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"

// Start of CEGUI namespace section
namespace CEGUI
{

const String NamedElement::EventNamespace("NamedElement");

const String NamedElement::EventNameChanged("NameChanged");

//----------------------------------------------------------------------------//
NamedElement::NamedElement(const String& name):
    d_name(name)
{
    addNamedElementProperties();
}

//----------------------------------------------------------------------------//
NamedElement::~NamedElement()
{}

//----------------------------------------------------------------------------//
void NamedElement::setName(const String& name)
{
    if (d_name == name)
        return;

    if (getParentElement())
    {
        NamedElement* parent = dynamic_cast<NamedElement*>(getParentElement());

        if (parent && parent->isChild(name))
        {
            CEGUI_THROW(AlreadyExistsException("NamedElement::setName - Failed to rename "
                "NamedElement at: " + getNamePath() + " as: " + name + ".  A Window "
                "with that name is already attached as a sibling."));
        }
    }

    // log this under informative level
    Logger::getSingleton().logEvent("Renamed element at: " + getNamePath() +
                                    " as: " + name,
                                    Informative);

    d_name = name;

    NamedElementEventArgs args(this);
    onNameChanged(args);
}

//----------------------------------------------------------------------------//
String NamedElement::getNamePath() const
{
    String path("");

    Element* parent_element = getParentElement();
    NamedElement* parent_named_element = dynamic_cast<NamedElement*>(parent_element);

    if (parent_element)
    {
        if (parent_named_element)
            path = parent_named_element->getNamePath() + '/';
        else
            path = "<not a named element>/";
    }

    path += getName();

    return path;
}

//----------------------------------------------------------------------------//
bool NamedElement::isChild(const String& name_path) const
{
    return getChildByNamePath_impl(name_path) != 0;
}

//----------------------------------------------------------------------------//
bool NamedElement::isAncestor(const String& name) const
{
    Element const* current = this;

    while (true)
    {
        const Element* parent = current->getParentElement();

        if (!parent)
            return false;

        const NamedElement* named_parent = dynamic_cast<const NamedElement*>(parent);

        if (named_parent && named_parent->getName() == name)
            return true;

        current = parent;
    }
}

//----------------------------------------------------------------------------//
NamedElement* NamedElement::getChildElement(const String& name_path) const
{
    NamedElement* e = getChildByNamePath_impl(name_path);

    if (e)
        return e;

    CEGUI_THROW(UnknownObjectException("NamedElement::getChildElement - The Element object "
        "referenced by '" + name_path + "' is not attached to Element at '"
        + getNamePath() + "'."));
}

//----------------------------------------------------------------------------//
void NamedElement::removeChild(const String& name_path)
{
    NamedElement* e = getChildByNamePath_impl(name_path);

    if (e)
        removeChild(e);
    else
        CEGUI_THROW(UnknownObjectException("NamedElement::removeChild - The Element object "
            "referenced by '" + name_path + "' is not attached to Element at '"
            + getNamePath() + "'."));
}

//----------------------------------------------------------------------------//
void NamedElement::addChild_impl(Element* element)
{
    NamedElement* named_element = dynamic_cast<NamedElement*>(element);

    if (named_element)
    {
        const NamedElement* const existing = getChildByNamePath_impl(named_element->getName());

        if (existing && named_element != existing)
            CEGUI_THROW(AlreadyExistsException("NamedElement::addChild_impl - Failed to add "
                "Element named: " + named_element->getName() + " to element at: " +
                getNamePath() + " since an Element with that name is already "
                "attached."));
    }

    Element::addChild_impl(element);
}

//----------------------------------------------------------------------------//
NamedElement* NamedElement::getChildByNamePath_impl(const String& name_path) const
{
    const size_t sep = name_path.find_first_of('/');
    const String base_child(name_path.substr(0, sep));

    const size_t child_count = d_children.size();

    for (size_t i = 0; i < child_count; ++i)
    {
        Element* child = getChildElementAtIdx(i);
        NamedElement* named_child = dynamic_cast<NamedElement*>(child);

        if (!named_child)
            continue;

        if (named_child->getName() == base_child)
        {
            if (sep != String::npos && sep < name_path.length() - 1)
                return named_child->getChildByNamePath_impl(name_path.substr(sep + 1));
            else
                return named_child;
        }
    }

    return 0;
}

//----------------------------------------------------------------------------//
void NamedElement::addNamedElementProperties()
{
    const String propertyOrigin("NamedElement");

    CEGUI_DEFINE_PROPERTY(NamedElement, String,
        "Name", "Property to get/set the name of the Element. Make sure it's unique in its parent if any.",
        &NamedElement::setName, &NamedElement::getName, ""
    );

    CEGUI_DEFINE_PROPERTY_NO_XML(NamedElement, String,
        "NamePath", "Property to get the absolute name path of this Element.",
        0, &NamedElement::getNamePath, ""
    );
}

//----------------------------------------------------------------------------//
void NamedElement::onNameChanged(NamedElementEventArgs& e)
{
    fireEvent(EventNameChanged, e, EventNamespace);
}

} // End of  CEGUI namespace section
<commit_msg>Make the NamedElement's Name property also NO_XML, we store its value elsewhere<commit_after>/***********************************************************************
    filename:   CEGUI/NamedElement.cpp
    created:    30/10/2011
    author:     Martin Preisler

    purpose:    Implements the NamedElement class
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif

#include "CEGUI/NamedElement.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"

// Start of CEGUI namespace section
namespace CEGUI
{

const String NamedElement::EventNamespace("NamedElement");

const String NamedElement::EventNameChanged("NameChanged");

//----------------------------------------------------------------------------//
NamedElement::NamedElement(const String& name):
    d_name(name)
{
    addNamedElementProperties();
}

//----------------------------------------------------------------------------//
NamedElement::~NamedElement()
{}

//----------------------------------------------------------------------------//
void NamedElement::setName(const String& name)
{
    if (d_name == name)
        return;

    if (getParentElement())
    {
        NamedElement* parent = dynamic_cast<NamedElement*>(getParentElement());

        if (parent && parent->isChild(name))
        {
            CEGUI_THROW(AlreadyExistsException("NamedElement::setName - Failed to rename "
                "NamedElement at: " + getNamePath() + " as: " + name + ".  A Window "
                "with that name is already attached as a sibling."));
        }
    }

    // log this under informative level
    Logger::getSingleton().logEvent("Renamed element at: " + getNamePath() +
                                    " as: " + name,
                                    Informative);

    d_name = name;

    NamedElementEventArgs args(this);
    onNameChanged(args);
}

//----------------------------------------------------------------------------//
String NamedElement::getNamePath() const
{
    String path("");

    Element* parent_element = getParentElement();
    NamedElement* parent_named_element = dynamic_cast<NamedElement*>(parent_element);

    if (parent_element)
    {
        if (parent_named_element)
            path = parent_named_element->getNamePath() + '/';
        else
            path = "<not a named element>/";
    }

    path += getName();

    return path;
}

//----------------------------------------------------------------------------//
bool NamedElement::isChild(const String& name_path) const
{
    return getChildByNamePath_impl(name_path) != 0;
}

//----------------------------------------------------------------------------//
bool NamedElement::isAncestor(const String& name) const
{
    Element const* current = this;

    while (true)
    {
        const Element* parent = current->getParentElement();

        if (!parent)
            return false;

        const NamedElement* named_parent = dynamic_cast<const NamedElement*>(parent);

        if (named_parent && named_parent->getName() == name)
            return true;

        current = parent;
    }
}

//----------------------------------------------------------------------------//
NamedElement* NamedElement::getChildElement(const String& name_path) const
{
    NamedElement* e = getChildByNamePath_impl(name_path);

    if (e)
        return e;

    CEGUI_THROW(UnknownObjectException("NamedElement::getChildElement - The Element object "
        "referenced by '" + name_path + "' is not attached to Element at '"
        + getNamePath() + "'."));
}

//----------------------------------------------------------------------------//
void NamedElement::removeChild(const String& name_path)
{
    NamedElement* e = getChildByNamePath_impl(name_path);

    if (e)
        removeChild(e);
    else
        CEGUI_THROW(UnknownObjectException("NamedElement::removeChild - The Element object "
            "referenced by '" + name_path + "' is not attached to Element at '"
            + getNamePath() + "'."));
}

//----------------------------------------------------------------------------//
void NamedElement::addChild_impl(Element* element)
{
    NamedElement* named_element = dynamic_cast<NamedElement*>(element);

    if (named_element)
    {
        const NamedElement* const existing = getChildByNamePath_impl(named_element->getName());

        if (existing && named_element != existing)
            CEGUI_THROW(AlreadyExistsException("NamedElement::addChild_impl - Failed to add "
                "Element named: " + named_element->getName() + " to element at: " +
                getNamePath() + " since an Element with that name is already "
                "attached."));
    }

    Element::addChild_impl(element);
}

//----------------------------------------------------------------------------//
NamedElement* NamedElement::getChildByNamePath_impl(const String& name_path) const
{
    const size_t sep = name_path.find_first_of('/');
    const String base_child(name_path.substr(0, sep));

    const size_t child_count = d_children.size();

    for (size_t i = 0; i < child_count; ++i)
    {
        Element* child = getChildElementAtIdx(i);
        NamedElement* named_child = dynamic_cast<NamedElement*>(child);

        if (!named_child)
            continue;

        if (named_child->getName() == base_child)
        {
            if (sep != String::npos && sep < name_path.length() - 1)
                return named_child->getChildByNamePath_impl(name_path.substr(sep + 1));
            else
                return named_child;
        }
    }

    return 0;
}

//----------------------------------------------------------------------------//
void NamedElement::addNamedElementProperties()
{
    const String propertyOrigin("NamedElement");

    // "Name" is already stored in <Window> element
    CEGUI_DEFINE_PROPERTY_NO_XML(NamedElement, String,
        "Name", "Property to get/set the name of the Element. Make sure it's unique in its parent if any.",
        &NamedElement::setName, &NamedElement::getName, ""
    );

    CEGUI_DEFINE_PROPERTY_NO_XML(NamedElement, String,
        "NamePath", "Property to get the absolute name path of this Element.",
        0, &NamedElement::getNamePath, ""
    );
}

//----------------------------------------------------------------------------//
void NamedElement::onNameChanged(NamedElementEventArgs& e)
{
    fireEvent(EventNameChanged, e, EventNamespace);
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2018 by contributors. 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.
//------------------------------------------------------------------------------

/*
This file is the implementation of logging facilities.
*/

#include "src/base/logging.h"

#include <stdlib.h>
#include <time.h>

//------------------------------------------------------------------------------
// Logger
//------------------------------------------------------------------------------

std::ofstream Logger::info_log_file_;
std::ofstream Logger::warn_log_file_;
std::ofstream Logger::erro_log_file_;

void InitializeLogger(const std::string& info_log_filename,
                      const std::string& warn_log_filename,
                      const std::string& erro_log_filename) {
  Logger::info_log_file_.open(info_log_filename.c_str());
  Logger::warn_log_file_.open(warn_log_filename.c_str());
  Logger::erro_log_file_.open(erro_log_filename.c_str());
  // check if the file has been open
  bool bo = false;
  if (Logger::info_log_file_.is_open() == 0) {
    std::cout << "Cannot create file: " << info_log_filename << ". "
              << "Please check that wether you need to "
              << "create a new directory. \n";
    bo = true;
  }
  if (Logger::warn_log_file_.is_open() == 0) {
    std::cout << "Cannot create file: " << warn_log_filename << ". "
              << "Please check that wether you need to "
              << "create a new directory. \n";
    bo = true;
  }
  if (Logger::erro_log_file_.is_open() == 0) {
    std::cout << "Cannot create file:  " << erro_log_filename << ". "
              << "Please check that wether you need to "
              << "create a new directory. \n";
    bo = true;
  }
  if (bo) { exit(0); }
}

/*static*/
std::ostream& Logger::GetStream(LogSeverity severity) {
  if (severity == INFO) {
    return info_log_file_.is_open() ? info_log_file_ : std::cout;
  } else if (severity == WARNING) {
    return warn_log_file_.is_open() ? warn_log_file_ : std::cerr;
  } else if (severity == ERR || severity == FATAL) {
    return erro_log_file_.is_open() ? erro_log_file_ : std::cerr;
  }
  return std::cout; // Print message
}

/*static*/
std::ostream& Logger::Start(LogSeverity severity,
                            const std::string& file,
                            int line,
                            const std::string& function) {
  time_t tm;
  time(&tm);
  char time_string[128];
  ctime_r(&tm, time_string);
  return GetStream(severity) << time_string
                             << " " << file << ":" << line
                             << " (" << function << ") " << std::flush;
}

Logger::~Logger() {
  GetStream(severity_) << "\n" << std::flush;
  if (severity_ == FATAL) {
    info_log_file_.close();
    warn_log_file_.close();
    erro_log_file_.close();
    abort();
  }
}
<commit_msg>Fit ctime for windows<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2018 by contributors. 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.
//------------------------------------------------------------------------------

/*
This file is the implementation of logging facilities.
*/

#include "src/base/logging.h"

#include <stdlib.h>
#include <time.h>

//------------------------------------------------------------------------------
// Logger
//------------------------------------------------------------------------------

std::ofstream Logger::info_log_file_;
std::ofstream Logger::warn_log_file_;
std::ofstream Logger::erro_log_file_;

void InitializeLogger(const std::string& info_log_filename,
                      const std::string& warn_log_filename,
                      const std::string& erro_log_filename) {
  Logger::info_log_file_.open(info_log_filename.c_str());
  Logger::warn_log_file_.open(warn_log_filename.c_str());
  Logger::erro_log_file_.open(erro_log_filename.c_str());
  // check if the file has been open
  bool bo = false;
  if (Logger::info_log_file_.is_open() == 0) {
    std::cout << "Cannot create file: " << info_log_filename << ". "
              << "Please check that wether you need to "
              << "create a new directory. \n";
    bo = true;
  }
  if (Logger::warn_log_file_.is_open() == 0) {
    std::cout << "Cannot create file: " << warn_log_filename << ". "
              << "Please check that wether you need to "
              << "create a new directory. \n";
    bo = true;
  }
  if (Logger::erro_log_file_.is_open() == 0) {
    std::cout << "Cannot create file:  " << erro_log_filename << ". "
              << "Please check that wether you need to "
              << "create a new directory. \n";
    bo = true;
  }
  if (bo) { exit(0); }
}

/*static*/
std::ostream& Logger::GetStream(LogSeverity severity) {
  if (severity == INFO) {
    return info_log_file_.is_open() ? info_log_file_ : std::cout;
  } else if (severity == WARNING) {
    return warn_log_file_.is_open() ? warn_log_file_ : std::cerr;
  } else if (severity == ERR || severity == FATAL) {
    return erro_log_file_.is_open() ? erro_log_file_ : std::cerr;
  }
  return std::cout; // Print message
}

/*static*/
std::ostream& Logger::Start(LogSeverity severity,
                            const std::string& file,
                            int line,
                            const std::string& function) {
  time_t tm;
  time(&tm);
  char time_string[128];
#ifndef _MSC_VER
  ctime_r(&tm, time_string);
#else
  ctime_s(time_string, sizeof(time_string), &tm);
#endif
  return GetStream(severity) << time_string
                             << " " << file << ":" << line
                             << " (" << function << ") " << std::flush;
}

Logger::~Logger() {
  GetStream(severity_) << "\n" << std::flush;
  if (severity_ == FATAL) {
    info_log_file_.close();
    warn_log_file_.close();
    erro_log_file_.close();
    abort();
  }
}
<|endoftext|>


<commit_before><commit_msg>Clarify treatment of double slashes in rtl::Uri::convertRelToAbs<commit_after><|endoftext|>


<commit_before>//
// Created by Miguel Rentes on 30/01/2017.
//

#include "STL.h"

void printKMax(int arr[], int n, int k) {
    deque<int> mydeque;
    for (int i = 0; i < n; i++) {
        // clean the deque if the new array element is greater
        // than the ones on the deque
        for (; !mydeque.empty() && arr[i] > mydeque.back();)
            mydeque.pop_back();
        mydeque.push_back(arr[i]);
        if (i >= k && mydeque.front() == arr[i-k])
            mydeque.pop_front();
        // at the end of the k-elements
        if (i >= k-1)
            printf (i < n-1 ? "%d " : "%d\n", mydeque.front());
    }
}

int main(void) {
    int t;
    cin >> t;
    while (t > 0) {
        int n, k;
        cin >> n >> k;
        int i;
        int arr[n];
        for (i = 0; i < n; i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return EXIT_SUCCESS;
}<commit_msg>Refactors solution for the Deque-STL challenge.<commit_after>//
// Created by Miguel Rentes on 30/01/2017.
//

#include "STL.h"

void printKMax(int arr[], int n, int k) {
    deque<int> mydeque;
    for (int i = 0; i < n; i++) {
        // clean the deque at the back if the array element is greater
        // than the ones currently on the deque
        for (; !mydeque.empty() && arr[i] > mydeque.back();)
            mydeque.pop_back();
        mydeque.push_back(arr[i]);
        if (i >= k && mydeque.front() == arr[i-k])
            mydeque.pop_front();
        // at the end of the k-elements
        if (i >= k-1)
            printf (i < n-1 ? "%d " : "%d\n", mydeque.front());
    }
}

int main(void) {
    int t;
    cin >> t;
    while (t > 0) {
        int n, k;
        cin >> n >> k;
        int i;
        int arr[n];
        for (i = 0; i < n; i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QString>
#include <QtCore/QTime>
#include <QtCore/QElapsedTimer>
#include <QtTest/QtTest>

static const int minResolution = 50; // the minimum resolution for the tests

class tst_QElapsedTimer : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void statics();
    void validity();
    void basics();
    void elapsed();
};

void tst_QElapsedTimer::statics()
{
    qDebug() << "Clock type is" << QElapsedTimer::clockType();
    qDebug() << "Said clock is" << (QElapsedTimer::isMonotonic() ? "monotonic" : "not monotonic");
    QElapsedTimer t;
    t.start();
    qDebug() << "Current time is" << t.msecsSinceReference();
}

void tst_QElapsedTimer::validity()
{
    QElapsedTimer t;

    t.invalidate();
    QVERIFY(!t.isValid());

    t.start();
    QVERIFY(t.isValid());

    t.invalidate();
    QVERIFY(!t.isValid());
}

void tst_QElapsedTimer::basics()
{
    QElapsedTimer t1;
    t1.start();

    QVERIFY(t1.msecsSinceReference() != 0);

    QCOMPARE(t1, t1);
    QVERIFY(!(t1 != t1));
    QVERIFY(!(t1 < t1));
    QCOMPARE(t1.msecsTo(t1), qint64(0));
    QCOMPARE(t1.secsTo(t1), qint64(0));
//    QCOMPARE(t1 + 0, t1);
//    QCOMPARE(t1 - 0, t1);

#if 0
    QElapsedTimer t2 = t1;
    t2 += 1000;   // so we can use secsTo

    QVERIFY(t1 != t2);
    QVERIFY(!(t1 == t2));
    QVERIFY(t1 < t2);
    QVERIFY(!(t2 < t1));
    QCOMPARE(t1.msecsTo(t2), qint64(1000));
    QCOMPARE(t1.secsTo(t2), qint64(1));
//    QCOMPARE(t2 - t1, qint64(1000));
//    QCOMPARE(t1 - t2, qint64(-1000));
#endif

    quint64 value1 = t1.msecsSinceReference();
    qint64 elapsed = t1.restart();
    QVERIFY(elapsed < minResolution);

    quint64 value2 = t1.msecsSinceReference();
    // in theory, elapsed == value2 - value1

    // However, since QElapsedTimer keeps internally the full resolution,
    // we have here a rounding error due to integer division
    QVERIFY(qAbs(elapsed - qint64(value2 - value1)) < 1);
}

void tst_QElapsedTimer::elapsed()
{
    QElapsedTimer t1;
    t1.start();

    QTest::qSleep(4*minResolution);
    QElapsedTimer t2;
    t2.start();

    QVERIFY(t1 != t2);
    QVERIFY(!(t1 == t2));
    QVERIFY(t1 < t2);
    QVERIFY(t1.msecsTo(t2) > 0);
    // don't check: t1.secsTo(t2)
//    QVERIFY(t1 - t2 < 0);

    QVERIFY(t1.elapsed() > 0);
    QVERIFY(t1.hasExpired(minResolution));
    QVERIFY(!t1.hasExpired(8*minResolution));
    QVERIFY(!t2.hasExpired(minResolution));

    QVERIFY(!t1.hasExpired(-1));
    QVERIFY(!t2.hasExpired(-1));

    qint64 elapsed = t1.restart();
    QVERIFY(elapsed > 3*minResolution);
    QVERIFY(elapsed < 5*minResolution);
    qint64 diff = t2.msecsTo(t1);
    QVERIFY(diff < minResolution);
}

QTEST_MAIN(tst_QElapsedTimer);

#include "tst_qelapsedtimer.moc"
<commit_msg>Autotest: fix the fix for the rounding error.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QString>
#include <QtCore/QTime>
#include <QtCore/QElapsedTimer>
#include <QtTest/QtTest>

static const int minResolution = 50; // the minimum resolution for the tests

class tst_QElapsedTimer : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void statics();
    void validity();
    void basics();
    void elapsed();
};

void tst_QElapsedTimer::statics()
{
    qDebug() << "Clock type is" << QElapsedTimer::clockType();
    qDebug() << "Said clock is" << (QElapsedTimer::isMonotonic() ? "monotonic" : "not monotonic");
    QElapsedTimer t;
    t.start();
    qDebug() << "Current time is" << t.msecsSinceReference();
}

void tst_QElapsedTimer::validity()
{
    QElapsedTimer t;

    t.invalidate();
    QVERIFY(!t.isValid());

    t.start();
    QVERIFY(t.isValid());

    t.invalidate();
    QVERIFY(!t.isValid());
}

void tst_QElapsedTimer::basics()
{
    QElapsedTimer t1;
    t1.start();

    QVERIFY(t1.msecsSinceReference() != 0);

    QCOMPARE(t1, t1);
    QVERIFY(!(t1 != t1));
    QVERIFY(!(t1 < t1));
    QCOMPARE(t1.msecsTo(t1), qint64(0));
    QCOMPARE(t1.secsTo(t1), qint64(0));
//    QCOMPARE(t1 + 0, t1);
//    QCOMPARE(t1 - 0, t1);

#if 0
    QElapsedTimer t2 = t1;
    t2 += 1000;   // so we can use secsTo

    QVERIFY(t1 != t2);
    QVERIFY(!(t1 == t2));
    QVERIFY(t1 < t2);
    QVERIFY(!(t2 < t1));
    QCOMPARE(t1.msecsTo(t2), qint64(1000));
    QCOMPARE(t1.secsTo(t2), qint64(1));
//    QCOMPARE(t2 - t1, qint64(1000));
//    QCOMPARE(t1 - t2, qint64(-1000));
#endif

    quint64 value1 = t1.msecsSinceReference();
    qint64 elapsed = t1.restart();
    QVERIFY(elapsed < minResolution);

    quint64 value2 = t1.msecsSinceReference();
    // in theory, elapsed == value2 - value1

    // However, since QElapsedTimer keeps internally the full resolution,
    // we have here a rounding error due to integer division
    QVERIFY(qAbs(elapsed - qint64(value2 - value1)) <= 1);
}

void tst_QElapsedTimer::elapsed()
{
    QElapsedTimer t1;
    t1.start();

    QTest::qSleep(4*minResolution);
    QElapsedTimer t2;
    t2.start();

    QVERIFY(t1 != t2);
    QVERIFY(!(t1 == t2));
    QVERIFY(t1 < t2);
    QVERIFY(t1.msecsTo(t2) > 0);
    // don't check: t1.secsTo(t2)
//    QVERIFY(t1 - t2 < 0);

    QVERIFY(t1.elapsed() > 0);
    QVERIFY(t1.hasExpired(minResolution));
    QVERIFY(!t1.hasExpired(8*minResolution));
    QVERIFY(!t2.hasExpired(minResolution));

    QVERIFY(!t1.hasExpired(-1));
    QVERIFY(!t2.hasExpired(-1));

    qint64 elapsed = t1.restart();
    QVERIFY(elapsed > 3*minResolution);
    QVERIFY(elapsed < 5*minResolution);
    qint64 diff = t2.msecsTo(t1);
    QVERIFY(diff < minResolution);
}

QTEST_MAIN(tst_QElapsedTimer);

#include "tst_qelapsedtimer.moc"
<|endoftext|>


<commit_before>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
#include <cstring>

#include "utils.h"
#include "logging.h"
#include "DeviceIndex.h"

#include "Error.h"

#if HAVE_ARAVIS
#include "aravis_utils.h"
#endif

#if HAVE_USB
#include "v4l2_utils.h"
#endif

using namespace tcam;

DeviceIndex::DeviceIndex ()
    : continue_thread(false),
      wait_period(2),
      device_list(std::vector<DeviceInfo>()),
      callbacks(std::vector<dev_callback>())
{
    continue_thread = true;
    std::thread (&DeviceIndex::run, this).detach();
}

DeviceIndex::~DeviceIndex ()
{
    continue_thread = false;
}

void DeviceIndex::register_device_lost (dev_callback c)
{
    tcam_log(TCAM_LOG_DEBUG, "Registered device lost callback");
    mtx.lock();
    callbacks.push_back(c);
    mtx.unlock();
}

void DeviceIndex::updateDeviceList ()
{
    std::vector<DeviceInfo> tmp_dev_list = std::vector<DeviceInfo>();
    tmp_dev_list.reserve(10);

#if HAVE_ARAVIS
    auto aravis_dev_list = get_aravis_device_list();
    if (!aravis_dev_list.empty())
        tmp_dev_list.insert(tmp_dev_list.end(), aravis_dev_list.begin(), aravis_dev_list.end());
#endif

#if HAVE_USB
    auto v4l2_dev_list = get_v4l2_device_list();
    if (!v4l2_dev_list.empty())
        tmp_dev_list.insert(tmp_dev_list.end(), v4l2_dev_list.begin(), v4l2_dev_list.end());
#endif

    for (const auto& d : device_list)
    {
        auto f = [&d] (const DeviceInfo& info)
            {
                if (d.getSerial().compare( info.getSerial()) == 0)
                    return true;
                return false;
            };

        auto found = std::find_if(tmp_dev_list.begin(), tmp_dev_list.end(), f);

        if (found == tmp_dev_list.end())
        {
            fire_device_lost(d);
        }
    }

    mtx.lock();

    device_list.clear();

    device_list.insert(device_list.end(), tmp_dev_list.begin(), tmp_dev_list.end());

    mtx.unlock();
}

void DeviceIndex::run ()
{
    while (continue_thread)
    {
        updateDeviceList();
        std::this_thread::sleep_for(std::chrono::seconds(wait_period));
    }
}

void DeviceIndex::fire_device_lost (const DeviceInfo& d)
{
    mtx.lock();
    for (auto& c : callbacks)
    {
        c(d);
    }
    mtx.unlock();
}

bool DeviceIndex::fillDeviceInfo (DeviceInfo& info)
{
    if (!info.getSerial().empty())
    {
        for (const auto& d : device_list)
        {
            if (info.getSerial() == d.getSerial())
            {
                info = d;
                return true;
            }
        }
        return false;
    }

    if (!info.getIdentifier().empty())
    {
        for (const auto& d : device_list)
        {
            if (info.getIdentifier() == d.getIdentifier())
            {
                info = d;
                return true;
            }
        }
    }
    return false;
}

std::vector<DeviceInfo> DeviceIndex::getDeviceList () const
{
    return device_list;
}

std::shared_ptr<DeviceIndex> tcam::getDeviceIndex ()
{
    return std::make_shared<DeviceIndex>();
}
<commit_msg>Made work thread joinable<commit_after>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
#include <cstring>

#include "utils.h"
#include "logging.h"
#include "DeviceIndex.h"

#include "Error.h"

#if HAVE_ARAVIS
#include "aravis_utils.h"
#endif

#if HAVE_USB
#include "v4l2_utils.h"
#endif

using namespace tcam;

DeviceIndex::DeviceIndex ()
    : continue_thread(false),
      wait_period(2),
      device_list(std::vector<DeviceInfo>()),
      callbacks(std::vector<dev_callback>())
{
    continue_thread = true;
    work_thread = std::thread (&DeviceIndex::run, this);
}

DeviceIndex::~DeviceIndex ()
{
    continue_thread = false;
    if (work_thread.joinable())
    {
        work_thread.join();
    }
}

void DeviceIndex::register_device_lost (dev_callback c)
{
    tcam_log(TCAM_LOG_DEBUG, "Registered device lost callback");
    mtx.lock();
    callbacks.push_back(c);
    mtx.unlock();
}

void DeviceIndex::updateDeviceList ()
{
    std::vector<DeviceInfo> tmp_dev_list = std::vector<DeviceInfo>();
    tmp_dev_list.reserve(10);

#if HAVE_ARAVIS
    auto aravis_dev_list = get_aravis_device_list();
    if (!aravis_dev_list.empty())
        tmp_dev_list.insert(tmp_dev_list.end(), aravis_dev_list.begin(), aravis_dev_list.end());
#endif

#if HAVE_USB
    auto v4l2_dev_list = get_v4l2_device_list();
    if (!v4l2_dev_list.empty())
        tmp_dev_list.insert(tmp_dev_list.end(), v4l2_dev_list.begin(), v4l2_dev_list.end());
#endif

    for (const auto& d : device_list)
    {
        auto f = [&d] (const DeviceInfo& info)
            {
                if (d.getSerial().compare( info.getSerial()) == 0)
                    return true;
                return false;
            };

        auto found = std::find_if(tmp_dev_list.begin(), tmp_dev_list.end(), f);

        if (found == tmp_dev_list.end())
        {
            fire_device_lost(d);
        }
    }

    mtx.lock();

    device_list.clear();

    device_list.insert(device_list.end(), tmp_dev_list.begin(), tmp_dev_list.end());

    mtx.unlock();
}

void DeviceIndex::run ()
{
    while (continue_thread)
    {
        updateDeviceList();
        std::this_thread::sleep_for(std::chrono::seconds(wait_period));
    }
}

void DeviceIndex::fire_device_lost (const DeviceInfo& d)
{
    mtx.lock();
    for (auto& c : callbacks)
    {
        c(d);
    }
    mtx.unlock();
}

bool DeviceIndex::fillDeviceInfo (DeviceInfo& info)
{
    if (!info.getSerial().empty())
    {
        for (const auto& d : device_list)
        {
            if (info.getSerial() == d.getSerial())
            {
                info = d;
                return true;
            }
        }
        return false;
    }

    if (!info.getIdentifier().empty())
    {
        for (const auto& d : device_list)
        {
            if (info.getIdentifier() == d.getIdentifier())
            {
                info = d;
                return true;
            }
        }
    }
    return false;
}

std::vector<DeviceInfo> DeviceIndex::getDeviceList () const
{
    return device_list;
}

std::shared_ptr<DeviceIndex> tcam::getDeviceIndex ()
{
    return std::make_shared<DeviceIndex>();
}
<|endoftext|>