Example #1
0
void CCaliData::ModifyResTime(vector<double> &afterResTime) {
	if (afterResTime.empty()) return;

	const int itemNum = m_CaliItems.size();

	CCaliData RefPeak;
	GetRefPeakData(RefPeak);

	if (RefPeak.GetItemSize()!=afterResTime.size())
	{
		::AfxMessageBox(_T("参考峰个数不匹配"));
		ASSERT(TRUE);
		return;
	}

	for (int i=0; i<itemNum; ++i) {
		if(m_CaliItems[i].szIsReference != _T("否")) //该字段应该有是,否,空 3个属性
			continue;
		int iStart=0, iEnd=INT_MAX; //该未知峰对应的参数峰的区间

		GetRefPeakInterval(i, iStart, iEnd);

		CString Ref_i_1_before;
		CString Ref_i_before;
		CString NofRef = m_CaliItems[i].szReserveTime;

		double  dRef_i_1_after;
		double  dRef_i_after;
		double  dRef_i_1_before;
		double  dRef_i_before;
		double  dNofRef_before = _tstof(NofRef);

		if (iStart==0){
			dRef_i_1_before=0.0f;
			dRef_i_1_after=0.0f;
		}
		else {
			RefPeak.GetReserveTime(iStart-1, Ref_i_1_before);
			dRef_i_1_before=_tstof(Ref_i_1_before);
			dRef_i_1_after = afterResTime[iStart-1];
		}
		

		if (iEnd==INT_MAX){
			dRef_i_before=0.0f;
			dRef_i_after =0.0f;
		}
		else{
			RefPeak.GetReserveTime(iEnd-1, Ref_i_before);
			dRef_i_before=_tstof(Ref_i_before);
			dRef_i_after =afterResTime[iEnd-1];
		}
		

		if (dRef_i_before-dRef_i_1_before==0.0f)
		{
			::AfxMessageBox(_T("参考峰前后数据一致,请进行数据检查"));
			continue;
		}
		double  dNofRef_after = (dNofRef_before-dRef_i_1_before)*(dRef_i_after-dRef_i_1_after)/(dRef_i_before-dRef_i_1_before)+dRef_i_1_after;
		CString szModifyResTime;
		szModifyResTime.Format(RESERVETIME_DATA_FORMAT, dNofRef_after);
		m_CaliItems[i].szReserveTime=szModifyResTime;
	}
}
Example #2
0
shared_ptr<Card> Beginner::playCard( const vector< shared_ptr<Card> >& cardsCanPlay ) const
{
  assert( !cardsCanPlay.empty() );
  // play random
  return cardsCanPlay[ rand() % cardsCanPlay.size() ]; 
}
Example #3
0
int CExactMethodForDGP::FindSourceVertex(int indexOfVert, vector<CPoint3D>& resultingPath) const
{
	resultingPath.clear();

	if (m_InfoAtVertices.find(indexOfVert) == m_InfoAtVertices.end())
	{
		assert(model.GetNumOfComponents() != 1 || model.Neigh(indexOfVert).empty());
		return -1;
	}
	vector<int> vertexNodes;
	int index = indexOfVert;
	vertexNodes.push_back(index);
	while (true)
	{
		map<int, InfoAtVertex>::const_iterator it = m_InfoAtVertices.find(index);
		if (it == m_InfoAtVertices.end())
			break;
		if (it->second.disUptodate <= FLT_EPSILON)
			break;
		int indexOfParent = it->second.indexOfParent;
		if (it->second.fParentIsPseudoSource)
		{
			index = indexOfParent;
		}
		else
		{
			index = it->second.indexOfRootVertOfParent;
		}
		vertexNodes.push_back(index);
	};
	int indexOfSourceVert = index;

	for (int i = 0; i < (int)vertexNodes.size() - 1; ++i)
	{
		int lastVert = vertexNodes[i];
		//if (lastVert != indexOfVert)
		if (resultingPath.empty() || (resultingPath.back() - model.Vert(lastVert)).Len() > 1e-5)
			resultingPath.push_back(model.Vert(lastVert));
		if (m_InfoAtVertices.find(lastVert)->second.fParentIsPseudoSource)
		{
			continue;
		}
		int parentEdgeIndex = m_InfoAtVertices.find(lastVert)->second.indexOfParent;
		int edgeIndex = model.Edge(parentEdgeIndex).indexOfReverseEdge;
		double leftLen =       model.Edge(model.Edge(parentEdgeIndex).indexOfRightEdge).length;
		double rightLen = model.Edge(model.Edge(parentEdgeIndex).indexOfLeftEdge).length;
		double xBack = model.Edge(parentEdgeIndex).length - model.Edge(parentEdgeIndex).xOfPlanarCoordOfOppositeVert;
		double yBack = -model.Edge(parentEdgeIndex).yOfPlanarCoordOfOppositeVert;
		double disToAngle = model.DistanceToIncidentAngle(edgeIndex, xBack, yBack);

		double proportion = 1 - m_InfoAtVertices.find(lastVert)->second.entryProp;
		while (1) 
		{
			if (resultingPath.empty() || (resultingPath.back() - IntersectionWithPath(edgeIndex, proportion).GetPosition(model)).Len() > 1e-5)
				resultingPath.push_back(IntersectionWithPath(edgeIndex, proportion).GetPosition(model));
			if (model.Edge(edgeIndex).indexOfOppositeVert == vertexNodes[i + 1])
				break;
			double oldProprotion = proportion;
			proportion = model.ProportionOnLeftEdgeByImage(edgeIndex,xBack, yBack, oldProprotion);
			if (model.Edge(edgeIndex).indexOfLeftEdge == -1 || model.Edge(edgeIndex).indexOfRightEdge == -1)
			{
				break;
			}

			if (proportion >= -LENGTH_EPSILON_CONTROL && proportion <= 1)
			{
                proportion = max(proportion, 0.0);
				edgeIndex = model.Edge(edgeIndex).indexOfLeftEdge;
				rightLen = disToAngle;				
			}
			else
			{
				proportion = model.ProportionOnRightEdgeByImage(edgeIndex, xBack, yBack, oldProprotion);
                proportion = max(proportion, 0.0);
                proportion = min(proportion, 1.0);
				edgeIndex = model.Edge(edgeIndex).indexOfRightEdge;
				leftLen = disToAngle;				
			}
			model.GetPointByRotatingAround(edgeIndex, leftLen, rightLen, xBack, yBack);			
			disToAngle = model.DistanceToIncidentAngle(edgeIndex, xBack, yBack);
		};
	}
	if (resultingPath.empty() || (resultingPath.back() - model.Vert(indexOfSourceVert)).Len() > 1e-5)
	resultingPath.push_back(model.Vert(indexOfSourceVert));
	return indexOfSourceVert;
}
Example #4
0
// Standard OSG code for initializing osgViewer::Viewer with explicit
// creation of own graphics context. This is also a good time to test
// for valid frame buffer configurations; we have a valid graphics
// context, but multithreading hasn't started, etc.
GraphicsContext* setupGC(osgViewer::Viewer& viewer, ArgumentParser& arguments)
{
    int x = -1, y = -1, width = -1, height = -1;
    while (arguments.read("--window",x,y,width,height)) {}

    GraphicsContext::WindowingSystemInterface* wsi =
        GraphicsContext::getWindowingSystemInterface();
    if (!wsi)
    {
        OSG_NOTIFY(NOTICE)<<"View::setUpViewOnSingleScreen() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
        return 0;
    }

    DisplaySettings* ds = viewer.getDisplaySettings() ? viewer.getDisplaySettings() : DisplaySettings::instance().get();
    GraphicsContext::ScreenIdentifier si;
    si.readDISPLAY();
    si.setUndefinedScreenDetailsToDefaultScreen();

    bool decoration = true;
    if (x < 0)
    {
        unsigned int w, h;
        wsi->getScreenResolution(si, w, h);
        OSG_NOTICE<<"Screen resolution is "<<w<<", "<<h<<std::endl;
        OSG_NOTICE<<"ScreenIdentifier "<<si.displayNum<<", "<<si.screenNum<<std::endl;
        x = 0;
        y = 0;
        width = w;
        height = h;
        decoration = false;
    }

    OSG_NOTICE<<"x = "<<x<<", y = "<<y<<", width = "<<width<<", height = "<<height<<std::endl;

    ref_ptr<GraphicsContext::Traits> traits = new GraphicsContext::Traits(ds);
    traits->hostName = si.hostName;
    traits->displayNum = si.displayNum;
    traits->screenNum = si.screenNum;
    traits->x = x;
    traits->y = y;
    traits->width = width;
    traits->height = height;
    traits->windowDecoration = decoration;
    traits->doubleBuffer = true;
    traits->sharedContext = 0;

    ref_ptr<GraphicsContext> gc = GraphicsContext::createGraphicsContext(traits.get());
    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
    if (gw)
    {
        OSG_NOTIFY(INFO)<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
        gw->getEventQueue()->getCurrentEventState()
            ->setWindowRectangle(0, 0, width, height);
    }
    else
    {
        OSG_NOTIFY(NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
    }
    double fovy, aspectRatio, zNear, zFar;
    viewer.getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio,
                                                         zNear, zFar);
    double newAspectRatio = double(traits->width) / double(traits->height);
    double aspectRatioChange = newAspectRatio / aspectRatio;
    if (aspectRatioChange != 1.0)
    {
        viewer.getCamera()->getProjectionMatrix()
            *= Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
    }
    // Context has to be current to test for extensions
    gc->realize();
    if (!gc->makeCurrent())
    {
        OSG_NOTIFY(NOTICE) << "Unable to create GraphicsWindow"<<std::endl;
        gc->releaseContext();
        gc->close(true);
        return 0;
    }

    unsigned int contextID = gc->getState()->getContextID();
    osg::GLExtensions* ext = gc->getState()->get<GLExtensions>();
    if (!ext->isFrameBufferObjectSupported)
    {
        OSG_NOTIFY(NOTICE) << "Frame buffer objects are not supported\n";
        gc->releaseContext();
        gc->close(true);
        return 0;
    }

    if (isGLExtensionSupported(contextID, "GL_ARB_depth_buffer_float"))
        depthTextureEnum = GL_DEPTH_COMPONENT32F;
    else if (isGLExtensionSupported(contextID, "GL_NV_depth_buffer_float"))
        depthTextureEnum = GL_DEPTH_COMPONENT32F_NV;

    BufferConfigList colorConfigs;
    BufferConfigList depthConfigs;
    vector<int> coverageConfigs;
    getPossibleConfigs(gc.get(), colorConfigs, depthConfigs, coverageConfigs);
    int coverageSampleConfigs = (coverageConfigs.size() - 4) / 2;
    cout << "color configs\nname\tbits\n";
    for (BufferConfigList::const_iterator colorItr = colorConfigs.begin(),
             colorEnd = colorConfigs.end();
         colorItr != colorEnd;
         ++colorItr)
    {
        for (BufferConfigList::const_iterator depthItr = depthConfigs.begin(),
             depthEnd = depthConfigs.end();
             depthItr != depthEnd;
             ++depthItr)
        {
            string root = colorItr->name + " " + depthItr->name;
            FboConfig config(root, colorItr->format, depthItr->format,
                             colorItr->bits, depthItr->bits);
            FboData data;
            if (createFBO(gc.get(), config, data))
                validConfigs.push_back(config);
            destroyFBO(gc.get(), data);
            if (coverageConfigs.size() > 0)
            {
                //CSAA provides a list of all supported AA modes for
                //quick enumeration
                for (int kk = 0; kk < coverageSampleConfigs; kk++)
                {
                    stringstream msText;
                    msText << root;
                    config.depthSamples = coverageConfigs[kk*2+1];
                    config.coverageSamples = coverageConfigs[kk*2];

                    if ( config.coverageSamples == config.depthSamples )
                    {
                        // Normal antialiasing
                        msText << " - " << config.depthSamples << " MSAA";
                    }
                    else
                    {
                        // coverage antialiasing
                        msText << " - " << config.coverageSamples << "/"
                               << config.depthSamples << " CSAA";
                    }
                    config.name = msText.str();

                    if (createFBO(gc.get(), config, data)) {
                        validConfigs.push_back( config);
                    }
                    destroyFBO(gc.get(), data);
                }
            }
        }
    }
    if (validConfigs.empty())
    {
        cout << "no valid frame buffer configurations!\n";
        return 0;
    }
    cout << "valid frame buffer configurations:\n";
    for (vector<FboConfig>::iterator itr = validConfigs.begin(),
             end = validConfigs.end();
         itr != end;
         ++itr)
        cout << itr->name << "\n";
    gc->releaseContext();

    return gc.release();
}
Example #5
0
int main( const int argc, const char **argv )
{
    // Generated using: http://patorjk.com/software/taag/#p=display&f=Soft&t=BEETL%20BWT
    cout << ",-----.  ,------.,------.,--------.,--.       ,-----.  ,--.   ,--.,--------. " << endl;
    cout << "|  |) /_ |  .---'|  .---''--.  .--'|  |       |  |) /_ |  |   |  |'--.  .--' " << endl;
    cout << "|  .-.  \\|  `--, |  `--,    |  |   |  |       |  .-.  \\|  |.'.|  |   |  |    " << endl;
    cout << "|  '--' /|  `---.|  `---.   |  |   |  '--.    |  '--' /|   ,'.   |   |  |    " << endl;
    cout << "`------' `------'`------'   `--'   `-----'    `------' '--'   '--'   `--'    " << endl;
    cout << "Version " << PACKAGE_VERSION << endl;
    cout << endl;

    cout << "Command called:" << endl << "   ";
    for ( int i = 0; i < argc; ++i )
    {
        cout << " " << argv[i];
    }
    cout << "\n" << endl;


    if ( !params.parseArgv( argc, argv ) || params["help"] == 1 || !params.chechRequiredParameters() )
    {
        printUsage();
        exit( 1 );
    }

    // Auto-detection of missing arguments
    if ( !params["input format"].isSet() )
    {
        const string &filename = params["input filename"];
        string fileFormat = detectFileFormat( filename );
        if ( fileFormat.empty() )
        {
            cerr << "Error: file format not recognised for " << filename << endl;
            exit( -1 );
        }
        params["input format"] = fileFormat;
    }
    checkFileFormat( params["input filename"], params["input format"] );

    if ( params["memory limit MB"] <= 0 )
    {
        params["memory limit MB"] = detectMemoryLimitInMB();
    }

    // Special case of SAP ordering
    /*
        if ( params["SAP ordering"] == 1 )
        {
            if ( !params["algorithm"].isSet() || strcasecmp( params["algorithm"].userValue.c_str(), "ext" ) != 0 )
            {
                clog << "Warning: Forcing algorithm=ext for --sap-ordering" << endl;
                params["algorithm"] = "ext";
            }
            if ( !params["intermediate format"].isSet() || strcasecmp( params["intermediate format"].userValue.c_str(), "ascii" ) != 0 )
            {
                clog << "Warning: Forcing intermediate-format=ascii for --sap-ordering" << endl;
                params["intermediate format"] = "ascii";
            }
        }
    */

    // Special case of LCP generation
    if ( params["generate LCP"] == 1 )
    {
        if ( !params["algorithm"].isSet() || strcasecmp( params["algorithm"].userValue.c_str(), "bcr" ) != 0 )
        {
            clog << "Warning: Forcing algorithm=bcr for --generate-lcp" << endl;
            params["algorithm"] = "bcr";
        }
        if ( !params["intermediate format"].isSet() || strcasecmp( params["intermediate format"].userValue.c_str(), "ascii" ) != 0 )
        {
            clog << "Warning: Forcing intermediate-format=ascii for --generate-lcp" << endl;
            params["intermediate format"] = "ascii";
        }
    }

    // Switches only available with the BCR algorithm
    if ( params["reverse"] == 1
         || params["pause between cycles"] == 1
         || params["process qualities"] == "permute"
         || params["add reverse complement"] == 1
       )
    {
        if ( !params["algorithm"].isSet() || strcasecmp( params["algorithm"].userValue.c_str(), "bcr" ) != 0 )
        {
            clog << "Warning: Forcing algorithm=bcr for --reverse/--pause-between-cycle/--qualities=permute/--add-rev-comp" << endl;
            params["algorithm"] = "bcr";
        }
    }

    // Use default parameter values where needed
    params.commitDefaultValues();

    datasetMetadata.init( params["input filename"], params["input format"] );
    // TODO: hardwareConstraints.init( params["HardwareConstraints"] );

    // Resource estimation
    calculateResourceRequirements();

    // Launch the fastest estimated configuration of Beetl
    if ( allEstimates.empty() )
    {
        cerr << "Error: Beetl doesn't seem to be able to run under these constraints. Try to relax some of them." << endl;
        exit( 2 );
    }
    launchBeetlBwt( allEstimates[0] );

    return 0;
}
Example #6
0
void OpenCL::Init()
{
#ifdef CPU_MINING_ONLY
	if (globalconfs.coin.threads_per_gpu != 0)
	{
		cout << "This binary was built with CPU mining support only." << endl;
	}
#else
	if (globalconfs.coin.threads_per_gpu == 0)
	{
		cout << "No GPUs selected." << endl;
		return;
	}

	cl_int status = 0;

	cl_uint numPlatforms;
	cl_platform_id platform = NULL;

	status = clGetPlatformIDs(0, NULL, &numPlatforms);
	if(status != CL_SUCCESS)
		throw string("Error getting OpenCL platforms");

	if(numPlatforms > 0)
	{   
		cl_platform_id* platforms = new cl_platform_id[numPlatforms];

		status = clGetPlatformIDs(numPlatforms, platforms, NULL);
		if(status != CL_SUCCESS)
			throw string("Error getting OpenCL platform IDs");

		unsigned int i;
		cout << "List of platforms:" << endl;
		for(i=0; i < numPlatforms; ++i)
		{   
			char pbuff[100];

			status = clGetPlatformInfo( platforms[i], CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL);
			if(status != CL_SUCCESS)
			{   
				delete [] platforms;
				throw string("Error getting OpenCL platform info");
			}

			cout << "\t" << i << "\t" << pbuff << endl;
			if (globalconfs.platform == i)
			{
				platform = platforms[i];
			}
		}   
		delete [] platforms;
	}
	else
	{
		throw string("No OpenCL platforms found");
	}

	if (platform == NULL)
	{
		throw string("Chosen platform number does not exist");
	}
	cout << "Using platform number " << globalconfs.platform << endl;

	cl_uint numDevices;
	cl_uint devicetype = CL_DEVICE_TYPE_ALL;
	status = clGetDeviceIDs(platform, devicetype, 0, NULL, &numDevices);
	if(status != CL_SUCCESS)
	{
		throw string("Error getting OpenCL device IDs");
	}

	if (numDevices == 0)
		throw string("No OpenCL devices found");

	vector<cl_device_id> devices;
	cl_device_id* devicearray = new cl_device_id[numDevices];

	status = clGetDeviceIDs(platform, devicetype, numDevices, devicearray, NULL);
	if(status != CL_SUCCESS)
		throw string("Error getting OpenCL device ID list");

	for(uint i=0; i<numDevices; ++i)
		devices.push_back(devicearray[i]);

	cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };

	clState.context = clCreateContextFromType(cps, devicetype, NULL, NULL, &status);
	if(status != CL_SUCCESS) 
		throw string("Error creating OpenCL context");

	cout << endl;
	if (globalconfs.devices.empty())
	{
		cout << "Using all devices" << endl;
	}
	else
	{
		cout << "Using device" << (globalconfs.devices.size()==1?"":"s") << " ";
		for(uint i=0; i<globalconfs.devices.size(); ++i)
		{
			cout << globalconfs.devices[i];
			if (i+1 < globalconfs.devices.size())
			{
				cout << ", ";
			}
		}
		cout << endl;
	}
	for(uint device_id=0; device_id<numDevices; ++device_id) 
	{
		string source;
		string sourcefilename;
		{
			sourcefilename = config.GetCombiValue<string>("device", device_id, "kernel");
			if (sourcefilename == "")
				sourcefilename = config.GetValue<string>("kernel");
			sourcefilename = globalconfs.coin.protocol + "-" + sourcefilename;
			FILE* filu = fopen(sourcefilename.c_str(), "rb");
			if (filu == NULL)
			{
				throw string("Couldn't find kernel file ") + sourcefilename;
			}
			fseek(filu, 0, SEEK_END);
			uint size = ftell(filu);
			fseek(filu, 0, SEEK_SET);
			size_t readsize = 0;
			for(uint i=0; i<size; ++i)
			{
				char c;
				readsize += fread(&c, 1, 1, filu);
				source.push_back(c);
			}
			if (readsize != size)
			{
				cout << "Read error while reading kernel source " << sourcefilename << endl;
			}
		}

		vector<size_t> sourcesizes;
		sourcesizes.push_back(source.length());

		const char* see = source.c_str();

		char pbuff[512];
		status = clGetDeviceInfo(devices[device_id], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
		cout << "\t" << device_id << "\t" << pbuff;
		if(status != CL_SUCCESS)
			throw string("Error getting OpenCL device info");

		if (!globalconfs.devices.empty() && std::find(globalconfs.devices.begin(), globalconfs.devices.end(), device_id) == globalconfs.devices.end())
		{
			cout << " (disabled)" << endl;
			continue;
		}

		cout << endl;

		uchar* filebinary = NULL;
		size_t filebinarysize=0;
		string filebinaryname;
		for(char*p = &pbuff[0]; *p != 0; ++p)
		{
			//get rid of unwanted characters in filenames
			if (*p >= 33 && *p < 127 && *p != '\\' && *p != ':' && *p != '/' && *p != '*' && *p != '<' && *p != '>' && *p != '"' && *p != '?' && *p != '|')
				filebinaryname += *p;
		}
		filebinaryname += string("-") + ToString(globalconfs.coin.local_worksize);
		if (globalconfs.coin.protocol == "litecoin")
		{
			filebinaryname += string("-") + ToString(globalconfs.coin.config.GetValue<string>("gpu_thread_concurrency"));
			filebinaryname += string("-") + ToString(globalconfs.coin.config.GetValue<string>("lookup_gap"));
			filebinaryname += string("-") + ToString(globalconfs.coin.config.GetValue<string>("localworksize"));
		}
		if (globalconfs.coin.protocol == "bitcoin")
		{
			filebinaryname += string("-") + ToString(globalconfs.coin.config.GetValue<string>("vectors"));
		}

		filebinaryname = sourcefilename.substr(0,sourcefilename.size()-3) + REAPER_VERSION + "." + filebinaryname + ".bin";
		if (globalconfs.save_binaries)
		{
			FILE* filu = fopen(filebinaryname.c_str(), "rb");
			if (filu != NULL)
			{
				fseek(filu, 0, SEEK_END);
				uint size = ftell(filu);
				fseek(filu, 0, SEEK_SET);
				if (size > 0)
				{
					filebinary = new uchar[size];
					filebinarysize = size;
					size_t readsize = fread(filebinary, size, 1, filu);
					if (readsize != 1)
					{
						cout << "Read error while reading binary" << endl;
					}
				}
				fclose(filu);
			}
		}

		_clState GPUstate;
		status = clGetDeviceInfo(devices[device_id], CL_DEVICE_EXTENSIONS, sizeof(pbuff), pbuff, NULL);
		vector<string> extensions = Explode(string(pbuff),' ');

		if (filebinary == NULL)
		{
			cout << "Compiling kernel... this could take up to 2 minutes." << endl;
			GPUstate.program = clCreateProgramWithSource(clState.context, 1, (const char **)&see, &sourcesizes[0], &status);
			if(status != CL_SUCCESS) 
				throw string("Error creating OpenCL program from source");

			string compile_options;
			compile_options += " -D WORKSIZE=" + ToString(globalconfs.coin.local_worksize);
			compile_options += " -D KERNELLOCALWORKSIZE=" + ToString(globalconfs.coin.kernellocal_worksize);


			bool amd_gpu = (std::find(extensions.begin(),extensions.end(), "cl_amd_media_ops") != extensions.end());

			if (amd_gpu)
				compile_options += " -D AMD_GPU";
			
			compile_options += " -D SHAREMASK=";
			compile_options += globalconfs.coin.config.GetValue<string>("gpu_sharemask");
			uint vectors = GetVectorSize();
			if (vectors == 2)
				compile_options += " -D VECTORS";
			else if (vectors == 4)
				compile_options += " -D VECTORS4";
			if (globalconfs.coin.protocol == "litecoin")
			{
				compile_options += string(" -D LOOKUP_GAP=") + globalconfs.coin.config.GetValue<string>("lookup_gap");
				compile_options += string(" -D CONCURRENT_THREADS=") + globalconfs.coin.config.GetValue<string>("gpu_thread_concurrency");
			}
			status = clBuildProgram(GPUstate.program, 1, &devices[device_id], compile_options.c_str(), NULL, NULL);
			if(status != CL_SUCCESS) 
			{   
				size_t logSize;
				status = clGetProgramBuildInfo(GPUstate.program, devices[device_id], CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);

				char* log = new char[logSize];
				status = clGetProgramBuildInfo(GPUstate.program, devices[device_id], CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
				cout << log << endl;
				delete [] log;
				throw string("Error building OpenCL program");
			}

			uint device_amount;
			clGetProgramInfo(GPUstate.program, CL_PROGRAM_NUM_DEVICES, sizeof(uint), &device_amount, NULL);

			size_t* binarysizes = new size_t[device_amount];
			uchar** binaries = new uchar*[device_amount];
			for(uint curr_binary = 0; curr_binary<device_amount; ++curr_binary)
			{
				clGetProgramInfo(GPUstate.program, CL_PROGRAM_BINARY_SIZES, device_amount*sizeof(size_t), binarysizes, NULL);
				binaries[curr_binary] = new uchar[binarysizes[curr_binary]];
			}
			clGetProgramInfo(GPUstate.program, CL_PROGRAM_BINARIES, sizeof(uchar*)*device_amount, binaries, NULL);
			for(uint binary_id = 0; binary_id < device_amount; ++binary_id)
			{
				if (binarysizes[binary_id] == 0)
					continue;

				cout << "Binary size: " << binarysizes[binary_id] << " bytes" << endl;
				if (globalconfs.save_binaries)
				{
					FILE* filu = fopen(filebinaryname.c_str(), "wb");
					fwrite(binaries[binary_id], binarysizes[binary_id], 1, filu);
					fclose(filu);
				}
			}

			cout << "Program built from source." << endl;
			delete [] binarysizes;
			for(uint binary_id=0; binary_id < device_amount; ++binary_id)
				delete [] binaries[binary_id];
			delete [] binaries;
		}
		else
		{
			cl_int binary_status, errorcode_ret;
			GPUstate.program = clCreateProgramWithBinary(clState.context, 1, &devices[device_id], &filebinarysize, const_cast<const uchar**>(&filebinary), &binary_status, &errorcode_ret);
			if (binary_status != CL_SUCCESS)
				cout << "Binary status error code: " << binary_status << endl;
			if (errorcode_ret != CL_SUCCESS)
				cout << "Binary loading error code: " << errorcode_ret << endl;
			status = clBuildProgram(GPUstate.program, 1, &devices[device_id], NULL, NULL, NULL);
			if (status != CL_SUCCESS)
				cout << "Error while building from binary: " << status << endl;

			cout << "Program built from saved binary." << endl;
		}
		delete [] filebinary;

		GPUstate.kernel = clCreateKernel(GPUstate.program, "search", &status);
		if(status != CL_SUCCESS)
		{
			cout << "Kernel build not successful: " << status << endl;
			throw string("Error creating OpenCL kernel");
		}
		for(uint thread_id = 0; thread_id < globalconfs.coin.threads_per_gpu; ++thread_id)
		{
			cl_mem padbuffer8;
			if (globalconfs.coin.protocol == "litecoin")
			{
			uint lookup_gap = globalconfs.coin.config.GetValue<uint>("lookup_gap");
			uint thread_concurrency = globalconfs.coin.config.GetValue<uint>("gpu_thread_concurrency");
			uint itemsperthread = (1024/lookup_gap+(1024%lookup_gap>0));
			uint bufsize = 128*itemsperthread*thread_concurrency;
			cout << "LTC buffer size: " << bufsize/1024.0/1024.0 << "MB." << endl;
			padbuffer8 = clCreateBuffer(clState.context, CL_MEM_READ_WRITE, bufsize, NULL, &status);
				if (status != 0)
				{
					cout << "Buffer too big: allocation failed. Either raise 'lookup_gap' or lower 'gpu_thread_concurrency'." << endl;
					throw string("");
				}
			}
			GPUstate.commandQueue = clCreateCommandQueue(clState.context, devices[device_id], 0, &status);
/*			if (thread_id == 0 && (globalconfs.coin.protocol == "solidcoin" || globalconfs.coin.protocol == "solidcoin3"))
			{
				clEnqueueWriteBuffer(GPUstate.commandQueue, padbuffer8, true, 0, 1024*1024*4+8, BlockHash_1_MemoryPAD8, 0, NULL, NULL);
			}
*/
			if(status != CL_SUCCESS)
				throw string("Error creating OpenCL command queue");

			GPUstate.CLbuffer[0] = clCreateBuffer(clState.context, CL_MEM_READ_ONLY, KERNEL_INPUT_SIZE, NULL, &status);
			GPUstate.CLbuffer[1] = clCreateBuffer(clState.context, CL_MEM_WRITE_ONLY, KERNEL_OUTPUT_SIZE*sizeof(uint), NULL, &status);
			GPUstate.padbuffer8 = padbuffer8;

			if(status != CL_SUCCESS)
			{
				cout << status << endl;
				throw string("Error creating OpenCL buffer");
			}

			//GPUstate.offset = 0x100000000ULL/globalconfs.coin.threads_per_gpu/numDevices*(device_id*globalconfs.coin.threads_per_gpu+thread_id);
			///@todo gpu offset is dependend on workrange we get from server, so we need to recalc this every getwork!
			pthread_mutex_t initializer = PTHREAD_MUTEX_INITIALIZER;
//			unsigned int fullspeed=400000; //ugly
	//		singleoffset=fullspeed/(globalconfs.coin.threads_per_gpu*numDevices);
//			if(thread_id==0)
				GPUstate.offset  = globalconfs.coin.threads_per_gpu;
//			else
//				GPUstate.offset = (globalconfs.coin.threads_per_gpu*numDevices)*(device_id*globalconfs.coin.threads_per_gpu+thread_id);
			cout <<  GPUstate.offset << " gpu offset for " << thread_id <<endl;
			GPUstate.share_mutex = initializer;
			GPUstate.shares_available = false;
			GPUstate.noncerange_used = false;

			GPUstate.vectors = GetVectorSize();
			GPUstate.thread_id = device_id*numDevices+thread_id;
			GPUstates.push_back(GPUstate);
		}
	}

	if (GPUstates.empty())
	{
		cout << "No GPUs selected." << endl;
		return;
	}

	cout << "Creating " << GPUstates.size() << " GPU threads" << endl;
	for(uint i=0; i<GPUstates.size(); ++i)
	{
		cout << i+1 << "...";
		if (globalconfs.coin.protocol == "bitcoin")
			pthread_create(&GPUstates[i].thread, NULL, Reap_GPU_BTC, (void*)&GPUstates[i]);
		else if (globalconfs.coin.protocol == "litecoin")
			pthread_create(&GPUstates[i].thread, NULL, Reap_GPU_LTC, (void*)&GPUstates[i]);
	}
	cout << "done" << endl;
#endif
}
Example #7
0
int main(int argc, char* argv[])
{
	bool generate = false;
	string sheetType;

	// parse command line
	uint	i;
	for (i=1; (sint)i<argc; i++)
	{
		const char	*arg = argv[i];
		if (arg[0] == '-')
		{
			switch (arg[1])
			{
			case 'p':
				++i;
				if ((sint)i == argc)
				{
					fprintf(stderr, "Missing <sheet path> after -p option\n");
					usage(argv[0], stderr);
					exit(0);
				}
				inputSheetPaths.push_back(argv[i]);
				break;
			case 's':
				++i;
				if ((sint)i == argc)
				{
					fprintf(stderr, "Missing <field_separator> after -s option\n");
					usage(argv[0], stderr);
					exit(0);
				}
				SEPARATOR = argv[i];
				break;
			case 'g':
				++i;
				if ((sint)i == argc)
				{
					fprintf(stderr, "Missing <sheetType> after -g option\n");
					usage(argv[0], stderr);
					exit(0);
				}
				generate = true;
				sheetType = string(argv[i]);
				break;
			case 'o':
				++i;
				if ((sint)i == argc)
				{
					fprintf(stderr, "Missing <output path> after -o option\n");
					usage(argv[0], stderr);
					exit(0);
				}
				OutputPath = string(argv[i]);
				break;
			default:
				fprintf(stderr, "Unrecognized option '%c'\n", arg[1]);
				usage(argv[0], stderr);
				exit(0);
				break;
			}
		}
		else
		{
			if (CFile::getExtension(arg) == "csv")
			{
				inputCsvFiles.push_back(arg);
			}
			else
			{
				inputScriptFiles.push_back(arg);
			}
		}
	}

	if (inputScriptFiles.empty() && inputCsvFiles.empty())
	{
		fprintf(stderr, "Missing input script file or csv file\n");
		usage(argv[0], stderr);
		exit(0);
	}



	for (i=0; i<inputScriptFiles.size(); ++i)
		executeScriptFile(inputScriptFiles[i]);

	for (i=0; i<inputCsvFiles.size(); ++i)
		convertCsvFile(inputCsvFiles[i], generate, sheetType);

	fprintf(stderr,"\nDone.\n");
	getchar();
	return 0;
}
Example #8
0
bool Stack::is_empty() {
	return v.empty();
}
}

BOOST_AUTO_TEST_SUITE(test_fixtures
                      , *utf::fixture<SuiteFixture>(1))

BOOST_AUTO_TEST_CASE(fixture_decorator_on_test_suite)
{
    BOOST_TEST(!container.empty());
    BOOST_TEST(container.size() == 1u);
    BOOST_TEST(*begin(container) == 1);
}

BOOST_AUTO_TEST_CASE(fixture_decorator_on_test_case
                     , *utf::fixture(setup, teardown))
{
    BOOST_TEST(!container.empty());
    BOOST_TEST(container.size() == 3u);

    array<int, 3> expected = {{1, 22, 333}};
    BOOST_TEST(expected == container, tt::per_element());
}

BOOST_AUTO_TEST_CASE(lambda_setup_teardown
                     , *utf::fixture(
                         [] { container.push_back(4444) ; },
                         [] { container.push_back(55555);}))
{
    BOOST_TEST(!container.empty());
    BOOST_TEST(container.size() == 1u);
    BOOST_TEST(*begin(container) == 4444);
}
 bool empty(){ return buffer.empty();}
Example #11
0
void loop() {



  /// Add coordinate axes
  myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());;

  // Read camera frame
  stream1.read(frame);
  //resize(frame, frame, Size(frame.cols*0.8, frame.rows*0.8));
  cvtColor(frame, grey, COLOR_BGR2GRAY);

  // move to function?
  if (!points1.empty()) {
    calcOpticalFlowPyrLK(prevGray, grey, points1, points2, status, err, winSize, 3, termcrit, 0, 0.001);
    // remove bad tracks
    size_t k;
    for (size_t i = k = 0; i < points2.size(); i++) {
      if (!status[i])
        continue;
      points2[k] = points2[i];
      points1[k] = points1[i];
      init[k] = init[i];

      if(rdpoints){
        init3dpoints[k] = init3dpoints[i];
      }
      k++;
      circle(frame, points2[i], 2, Scalar(0, 255, 0), -1, 8);
      if (!rdpoints){
        line(frame, init[i], points2[i], Scalar(0, 255, 0));
      }
    }
    points1.resize(k);
    points2.resize(k);
    init.resize(k);
    if (rdpoints) {
      init3dpoints.resize(k);
    }
  }

  if (points1.size() > 8) {
    totalT = totalT + T;

    cv::Mat rvec(3, 1, cv::DataType<double>::type);
    cv::Mat tvec(3, 1, cv::DataType<double>::type);
    float scale = 0;
    if (init3dpoints.size() > 0) {
      solvePnPRansac(init3dpoints, points2, K, noArray(), rvec, tvec, false, 200,4);
      T = tvec;
      Rodrigues(rvec, R);
      /*frames++;
      T = T + tvec;
      if (frames == 3) {
        T = T / 3;
        circle(poseplot, Point(200 + T.at<double>(0, 0) * 100, 200 + T.at<double>(1, 0) * 100), 2, Scalar(0, 255, 0));
        T = Mat::zeros(3, 1, CV_64F);
        frames = 0;
      }*/
    }
  }

  imshow("cam", frame);

  int key = waitKey(15);

  if (key == ' ') {
    if (started && !rdpoints) {
      rdpoints = 1;
      float f = K.at<double>(0, 0);
      Point2f pp(K.at<double>(0, 2), K.at<double>(1, 2));
      Mat E = findEssentialMat(init, points2, f, pp, RANSAC, 0.99, 1.0, mask);
      int inliers = recoverPose(E, init, points2, R, T, f, pp);
      hconcat(R, T, M1);
      triangulate_points(K*M0, K*M1, init, points2, &init3dpoints);
      c3dpoints.clear();
      for (int i = 0; i < init3dpoints.size(); i++) {
          c3dpoints.push_back(init3dpoints[i]/10);
      }
    }
  }

  std::swap(points2, points1);
  cv::swap(prevGray, grey);

  if (key == ' ' && !rdpoints) {
    started = 1;
    // features and keypoints for object
    img1 = grey.clone();
    keyframes.push_back(img1);
    kpts1.clear();
    init.clear();
    goodFeaturesToTrack(img1, points1, MAX_FEATURES, 0.01, 15, Mat(), 3, 0, 0.04);
    //cornerSubPix(img1, points1, subPixWinSize, Size(-1, -1), termcrit);
    for (size_t i = 0; i < points1.size(); i++) {
      kpts1.push_back(cv::KeyPoint(points1[i], 1.f));
      init.push_back(Point2f(points1[i]));
    }
  }
  else if (key == 'q') {
    exit(0);
  }
  imshow("pose", poseplot);

  // Plot 3D points
  if (!init3dpoints.empty()) {

    viz::WCloud cw(c3dpoints);
    cw.setRenderingProperty(viz::POINT_SIZE, 5);
    myWindow.showWidget("CloudWidget", cw);
    /// Let's assume camera has the following properties
    //double sz[3] = {0,0,-1};
    //Mat fD(3,sz, CV_64F, Scalar::all(0));
    Mat fD = (Mat_<double>(3,1) << 0, 0, -1);
    Mat tmp = R*fD;
    Vec3d cam_pos(T), cam_focal_point(tmp), cam_y_dir(-1.0f,0.0f,0.0f);

    /// We can get the pose of the cam using makeCameraPose
    Affine3f cam_pose = viz::makeCameraPose(cam_pos, cam_focal_point, cam_y_dir);

    /// We can get the transformation matrix from camera coordinate system to global using
    /// - makeTransformToGlobal. We need the axes of the camera
    //Affine3f transform = viz::makeTransformToGlobal(Vec3f(0.0f,-1.0f,0.0f), Vec3f(-1.0f,0.0f,0.0f), Vec3f(0.0f,0.0f,-1.0f), cam_pos);

    /// Create a cloud widget.
    //Mat bunny_cloud = cvcloud_load();
    //viz::WCloud cloud_widget(bunny_cloud, viz::Color::green());

    /// Pose of the widget in camera frame
    //Affine3f cloud_pose = Affine3f().translate(Vec3f(0.0f,0.0f,3.0f));
    /// Pose of the widget in global frame
    //Affine3f cloud_pose_global = transform * cloud_pose;

    /// Visualize camera frame

    viz::WCameraPosition cpw(0.5); // Coordinate axes
    viz::WCameraPosition cpw_frustum(Vec2f(0.889484, 0.523599)); // Camera frustum
    myWindow.showWidget("CPW", cpw, cam_pose);
    myWindow.showWidget("CPW_FRUSTUM", cpw_frustum, cam_pose);

    /// Visualize widget
    //myWindow.showWidget("bunny", cloud_widget, cloud_pose_global);

    /// Set the viewer pose to that of camera
    //myWindow.setViewerPose(cam_pose);

    /// Start event loop.
    //myWindow.spin();
  }
   myWindow.spinOnce(1, true);
}
Example #12
0
bool menukey(int code, bool isdown, int unicode, SDLMod mod)
{
    if(!curmenu) return false;
    int n = curmenu->items.length(), menusel = curmenu->menusel;
    if(isdown)
    {
        bool hasdesc = false;
        loopv(curmenu->items) if(curmenu->items[i]->getdesc()) { hasdesc = true; break;}
        //int pagesize = MAXMENU - (curmenu->header ? 2 : 0) - (curmenu->footer || hasdesc ? 2 : 0); // FIXME: footer-length
        int pagesize = MAXMENU - (curmenu->header ? 2 : 0) - (curmenu->footer ? (curmenu->footlen?(curmenu->footlen+1):2) : (hasdesc ? 2 : 0)); // FIXME: footer-length

        if(curmenu->items.inrange(menusel))
        {
            mitem *m = curmenu->items[menusel];
            if(m->type == mitem::TYPE_KEYINPUT && ((mitemkeyinput *)m)->capture && code != SDLK_ESCAPE)
            {
                m->key(code, isdown, unicode);
                return true;
            }
        }

        switch(code)
        {
            case SDLK_PAGEUP: menusel -= pagesize; break;
            case SDLK_PAGEDOWN:
                if(menusel+pagesize>=n && menusel/pagesize!=(n-1)/pagesize) menusel = n-1;
                else menusel += pagesize;
                break;
            case SDLK_ESCAPE:
            case SDL_AC_BUTTON_RIGHT:
                if(!curmenu->allowinput) return false;
                menuset(menustack.empty() ? NULL : menustack.pop(), false);
                return true;
                break;
            case SDLK_UP:
            case SDL_AC_BUTTON_WHEELUP:
                if(iskeypressed(SDLK_LCTRL)) return menukey(SDLK_LEFT, isdown, 0);
                if(!curmenu->allowinput) return false;
                menusel--;
                break;
            case SDLK_DOWN:
            case SDL_AC_BUTTON_WHEELDOWN:
                if(iskeypressed(SDLK_LCTRL)) return menukey(SDLK_RIGHT, isdown, 0);
                if(!curmenu->allowinput) return false;
                menusel++;
                break;
            case SDLK_TAB:
                if(!curmenu->allowinput) return false;
                if(mod & KMOD_LSHIFT) menusel--;
                else menusel++;
                break;

            case SDLK_PRINT:
                curmenu->conprintmenu();
                return true;

            case SDLK_F12:
            {
                extern void screenshot(const char *imagepath);
                if(!curmenu->allowinput) return false;
                screenshot(NULL);
                break;
            }

            case SDLK_1:
            case SDLK_2:
            case SDLK_3:
            case SDLK_4:
            case SDLK_5:
            case SDLK_6:
            case SDLK_7:
            case SDLK_8:
            case SDLK_9:
                if(curmenu->allowinput && curmenu->hotkeys)
                {
                    int idx = code-SDLK_1;
                    if(curmenu->items.inrange(idx))
                    {
                        menuselect(curmenu, idx);
                        mitem &m = *curmenu->items[idx];
                        m.select();
                    }
                    return true;
                }
            default:
            {
                if(!curmenu->allowinput) return false;
                if(curmenu->keyfunc && (*curmenu->keyfunc)(curmenu, code, isdown, unicode)) return true;
                if(!curmenu->items.inrange(menusel)) return false;
                mitem &m = *curmenu->items[menusel];
                m.key(code, isdown, unicode);
                return !curmenu->forwardkeys;
            }
        }

        if(!curmenu->hotkeys) menuselect(curmenu, menusel);
        return true;
    }
    else
    {
        if(!curmenu->allowinput || !curmenu->items.inrange(menusel)) return false;
Example #13
0
void PreComputeTA(char * filename, vector<vector<Cell> >& storebyrow, map<int, vector<float> >& index)
{
	Tuples allTuples;
	
	ReadData(filename, allTuples);

    int dimension;
    cout<<"Input Dimension:"<<endl;
    scanf("%d", &dimension);

	vector<list<Cell> >  sortedTuples(dimension);

    int position[5] = {0,1,2, 3, 4};

	for(Tuples::iterator iter = allTuples.begin(); iter!=allTuples.end(); iter++)
	{
		Tuple tuple = *iter;
		vector<float> needed_attr;
		
		for(int i=0; i<dimension; i++)
		{
			Cell temp;
			temp.ID = tuple.ID;
			try{
				temp.data = tuple.data.at(position[i]);
				needed_attr.push_back(temp.data);
				sortedTuples.at(i).push_back(temp);
			}
			catch(out_of_range outOfRange)
			{
				cout << "\n\nException1: "<<outOfRange.what()<<endl;
				cout<< tuple.data.size()<<","<<tuple.ID;
				return;
			}
		}

		index.insert(pair<int, vector<float> >(tuple.ID, needed_attr));
	}


	for(vector<list<Cell> >::iterator iter = sortedTuples.begin(); iter!=sortedTuples.end(); iter++)
	{
		(*iter).sort(compfn);

		list<Cell>  temp = *iter;

		if(storebyrow.empty())
		{
			for(list<Cell>::iterator iter1 = temp.begin(); iter1!=temp.end();iter1++)
			{
				vector<Cell> tempvector;
				Cell tempCell;

				tempCell.ID = iter1->ID;
				tempCell.data = iter1->data;

				tempvector.push_back(tempCell);

				storebyrow.push_back(tempvector);	
			}
		}

		else
		{
			unsigned int i = 0;
			for(list<Cell>::iterator iter1 = temp.begin(); iter1!=temp.end();iter1++, i++)
			{
				Cell tempCell;

				tempCell.ID = iter1->ID;
				tempCell.data = iter1->data;

				storebyrow[i].push_back(tempCell);
			}

			assert(i == temp.size());
		}
	}	


}
Example #14
0
void
ctlToLut (vector<string> transformNames,
	  Header inHeader,
	  size_t lutSize,
	  const half pixelValues[/*lutSize*/],
	  half lut[/*lutSize*/])
{
    //
    // If we do not have an explicit set of transform names
    // then find suitable look modification, rendering and
    // display transforms.
    //

    if (transformNames.empty())
    {
	if (hasLookModTransform (inHeader))
	    transformNames.push_back (lookModTransform (inHeader));

	if (hasRenderingTransform (inHeader))
	    transformNames.push_back (renderingTransform (inHeader));
	else
	    transformNames.push_back ("transform_RRT");

	transformNames.push_back (displayTransformName());
    }

    //
    // Initialize an input and an environment header:
    // Make sure that the headers contain information about the primaries
    // and the white point of the image files an the display, and about
    // the display's white luminance and surround luminance.
    //

    Header envHeader;
    Header outHeader;

    if (!hasChromaticities (inHeader))
	addChromaticities (inHeader, Chromaticities());

    if (!hasAdoptedNeutral (inHeader))
	addAdoptedNeutral (inHeader, chromaticities(inHeader).white);

    initializeEnvHeader (envHeader);

    //
    // Set up input and output FrameBuffer objects for the CTL transforms.
    //

    assert (lutSize % 4 == 0);

    FrameBuffer inFb;

    inFb.insert ("R",
		 Slice (HALF,				// type
		        (char *)pixelValues,		// base
			4 * sizeof (half),		// xStride
			0));				// yStride

    inFb.insert ("G",
		 Slice (HALF,				// type
			(char *)(pixelValues + 1),	// base
			4 * sizeof (half),		// xStride
			0));				// yStride

    inFb.insert ("B",
		 Slice (HALF,				// type
			(char *)(pixelValues + 2),	// base
			4 * sizeof (half),		// xStride
			0));				// yStride

    FrameBuffer outFb;

    outFb.insert ("R_display",
		  Slice (HALF,				// type
			 (char *)lut,			// base
			 4 * sizeof (half),		// xStride
			 0));				// yStride

    outFb.insert ("G_display",
		  Slice (HALF,				// type
			 (char *)(lut + 1),		// base
			 4 * sizeof (half),		// xStride
			 0));				// yStride

    outFb.insert ("B_display",
		  Slice (HALF,				// type
			 (char *)(lut + 2),		// base
			 4 * sizeof (half),		// xStride
			 0));				// yStride

    //
    // Run the CTL transforms.
    //

    SimdInterpreter interpreter;

    #ifdef CTL_MODULE_BASE_PATH

	//
	// The configuration scripts has defined a default
	// location for CTL modules.  Include this location
	// in the CTL module search path.
	//

	vector<string> paths = interpreter.modulePaths();
	paths.push_back (CTL_MODULE_BASE_PATH);
	interpreter.setModulePaths (paths);

    #endif

    ImfCtl::applyTransforms (interpreter,
			     transformNames,
			     Box2i (V2i (0, 0), V2i (lutSize / 4 - 1, 0)),
			     envHeader,
			     inHeader,
			     inFb,
			     outHeader,
			     outFb);
}
Example #15
0
   vector<vector<int> > fourSum(vector<int> &num, int target) {
      // Note: The Solution object is instantiated only once and is reused by each test case.
        
      vector<vector<int> > result;

      if(num.empty()) return result;

      sort(num.begin(), num.end());
        
      unordered_multimap<int, int> MM;
      unordered_map<int, bool> visited;

      int sz = num.size();
      for(int i=0; i<sz; i++)
      {
         if(i > 0 && num[i-1] == num[i]) continue;
         for(int j=i+1; j<sz; j++)
         {
            if(j-1 > i && num[j-1] == num[j]) continue; 
            MM.insert({{num[i] + num[j], i*sz + j}});
         }
      }
        
      for(int i=0; i<sz; i++)
      {
         for(int j=i+1; j<sz; j++)
         {
            int t = target - (num[i] + num[j]);
            if(MM.find(t) != MM.end())
            {
               auto range = MM.equal_range(t);
               for(auto it = range.first; it != range.second; ++it)
               {
                  int m = it->second / sz;
                  int n = it->second % sz; // note that m < n and i < j
                     
                  vector<int> index = {i, j, m, n};
                  sort(index.begin(), index.end());
                  auto pos = unique(index.begin(), index.end());
                  index.resize(distance(index.begin(), pos));
                  if(index.size() == 4)
                  {
                     int n1 = num[ index[0] ] - num[0];
                     int n2 = num[ index[1] ] * sz;
                     int n3 = num[ index[2] ] * sz*sz;
                     int n4 = num[ index[3] ] * sz*sz*sz;

                     if(!visited[n1+n2+n3+n4])
                     {
                        visited[n1+n2+n3+n4] = true;
                        vector<int> sol;                          
                        for_each(index.begin(), index.end(), [&sol, &num](int x){ sol.push_back(num[x]); });
                        result.push_back(sol);
                     }
                  }
               }//for
            }
         }
      }//for

      return result;
   }
Example #16
0
    int numDistinctIslands(vector<vector<int>>& grid) {
        if(grid.empty() || grid[0].empty()) return 0;
        int m = grid.size();
        int n = grid[0].size();

        vector<int> p(m * n, -1);
        for(int i = 0; i < m; ++i) {
            for(int j = 0; j < n; ++j) {
                int idx = n * i + j;
                //cout<<i<<" "<<j<<" "<<idx<<endl;
                if(grid[i][j]) {
                    int p1 = -1, p2 = -1;
                    if(i > 0 && grid[i - 1][j]) {
                        p1 = getParent(p, n * (i - 1) + j);
                    }

                    if(j > 0 && grid[i][j - 1]) {
                        p2 = getParent(p, n * i + j - 1);
                    }
                    
                    if(p1 != -1 && p2 != -1) {
                        p[idx] = min(p1, p2);
                        p[max(p1, p2)] = min(p1, p2);
                    }
                    else if(p1 != -1) {
                        p[idx] = p1;
                    }
                    else if(p2 != -1) {
                        p[idx] = p2;
                    }
                    else {
                        p[idx] = idx;
                    }
                }
            }
        }

        //for(int i = 0; i < m * n; ++i)
        //cout<<p[i]<<endl;
        unordered_map<int, vector<int>> islands;
        for(int i = 0; i < m * n; ++i)
        {
            if(p[i] != -1)
            {
                int pp = getParent(p, i);
                islands[pp].push_back(i);
            }
        }

        set<vector<pair<int, int>>> s;
        for(auto& p : islands)
        {
            vector<pair<int, int>> t;
            auto& v = p.second;
            int x = v[0] / n;
            int y = v[0] % n;
            for_each(v.begin(), v.end(), [&](int& idx){ 
                t.emplace_back(make_pair(idx / n - x, idx % n - y));
            });
            s.insert(t);
        }
        return s.size();
    }
Example #17
0
	// Returns the results into ptRes
	void FilterBoostClassifier::computeResults(InputData* pData, vector<BaseLearner*>& weakHypotheses, 
		vector< ExampleResults* >& results, int numIterations)
	{
		assert( !weakHypotheses.empty() );

		const int numClasses = pData->getNumClasses();
		const int numExamples = pData->getNumExamples();

		// Initialize the output info
		OutputInfo* pOutInfo = NULL;

		if ( !_outputInfoFile.empty() )
			pOutInfo = new OutputInfo(_outputInfoFile);

		// Creating the results structures. See file Structures.h for the
		// PointResults structure
		results.clear();
		results.reserve(numExamples);
		for (int i = 0; i < numExamples; ++i)
			results.push_back( new ExampleResults(i, numClasses) );

		// iterator over all the weak hypotheses
		vector<BaseLearner*>::const_iterator whyIt;
		int t;

		if ( pOutInfo )
			pOutInfo->initialize( pData );

		// for every feature: 1..T
		for (whyIt = weakHypotheses.begin(), t = 0; 
			whyIt != weakHypotheses.end() && t < numIterations; ++whyIt, ++t)
		{
			BaseLearner* currWeakHyp = *whyIt;
			float alpha = currWeakHyp->getAlpha();

			// for every point
			for (int i = 0; i < numExamples; ++i)
			{
				// a reference for clarity and speed
				vector<float>& currVotesVector = results[i]->getVotesVector();

				// for every class
				for (int l = 0; l < numClasses; ++l)
					currVotesVector[l] += alpha * currWeakHyp->classify(pData, i, l);
			}

			// if needed output the step-by-step information
			if ( pOutInfo )
			{
				pOutInfo->outputIteration(t);
				pOutInfo->outputError(pData, currWeakHyp);
				
				pOutInfo->outputBalancedError(pData, currWeakHyp);
				if ( ( t % 1 ) == 0 ) {
					pOutInfo->outputROC(pData, currWeakHyp);
				}

				// Margins and edge requires an update of the weight,
				// therefore I keep them out for the moment
				//outInfo.outputMargins(pData, currWeakHyp);
				//outInfo.outputEdge(pData, currWeakHyp);
				pOutInfo->endLine();
			}
		}

		if (pOutInfo)
			delete pOutInfo;

	}
Example #18
0
static BOOL CALLBACK FavoriteVolumesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    /* This dialog is used both for System Favorites and non-system Favorites.

    The following options have different meaning in System Favorites mode:

    IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT	=> MOUNT_SYSTEM_FAVORITES_ON_BOOT
    IDC_FAVORITE_DISABLE_HOTKEY		=> DISABLE_NONADMIN_SYS_FAVORITES_ACCESS

    */

    WORD lw = LOWORD (wParam);
    static bool SystemFavoritesMode;
    static vector <FavoriteVolume> Favorites;
    static int SelectedItem;
    static HWND FavoriteListControl;

    switch (msg)
    {
    case WM_INITDIALOG:
    {
        try
        {
            FavoriteListControl = GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUMES_LIST);

            FavoriteVolumesDlgProcArguments *args = (FavoriteVolumesDlgProcArguments *) lParam;
            SystemFavoritesMode = args->SystemFavorites;

            LocalizeDialog (hwndDlg, SystemFavoritesMode ? "SYSTEM_FAVORITES_DLG_TITLE" : "IDD_FAVORITE_VOLUMES");

            if (SystemFavoritesMode)
            {
                RECT rec;

                BootEncryptionStatus bootEncStatus = BootEncryption (hwndDlg).GetStatus();

                if (!bootEncStatus.DriveMounted)
                    throw ErrorException ("SYS_FAVORITES_REQUIRE_PBA", SRC_POS);

                ShowWindow (GetDlgItem(hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON), SW_HIDE);
                ShowWindow (GetDlgItem(hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL), SW_HIDE);

                // MOUNT_SYSTEM_FAVORITES_ON_BOOT

                SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT), GetString ("MOUNT_SYSTEM_FAVORITES_ON_BOOT"));

                // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS

                SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY), GetString ("DISABLE_NONADMIN_SYS_FAVORITES_ACCESS"));

                // Group box

                GetClientRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), &rec);

                SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, 0, 0,
                              rec.right,
                              rec.bottom - CompensateYDPI (90),
                              SWP_NOMOVE | SWP_NOZORDER);

                InvalidateRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), NULL, TRUE);
            }
            else
            {
                ShowWindow (GetDlgItem(hwndDlg, IDC_FAV_VOL_OPTIONS_GLOBAL_SETTINGS_BOX), SW_HIDE);
            }

            Favorites.clear();

            LVCOLUMNW column;
            SendMessageW (FavoriteListControl, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT);

            memset (&column, 0, sizeof (column));
            column.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT;
            column.pszText = GetString ("DRIVE");
            column.cx = CompensateXDPI (38);
            column.fmt = LVCFMT_CENTER;
            SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 1, (LPARAM) &column);

            ++column.iSubItem;
            column.fmt = LVCFMT_LEFT;
            column.pszText = GetString ("LABEL");
            column.cx = CompensateXDPI (160);
            SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 2, (LPARAM) &column);

            ++column.iSubItem;
            column.fmt = LVCFMT_LEFT;
            column.pszText = GetString ("VOLUME");
            column.cx = CompensateXDPI (330);
            SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 3, (LPARAM) &column);

            SetControls (hwndDlg, FavoriteVolume(), SystemFavoritesMode, false);

            if (SystemFavoritesMode)
                LoadFavoriteVolumes (Favorites, true);
            else
                Favorites = FavoriteVolumes;

            if (args->AddFavoriteVolume)
                Favorites.push_back (args->NewFavoriteVolume);

            FillListControl (FavoriteListControl, Favorites);

            SelectedItem = -1;

            if (args->AddFavoriteVolume)
            {
                ListView_SetItemState (FavoriteListControl, Favorites.size() - 1, LVIS_SELECTED, LVIS_SELECTED);
                ListView_EnsureVisible (FavoriteListControl, Favorites.size() - 1, FALSE);
            }

            if (SystemFavoritesMode)
                SetDlgItemTextW (hwndDlg, IDC_FAVORITES_HELP_LINK, GetString ("SYS_FAVORITES_HELP_LINK"));

            ToHyperlink (hwndDlg, IDC_FAVORITES_HELP_LINK);
        }
        catch (Exception &e)
        {
            e.Show (hwndDlg);
            EndDialog (hwndDlg, IDCLOSE);
        }
    }
    return 1;

    case WM_COMMAND:

        switch (lw)
        {
        case IDOK:

            /* Global System Favorites settings */

            if (SystemFavoritesMode)
            {
                BootEncryption BootEncObj (NULL);

                if (BootEncObj.GetStatus().DriveMounted)
                {
                    try
                    {
                        uint32 reqConfig = IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT) ? TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES : 0;
                        if (reqConfig != (ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES))
                            BootEncObj.RegisterSystemFavoritesService (reqConfig ? TRUE : FALSE);

                        SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS, IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY));
                    }
                    catch (Exception &e)
                    {
                        e.Show (hwndDlg);
                    }
                }
            }

            /* (System) Favorites list */

            if (SelectedItem != -1 && !Favorites.empty())
                SetFavoriteVolume (hwndDlg, Favorites[SelectedItem], SystemFavoritesMode);

            if (SaveFavoriteVolumes (hwndDlg, Favorites, SystemFavoritesMode))
            {
                if (!SystemFavoritesMode)
                {
                    bMountFavoritesOnLogon = FALSE;

                    foreach (const FavoriteVolume &favorite, Favorites)
                    {
                        if (favorite.MountOnLogOn)
                        {
                            bMountFavoritesOnLogon = TRUE;
                            break;
                        }
                    }

                    if (!bEnableBkgTask || bCloseBkgTaskWhenNoVolumes || IsNonInstallMode())
                    {
                        foreach (const FavoriteVolume favorite, Favorites)
                        {
                            if (favorite.MountOnArrival)
                            {
                                Warning ("FAVORITE_ARRIVAL_MOUNT_BACKGROUND_TASK_ERR", hwndDlg);
                                break;
                            }
                        }
                    }

                    FavoriteVolumes = Favorites;

                    ManageStartupSeq();
                    SaveSettings (hwndDlg);
                }
                else
                    SystemFavoriteVolumes = Favorites;

                OnFavoriteVolumesUpdated();
                LoadDriveLetters (hwndDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0);

                EndDialog (hwndDlg, IDOK);
            }
Example #19
0
    int maxKilledEnemies(vector<vector<char>>& grid) {
        if (grid.empty() || grid[0].empty()) return 0;
        int m = grid.size();
        int n = grid[0].size();

        // dp1[i][j] (1<=i<=m && 1<=j<=m) means the number of enemies to the prev-left and prev-top wall
        // dp2[i][j] (1<=i<=m && 1<=j<=m) means the number of enemies to the prev-right and prev-bottom wall
        vector<vector<pair<int, int>>> dp1, dp2;
        dp1 = dp2 = vector<vector<pair<int, int>>>(m+2, vector<pair<int, int>>(n+2, {0, 0}));

        queue<pair<int, int>> aQueue;

        // from  top-left to bottom-right
        char c;
        for (int i=1; i<=m; ++i) {
            for (int j=1; j<=n; ++j) {
                c = grid[i-1][j-1];
                auto &cur = dp1[i][j];
                if (c == 'E') {
                    cur.first = dp1[i-1][j].first + 1;
                    cur.second = dp1[i][j-1].second + 1;
                } else if (c == 'W') {
                    cur.first = 0;
                    cur.second = 0;
                } else {
                    aQueue.push({i, j});
                    cur.first = dp1[i-1][j].first;
                    cur.second = dp1[i][j-1].second;
                }
            }
        }

        // from  bottom-right to top-left
        for (int i=m; i>=1; --i) {
            for (int j=n; j>=1; --j) {
                c = grid[i-1][j-1];
                auto &cur = dp2[i][j];
                if (c == 'E') {
                    cur.first = dp2[i+1][j].first + 1;
                    cur.second = dp2[i][j+1].second + 1;
                } else if (c == 'W') {
                    cur.first = 0;
                    cur.second = 0;
                } else {
                    cur.first = dp2[i+1][j].first;
                    cur.second = dp2[i][j+1].second;
                }
            }
        }

        int res = 0;
        int x, y;
        int cnt = 0;
        while (!aQueue.empty()) {
            cnt = 0;
            x = aQueue.front().first;
            y = aQueue.front().second;
            aQueue.pop();
            cnt += dp1[x][y].first;
            cnt += dp1[x][y].second;
            cnt += dp2[x][y].first;
            cnt += dp2[x][y].second;
            if (cnt > res) res = cnt;
        }

        return res;
    }
Example #20
0
// Highest price is the first element of MaxHeap. Complexity: O(1)
double Orderbook::getHighestPrice()
{
    return records.empty() ? NAN : records.front().price;
}
Example #21
0
void PrintLog(const char* fmt, const char* function, bool error, ...)
{
  string                logstr;
  string                funcstr;
  va_list               args;
  int                   nrspaces;

  static int            logbuffsize = 128; //size of the buffer
  static char*          logbuff = reinterpret_cast<char*>(malloc(logbuffsize)); //buffer for vsnprintf
  static vector<string> logstrings;      //we save any log lines here while the log isn't open

  CLock lock(g_logmutex);
  
  va_start(args, error);

  //print to the logbuffer and check if our buffer is large enough
  int neededbuffsize = vsnprintf(logbuff, logbuffsize, fmt, args);
  if (neededbuffsize + 1 > logbuffsize)
  {
    logbuffsize = neededbuffsize + 1;
    logbuff = reinterpret_cast<char*>(realloc(logbuff, logbuffsize)); //resize the buffer to the needed size

    va_end(args); //need to reinit or we will crash
    va_start(args, error);

    vsnprintf(logbuff, logbuffsize, fmt, args);                       //write to the buffer again
  }
  
  va_end(args);

  if (error)
    logstr += "ERROR: ";

  logstr += logbuff;

  funcstr = "(" + PruneFunction(function) + ")";
  nrspaces = 32 - funcstr.length();
  if (nrspaces > 0)
    funcstr.insert(funcstr.length(), nrspaces, ' ');
  
  if (g_logfile.is_open() && printlogtofile)
  {
    //print any saved log lines
    if (!logstrings.empty())
    {
      for (int i = 0; i < logstrings.size(); i++)
      {
        g_logfile << logstrings[i] << flush;
      }
      logstrings.clear();
    }
    //write the string to the logfile
    g_logfile << GetStrTime() << " " << funcstr << " " << logstr << '\n' << flush;
  }
  else if (printlogtofile)
  {
    //save the log line if the log isn't open yet
    logstrings.push_back(GetStrTime() + " " + funcstr + " " + logstr + '\n');
  }

  //print to stdout when requested
  if (logtostderr)
    cerr << funcstr << logstr << '\n' << flush;
}
Example #22
0
bool ConfigServer::init( vector<string> configHosts , bool infer ) {
    string hn = getHostName();
    if ( hn.empty() ) {
        sleepsecs(5);
        exit(16);
    }
    ourHostname = hn;

    char buf[256];
    strcpy(buf, hn.c_str());

    if ( configHosts.empty() ) {
        char *p = strchr(buf, '-');
        if ( p )
            p = strchr(p+1, '-');
        if ( !p ) {
            log() << "can't parse server's hostname, expect <city>-<locname>-n<nodenum>, got: " << buf << endl;
            sleepsecs(5);
            exit(17);
        }
        p[1] = 0;
    }

    string left, right; // with :port#
    string hostLeft, hostRight;

    if ( configHosts.empty() ) {
        if ( ! infer ) {
            out() << "--configdb or --infer required\n";
            exit(7);
        }
        stringstream sl, sr;
        sl << buf << "grid-l";
        sr << buf << "grid-r";
        hostLeft = sl.str();
        hostRight = sr.str();
        sl << ":" << Port;
        sr << ":" << Port;
        left = sl.str();
        right = sr.str();
    }
    else {
        hostLeft = getHost( configHosts[0] , false );
        left = getHost( configHosts[0] , true );

        if ( configHosts.size() > 1 ) {
            hostRight = getHost( configHosts[1] , false );
            right = getHost( configHosts[1] , true );
        }
    }


    if ( !isdigit(left[0]) )
        /* this loop is not really necessary, we we print out if we can't connect
           but it gives much prettier error msg this way if the config is totally
           wrong so worthwhile.
           */
        while ( 1 ) {
            if ( hostbyname(hostLeft.c_str()).empty() ) {
                log() << "can't resolve DNS for " << hostLeft << ", sleeping and then trying again" << endl;
                sleepsecs(15);
                continue;
            }
            if ( !hostRight.empty() && hostbyname(hostRight.c_str()).empty() ) {
                log() << "can't resolve DNS for " << hostRight << ", sleeping and then trying again" << endl;
                sleepsecs(15);
                continue;
            }
            break;
        }

    Nullstream& l = log();
    l << "connecting to griddb ";

    if ( !hostRight.empty() ) {
        // connect in paired mode
        l << "L:" << left << " R:" << right << "...";
        l.flush();
        _primary = left + "," + right;
    }
    else {
        l << left << "...";
        l.flush();
        _primary = left;
    }

    return true;
}
Example #23
0
    bool search(vector<int> &A, int target) {

        // write your code here


        if (A.empty())

        {

            return false;

        }

        int l = 0;

        int r = A.size() - 1;

        while (l + 1 < r)

        {

            int mid = l + (r - l) / 2;

            while (r > mid && A[r] == A[mid])

            {

                --r;

                mid = l + (r - l) / 2;

            }

            if (A[l] < A[r])

            {

                if (A[mid] < target)

                {

                    l = mid;

                }

                else

                {

                    r = mid;

                }

            }

            else

            {

                if (A[mid] < A[r])

                {

                    if (A[mid] < target && target <= A[r])

                    {

                        l = mid;

                    }

                    else

                    {

                        r = mid;

                    }

                }

                else

                {

                    if (A[l] <= target && target < A[mid])

                    {

                        r = mid;

                    }

                    else

                    {

                        l = mid;

                    }

                }

            }

        }



        return A[l] == target || A[r] == target;

    }
static bool isShardMetadataChanging(const vector<ShardError*>& staleErrors) {
    if (!staleErrors.empty() && staleErrors.back()->error.isErrInfoSet())
        return staleErrors.back()->error.getErrInfo()["inCriticalSection"].trueValue();
    return false;
}
int main( int argc, char** argv )
{
	VideoCapture cap;
	TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
	Size subPixWinSize(10,10), winSize(31,31);

	const int MAX_COUNT = 500;
	bool needToInit = false;
	bool nightMode = false;

	cap.open(0);

	if( !cap.isOpened() )
	{
		cout << "Could not initialize capturing...\n";
		return 0;
	}

	help();

	namedWindow( "PlaneTracking", 1 );
	setMouseCallback( "PlaneTracking", onMouse, 0 );

	Mat gray, prevGray, image;

	for(;;)
	{
		Mat frame;
		cap >> frame;
		if( frame.empty() )
			break;

		frame.copyTo(image);
		cvtColor(image, gray, CV_BGR2GRAY); 

		if( nightMode )
			image = Scalar::all(0);

		if( needToInit )
		{
			// automatic initialization
			/*goodFeaturesToTrack(gray, points[1], MAX_COUNT, 0.01, 10, Mat(), 3, 0, 0.04);
			cornerSubPix(gray, points[1], subPixWinSize, Size(-1,-1), termcrit);*/

			initTrackingPoints(frame);
			addRemovePt = false;
		}
		else if( !trackPtsPre.empty() )
		{
			vector<uchar> status;
			vector<float> err;
			if(prevGray.empty())
				gray.copyTo(prevGray);
			calcOpticalFlowPyrLK(prevGray, gray, trackPtsPre, trackPtsCur, status, err, winSize,
				3, termcrit, 0, 0, 0.001);

			size_t i, k;
			for( i = k = 0; i < trackPtsCur.size(); i++ )
			{
				if( addRemovePt )
				{
					if( norm(pt - trackPtsCur[i]) <= 5 )
					{
						addRemovePt = false;
						continue;
					}
				}

				if( !status[i] )
					continue;

				trackPtsCur[k++] = trackPtsCur[i];
				circle( image, trackPtsCur[i], 3, Scalar(0,255,0), -1, 8);
			}
			trackPtsCur.resize(k);
		}

		if( addRemovePt && trackPtsCur.size() < (size_t)MAX_COUNT )
		{
			vector<Point2f> tmp;
			tmp.push_back(pt);
			cornerSubPix( gray, tmp, winSize, cvSize(-1,-1), termcrit);
			trackPtsCur.push_back(tmp[0]);
			addRemovePt = false;
		}

		needToInit = false;
		imshow("LK Demo", image);

		char c = (char)waitKey(10);
		if( c == 27 )
			break;
		switch( c )
		{
		case 'r':
			needToInit = true;
			break;
		case 'c':
			trackPtsCur.clear();
			break;
		case 'n':
			nightMode = !nightMode;
			break;
		default:
			;
		}

		std::swap(trackPtsCur, trackPtsPre);
		swap(prevGray, gray);
	}

	return 0;
}
Example #26
0
/***************************************************************************//**
 * psim_rr
 *
 * Author:
 * Daniel Andrus
 * 
 * Description:
 * Simulates a round-robin process scheduler on a list of processes using the
 * supplied time quantum.
 *
 * Parameters:
 * processes - Vector of proc structs listing the incoming processes in the
 * order of their arrival.
 * quanum - The time quantum to use for the simulation. Must be a positive
 * integer to avoid an infinite loop.
 ******************************************************************************/
void psim_rr( vector<proc> &processes, const int quantum )
{
  vector<proc> queue;
  proc current;
  current.id = 0;
  current.remaining = -1;
  int t = 0;
  int q = -1;
  int proc_count = processes.size();
  double wait_time = 0.0;       // average waiting time
  double throughput = 0.0;      // throughput
  double turnaround = 0.0;      // turnaround time
  double response_time = 0.0;   // average response time
  double idle_time = 0.0;
  
  for( t = 0; !processes.empty() || !queue.empty() || current.remaining > 0; t++ )
  {
    // handle incoming processes
    if ( !processes.empty() && processes.front().start == t )
    {
      // add all incoming processes at this time to queue
      while( !processes.empty() && processes.front().start == t )
      {
        cout << t << ": incoming process " << processes.front().id << endl;
        
        queue.push_back( processes.front() );
        processes.erase( processes.begin() );
      }
      
      // no sorting for RR
    }
    
    // Print output for currently running process
    if( current.remaining == 0 || q == 0 )
    {
      if( current.remaining == 0 )
      {
        cout << t << ": finished process " << current.id << endl;
        turnaround += t - current.start;
      }
      else if( current.remaining > 0 && q == 0 )
      {
        cout << t << ": paused process " << current.id << endl;
      }
    }
    
    // Handle outgoing processes
    if((( current.remaining <= 0 || q <= 0 ) && !queue.empty() )
       || ( current.remaining > 0 && q <= 0 ))
    {
      // Add currently running process back into the queue
      if( current.remaining > 0 && q == 0 )
      {
        queue.push_back( current );
      }
      
      // Start up first process in queue
      current = queue.front();
      queue.erase( queue.begin() );
      q = quantum;
      
      // Stats upkeep
      if( current.remaining == current.length )
      {
        response_time += t - current.start;
      }
      
      // Display output
      cout << t << ": started process " << current.id << endl;
    }
    
    // Upkeep
    if (current.remaining <= 0)
    {
      idle_time += 1.0;
    }
    if( current.remaining >= 0 && q >= 0 )
    {
      current.remaining--;
      q--;
    }
    wait_time += queue.size();
  }
  
  // Final output
  cout << t-1 << ": finished process " << current.id << endl;
  cout << t-1 << ": end\n" << endl;
  
  // Update & output stats
  wait_time /= proc_count;
  throughput = (double) proc_count / (double) (t-1);
  turnaround += (t-1) - current.start;
  turnaround /= proc_count;
  response_time /= proc_count;
  cout << "total idle time:         " << idle_time << endl;
  cout << "system throughput:       " << throughput << endl;
  cout << "average wait time:       " << wait_time << endl;
  cout << "average turnaround time: " << turnaround << endl;
  cout << "average response time:   " << response_time << endl;
}
void RenderingEngine::Initialize(const vector<ISurface*>& surfaces)
{
    vector<ISurface*>::const_iterator surface;
    for (surface = surfaces.begin();
         surface != surfaces.end(); ++surface) {
        // Create the VBO for the vertices.
        vector<float> vertices;
        (*surface)->GenerateVertices(vertices, VertexFlagsNormals);
        GLuint vertexBuffer;
        glGenBuffers(1, &vertexBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
        glBufferData(GL_ARRAY_BUFFER,
                     vertices.size() * sizeof(vertices[0]),
                     &vertices[0],
                     GL_STATIC_DRAW);

        // Create a new VBO for the indices if needed.
        int indexCount = (*surface)->GetLineIndexCount();
        GLint indexBuffer;
        if (!m_drawable.empty() &&
                indexCount == m_drawables[0].IndexCount) {
            indexBuffer = m_drawables[0].IndexBuffer;
        } else {
            vector<GLushort> indices(indexCount);
            (*sourface)->GenerateLineIndices(indices);
            glGenBuffers(1, &indexbuffer);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
            glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                    indexCount * sizeof(GLushort),
                    &indices[0],
                    GL_STATIC_DRAW);
        }

        Drawable drawalbe = { vertexBuffer, indexBuffer, indexCount };
        m_drawables.push_back(drawable);
    }

    // 프레임 버퍼 객체를 생성한다.
    // GLuint framebuffer;
    // glGenFramebuffersOES(1, &framebuffer);
    // glBindFramebufferOES(GL_FRAMEBUFFER_OES, framebuffer);
    // glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
    //                             GL_COLOR_ATTACHMENT0_OES,
    //                             GL_RENDERBUFFER_OES,
    //                             m_colorRenderbuffer);

    // glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_colorRenderbuffer);

    // 여러 GL상태를 설정한다.
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);

    // 물체 속성을 설정한다.
    vec4 specular(0.5f, 0.5f, 0.5f, 1);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular.Pointer());
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50.0f);

    m_translation = mat4::Translate(0, 0, -7);
}
Example #28
0
/***************************************************************************//**
 * psim_sjf
 *
 * Author:
 * Daniel Andrus
 * 
 * Description:
 * Simulates a shortest-job-first process scheduler on a list of processes
 *
 * Parameters:
 * processes - Vector of proc structs listing the incoming processes in the
 * order of their arrival.
 ******************************************************************************/
void psim_sjf( vector<proc> &processes )
{
  // declare variables
  vector<proc> queue;
  proc current;
  current.id = 0;
  current.remaining = -1;
  int t = 0;
  int proc_count = processes.size();
  double wait_time = 0.0;       // average waiting time
  double throughput = 0.0;      // throughput
  double turnaround = 0.0;      // turnaround time
  double response_time = 0.0;   // average response time
  double idle_time = 0.0;

  // run time simulation
  for( t = 0; !processes.empty() || !queue.empty() || current.remaining > 0; t++ )
  {

    // handle incoming processes
    if( !processes.empty() && processes.front().start == t )
    {
      // add all incoming processes at this time to queue
      while( !processes.empty() && processes.front().start == t )
      {
        cout << t << ": incoming process " << processes.front().id << endl;
        
        queue.push_back( processes.front() );
        processes.erase( processes.begin() );
      }

      // sort queue by shortest job
      // note fanceh lambda function
      sort( queue.begin(), queue.end(), []( const proc& p1, const proc& p2 ) -> bool
      {
        return( p1.remaining < p2.remaining );
      });
    }
    
    // Print ouput for currently running process
    if( current.remaining == 0 )
    {
      cout << t << ": finished process " << current.id << endl;
      turnaround += t - current.start;
    }
    
    // Handle outgoing processes, replace with item in front of queue
    if( current.remaining <= 0 && !queue.empty() )
    {
      current = queue.front();
      queue.erase( queue.begin() );
      
      // Stats upkeep
      if( current.remaining == current.length )
      {
        response_time += t - current.start;
      }
      
      cout << t << ": started process " << current.id << endl; 
    }
    
    // Upkeep
    if (current.remaining <= 0)
    {
      idle_time += 1.0;
    }
    if( current.remaining >= 0 )
    {
      current.remaining--;
    }
    wait_time += queue.size();
  }
  
  // Final output
  cout << t-1 << ": finished process " << current.id << endl;
  cout << t-1 << ": end\n" << endl;
  
  // Update & output stats
  wait_time /= proc_count;
  throughput = (double) proc_count / (double) (t-1);
  turnaround += (t-1) - current.start;
  turnaround /= proc_count;
  response_time /= proc_count;
  cout << "total idle time:         " << idle_time << endl;
  cout << "system throughput:       " << throughput << endl;
  cout << "average wait time:       " << wait_time << endl;
  cout << "average turnaround time: " << turnaround << endl;
  cout << "average response time:   " << response_time << endl;
}
 bool hasNext()
 {
     if(result.empty()) return false;
     if(nextIndex >= result.size()) return false;
     else return true;
 }
Example #30
0
 bool           empty () const { return (mode == none || ids.empty()); }