Example #1
0
// Updates the local constant buffer and 
// push it to the buffer on the device
void DemoGame::UpdateScene(float dt)
{
	if(GetAsyncKeyState(VK_ADD)){
		std::random_device rd;
		std::default_random_engine rnd(rd());
		std::uniform_int_distribution<int> uInt(-50, 50);
		GameObject* go = new GameObject();
		go->transform.SetPosition(uInt(rnd), uInt(rnd), uInt(rnd));
		gameobjects.push_back(go);
	}
	if(GetAsyncKeyState(VK_SUBTRACT)){
		if(gameobjects.size() > 0){
			delete gameobjects.back();
			gameobjects.pop_back();
		}
	}

	float speed = 10.0f;
	if(GetAsyncKeyState('W'))
		Camera::MainCamera.transform.Move(0, speed * dt, 0);
	if(GetAsyncKeyState('S'))
		Camera::MainCamera.transform.Move(0, -speed * dt, 0);
	if(GetAsyncKeyState('A'))
		Camera::MainCamera.transform.Move(-speed * dt, 0, 0);
	if(GetAsyncKeyState('D'))
		Camera::MainCamera.transform.Move(speed * dt, 0, 0);

	Camera::MainCamera.Update(dt);

	for(UINT i = 0; i < gameobjects.size(); i++){
		gameobjects[i]->Update(dt);
	}
}
Example #2
0
void STBaselineTable::appendbasedata(int scanno, int cycleno, 
				     int beamno, int ifno, int polno, 
				     int freqid, Double time)
{
  uInt irow = nrow();
  table_.addRow(1, True);
  setbasedata(irow, uInt(scanno), uInt(cycleno), uInt(beamno), uInt(ifno), uInt(polno), uInt(freqid), time);
}
Example #3
0
void STBaselineTable::appenddata(int scanno, int cycleno, 
				 int beamno, int ifno, int polno, 
				 int freqid, Double time, 
				 bool apply, 
				 STBaselineFunc::FuncName ftype, 
				 vector<int> fpar, 
				 vector<float> ffpar, 
				 Vector<uInt> mask,
				 vector<float> res,
				 float rms,
				 int nchan, 
				 float cthres,
				 int citer, 
				 float lfthres, 
				 int lfavg, 
				 vector<int> lfedge)
{
  Vector<Int> fparam(fpar.size());
  for (uInt i = 0; i < fpar.size(); ++i) {
    fparam[i] = fpar[i];
  }
  Vector<uInt> edge(lfedge.size());
  for (uInt i = 0; i < lfedge.size(); ++i) {
    edge[i] = lfedge[i];
  }
  appenddata(uInt(scanno), uInt(cycleno), uInt(beamno), 
	     uInt(ifno), uInt(polno), uInt(freqid), time,
	     Bool(apply), ftype, fparam, Vector<Float>(ffpar), 
	     mask, Vector<Float>(res), Float(rms), uInt(nchan), 
	     Float(cthres), uInt(citer), 
	     Float(lfthres), uInt(lfavg), edge);
}
Example #4
0
/*static*/ status_t
ZlibDecompressor::DecompressSingleBuffer(const void* input, size_t inputSize,
	void* output, size_t outputSize, size_t& _uncompressedSize)
{
	if (inputSize == 0 || outputSize == 0)
		return B_BAD_VALUE;

	// prepare stream
	z_stream zStream = {
		(Bytef*)input,				// next_in
		uInt(inputSize),			// avail_in
		0,							// total_in
		(Bytef*)output,				// next_out
		uInt(outputSize),			// avail_out
		0,							// total_out
		0,							// msg
		0,							// state;
		Z_NULL,						// zalloc
		Z_NULL,						// zfree
		Z_NULL,						// opaque
		0,							// data_type
		0,							// adler
		0							// reserved
	};

	int zlibError = inflateInit(&zStream);
	if (zlibError != Z_OK)
		return TranslateZlibError(zlibError);


	// inflate
	status_t error = B_OK;
	zlibError = inflate(&zStream, Z_FINISH);
	if (zlibError != Z_STREAM_END) {
		if (zlibError == Z_OK)
			error = B_BUFFER_OVERFLOW;
		else
			error = TranslateZlibError(zlibError);
	}

	// clean up
	zlibError = inflateEnd(&zStream);
	if (zlibError != Z_OK && error == B_OK)
		error = TranslateZlibError(zlibError);

	if (error != B_OK)
		return error;

	_uncompressedSize = zStream.total_out;
	return B_OK;
}
Example #5
0
/***
uInt STMolecules::addEntry( Double restfreq, const String& name,
                            const String& formattedname )
{

  Table result =
    table_( near(table_.col("RESTFREQUENCY"), restfreq) );
  uInt resultid = 0;
  if ( result.nrow() > 0) {
    ROScalarColumn<uInt> c(result, "ID");
    c.get(0, resultid);
  } else {
    uInt rno = table_.nrow();
    table_.addRow();
    // get last assigned _id and increment
    if ( rno > 0 ) {
      idCol_.get(rno-1, resultid);
      resultid++;
    }
    restfreqCol_.put(rno, restfreq);
    nameCol_.put(rno, name);
    formattednameCol_.put(rno, formattedname);
    idCol_.put(rno, resultid);
  }
  return resultid;
}
***/
uInt STMolecules::addEntry( Vector<Double> restfreq, const Vector<String>& name,
                            const Vector<String>& formattedname )
{
// How to handle this...?
  Table result =
    table_( nelements(table_.col("RESTFREQUENCY")) == uInt (restfreq.size()) && 
            all(table_.col("RESTFREQUENCY")== restfreq), 1 );
  uInt resultid = 0;
  if ( result.nrow() > 0) {
    ROScalarColumn<uInt> c(result, "ID");
    c.get(0, resultid);
  } else {
    uInt rno = table_.nrow();
    table_.addRow();
    // get last assigned _id and increment
    if ( rno > 0 ) {
      idCol_.get(rno-1, resultid);
      resultid++;
    }
    restfreqCol_.put(rno, restfreq);
    nameCol_.put(rno, name);
    formattednameCol_.put(rno, formattedname);
    idCol_.put(rno, resultid);
  }
  return resultid;
}
Example #6
0
void FillerBase::setTcal2(const String& tcaltime,
                          const Vector<Float>& tcal)
{
  uInt id = 0 ;
  Table tab = table_->tcal().table() ;
  Table result =
    //tab( nelements(tab.col("TCAL")) == uInt (tcal.size()) && 
    //     all(tab.col("TCAL")== tcal) &&
    //     tab.col("TIME") == tcaltime, 1 ) ;
    tab( nelements(tab.col("TCAL")) == uInt (tcal.size()) && 
         all(tab.col("TCAL")== tcal), 1 ) ;

  if ( result.nrow() > 0 ) {
    ROTableColumn tmpCol( result, "ID" ) ;
    tmpCol.getScalar( 0, id ) ;
  }
  else {
    uInt rno = tab.nrow();
    tab.addRow();
    TableColumn idCol( tab, "ID" ) ;
    TableColumn tctimeCol( tab, "TIME" ) ;
    ArrayColumn<Float> tcalCol( tab, "TCAL" ) ;
    // get last assigned _id and increment
    if ( rno > 0 ) {
      idCol.getScalar(rno-1, id);
      id++;
    }
    tctimeCol.putScalar(rno, tcaltime);
    tcalCol.put(rno, tcal);
    idCol.putScalar(rno, id);
  }

  RecordFieldPtr<uInt> mcalidCol(row_.record(), "TCAL_ID");
  *mcalidCol = id;
}
std::string compress(const std::string &raw) {
    z_stream deflate_stream;
    memset(&deflate_stream, 0, sizeof(deflate_stream));

    // TODO: reuse z_streams
    if (deflateInit(&deflate_stream, Z_DEFAULT_COMPRESSION) != Z_OK) {
        throw std::runtime_error("failed to initialize deflate");
    }

    deflate_stream.next_in = (Bytef *)raw.data();
    deflate_stream.avail_in = uInt(raw.size());

    std::string result;
    char out[16384];

    int code;
    do {
        deflate_stream.next_out = reinterpret_cast<Bytef *>(out);
        deflate_stream.avail_out = sizeof(out);
        code = deflate(&deflate_stream, Z_FINISH);
        if (result.size() < deflate_stream.total_out) {
            // append the block to the output string
            result.append(out, deflate_stream.total_out - result.size());
        }
    } while (code == Z_OK);

    deflateEnd(&deflate_stream);

    if (code != Z_STREAM_END) {
        throw std::runtime_error(deflate_stream.msg);
    }

    return result;
}
std::string decompress(const std::string &raw) {
    z_stream inflate_stream;
    memset(&inflate_stream, 0, sizeof(inflate_stream));

    // TODO: reuse z_streams
    if (inflateInit(&inflate_stream) != Z_OK) {
        throw std::runtime_error("failed to initialize inflate");
    }

    inflate_stream.next_in = (Bytef *)raw.data();
    inflate_stream.avail_in = uInt(raw.size());

    std::string result;
    char out[15384];

    int code;
    do {
        inflate_stream.next_out = reinterpret_cast<Bytef *>(out);
        inflate_stream.avail_out = sizeof(out);
        code = inflate(&inflate_stream, 0);
        // result.append(out, sizeof(out) - inflate_stream.avail_out);
        if (result.size() < inflate_stream.total_out) {
            result.append(out, inflate_stream.total_out - result.size());
        }
    } while (code == Z_OK);

    inflateEnd(&inflate_stream);

    if (code != Z_STREAM_END) {
        throw std::runtime_error(inflate_stream.msg ? inflate_stream.msg : "decompression error");
    }

    return result;
}
Example #9
0
			void new_buffer_(){
				if (map_dest){
					wview = map_dest->view_wr(ext_heap::handle(zstream.total_out, zstream.total_out + K_CompressedViewSize));
					if (wview.get<io::write_view>().address().size() != K_CompressedViewSize)
						AIO_THROW(deflate_exception)("Failed to request write view");

					auto addr  = wview.get<io::write_view>().address();
					zstream.next_out = (Bytef*)addr.begin();
					zstream.avail_out = uInt(addr.size());
				}
				else{
					crc = crc32(to_range(buf), crc);
					stream_dest->write(to_range(buf));
					buf.resize(K_CompressedViewSize);
					zstream.next_out = (Bytef*)buf.begin();
					zstream.avail_out = uInt(buf.size());
				}
			}
Example #10
0
//----------------------------------------------------------------------
void FFileDialog::printPath (const FString& txt)
{
  const auto& path = txt;
  const uInt max_width = uInt(filebrowser.getWidth()) - 4;

  if ( path.getLength() > max_width )
    filebrowser.setText(".." + path.right(max_width - 2));
  else
    filebrowser.setText(path);
}
Example #11
0
			void new_input_(){
				if (map_src){
					long_size_t rest_in_size = map_src->size() - zstream.total_in;
					if (rest_in_size > 0){
						typedef ext_heap::handle handle;
						handle hin(zstream.total_in,  zstream.total_in + std::min(K_UncompressedViewSize, rest_in_size));
						rview = map_src->view_rd(hin);
						auto bin = rview.get<io::read_view>().address();
						zstream.avail_in = uInt(bin.size());
						zstream.next_in = (Bytef*)bin.begin();
						crc = crc32(bin, crc);
					}
				}
				else if(stream_src->readable()){
					buf.resize(K_UncompressedViewSize);
					auto res = stream_src->read(to_range(buf));
					buf.resize(buf.size() - res.size());
					zstream.avail_in = uInt(buf.size());
					zstream.next_in = (Bytef*)buf.begin();
				}
			}
Example #12
0
void STBaselineTable::setdata(uInt irow, uInt scanno, uInt cycleno, 
			      uInt beamno, uInt ifno, uInt polno, 
			      uInt freqid, Double time, 
			      Bool apply, 
			      STBaselineFunc::FuncName ftype, 
			      Vector<Int> fpar, 
			      Vector<Float> ffpar, 
			      Vector<uInt> mask,
			      Vector<Float> res,
			      Float rms, 
			      uInt nchan, 
			      Float cthres,
			      uInt citer, 
			      Float lfthres, 
			      uInt lfavg, 
			      Vector<uInt> lfedge)
{
  if (irow >= (uInt)nrow()) {
    //throw AipsError("row index out of range");
    stringstream ss;
    ss << "row index out of range[irow=" << irow << "][nrow=" << nrow() << "]";
    throw AipsError(ss.str());
  }

  if (!sel_.empty()) {
    os_.origin(LogOrigin("STBaselineTable","setdata",WHERE));
    os_ << LogIO::WARN << "Data selection is effective. Specified row index may be wrong." << LogIO::POST;
  }  

  setbasedata(irow, scanno, cycleno, beamno, ifno, polno, freqid, time);
  applyCol_.put(irow, apply);
  ftypeCol_.put(irow, uInt(ftype));
  fparCol_.put(irow, fpar);
  ffparCol_.put(irow, ffpar);
  maskCol_.put(irow, mask);
  resCol_.put(irow, res);
  rmsCol_.put(irow, rms);
  nchanCol_.put(irow, nchan);
  cthresCol_.put(irow, cthres);
  citerCol_.put(irow, citer);
  lfthresCol_.put(irow, lfthres);
  lfavgCol_.put(irow, lfavg);
  lfedgeCol_.put(irow, lfedge);
}
Example #13
0
			range<const byte*> write(const range<const byte*>& buf){
				AIO_PRE_CONDITION(!finished);
				AIO_PRE_CONDITION(zstream.avail_in == 0);
				crc = crc32(buf, crc);
				zstream.next_in = (Bytef*)buf.begin();
				zstream.avail_in = uInt(buf.size());

				for(;zstream.avail_in != 0;){
					if (zstream.avail_out ==0 )
						new_buffer_();

					switch (deflate(&zstream, Z_NO_FLUSH)){
						case Z_OK:
						case Z_BUF_ERROR:
							break;
						default:
							AIO_THROW(deflate_exception)("deflate with Z_NO_FLUSH failed");
					}
				}
				return range<const byte*>(buf.end(), buf.end());
			}
Example #14
0
			range<byte*> read(const range<byte*>& buf)
			{
				zstream.avail_out = uInt(buf.size());
				zstream.next_out = (Bytef*)buf.begin();

				for(;zstream.avail_out != 0;){
					if (zstream.avail_in == 0){
						new_input_();
					}

					auto res = ::inflate(&zstream, Z_NO_FLUSH);
					switch(res)
					{
						case Z_NEED_DICT:
							{
								if (dict.empty())
									AIO_THROW(inflate_exception)("Need dictionary");
								auto dic_err = inflateSetDictionary(&zstream, (Bytef*)dict.begin(), dict.size());
								if (dic_err != Z_OK)
									AIO_THROW(inflate_exception)("Bad dictionary");
							}
						case Z_OK:
							break;
						case Z_DATA_ERROR:
							AIO_THROW(inflate_exception)("Z_DATA_ERROR");
						case Z_MEM_ERROR:
							AIO_THROW(inflate_exception)("Z_MEM_ERROR");
						case Z_STREAM_END:
							uncompressed_size = zstream.total_out;
							return range<byte*>((buf.size() - zstream.avail_out) + buf.begin(), buf.end());
						default:
							AIO_THROW(inflate_exception)("zlib internal error");
					}
				}
				return range<byte*>(buf.end() - zstream.avail_out, buf.end());
			}
Example #15
0
	inline void set_out(zstream_handle stream, char * out_first, std::size_t out_size)
	{
		stream->next_out = reinterpret_cast<unsigned char *>(out_first);
		stream->avail_out = uInt(out_size);
	}
Example #16
0
	inline void set_in(zstream_handle stream, const char * in_first, std::size_t in_size)
	{
		//stream->next_in = reinterpret_cast<const unsigned char *>(in_first);
		stream->next_in = (unsigned char *)in_first;
		stream->avail_in = uInt(in_size);
	}
void BeamColumnJoint3d::getGlobalDispls(Vector &dg) 
{
	// local variables that will be used in this method
	int converge = 0;
	int linesearch = 0;
	int totalCount = 0;
	int dtConverge = 0;
	int incCount = 0;
	int count = 0;
	int maxTotalCount = 1000;
	int maxCount = 20;
	double loadStep = 0.0;
	double dLoadStep = 1.0;
	double stepSize;

	Vector uExtOld(24);       uExtOld.Zero();
	Vector uExt(12);          uExt.Zero();
	Vector duExt(12);         duExt.Zero();
	Vector uIntOld(4);        uIntOld.Zero();
	Vector uInt(4);           uInt.Zero();
	Vector duInt(4);          duInt.Zero();
	Vector duIntTemp(4);      duIntTemp.Zero();
	Vector intEq(4);          intEq.Zero();
	Vector intEqLast(4);      intEqLast.Zero();
	Vector Uepr(24);          Uepr.Zero();
	Vector UeprInt(4);        UeprInt.Zero();
	Vector Ut(24);            Ut.Zero();
	Vector duExtTemp(24);     duExtTemp.Zero();

    Vector disp1 = nodePtr[0]->getTrialDisp(); 
    Vector disp2 = nodePtr[1]->getTrialDisp();
    Vector disp3 = nodePtr[2]->getTrialDisp();
    Vector disp4 = nodePtr[3]->getTrialDisp();

	for (int i = 0; i < 6; i++)
    {
      Ut(i)     = disp1(i);
      Ut(i+6)   = disp2(i);
      Ut(i+12)   = disp3(i);
      Ut(i+18)   = disp4(i);
    }
	
	Uepr = Uecommit;   

	UeprInt = UeIntcommit;  

	uExtOld = Uepr;

	duExtTemp = Ut - Uepr;
	duExt.addMatrixVector(0.0,Transf,duExtTemp,1.0);
	uExt.addMatrixVector(0.0,Transf,uExtOld,1.0);  

	uIntOld = UeprInt;
	uInt = uIntOld;

	double tol = 1e-12;
	double tolIntEq = tol;
	double toluInt = (tol>tol*uInt.Norm())? tol:tol*uInt.Norm();
	double tolIntEqdU = tol;
	double ctolIntEqdU = tol;
	double ctolIntEq = tol;
	double normDuInt = toluInt;
	double normIntEq = tolIntEq;
	double normIntEqdU = tolIntEqdU;
	    
	Vector u(16);   u.Zero();

	double engrLast = 0.0;
	double engr = 0.0;

	Vector fSpring(13);          fSpring.Zero();
	Vector kSpring(13);          kSpring.Zero();
	Matrix dintEq_du(4,4);       dintEq_du.Zero();
	Matrix df_dDef(13,13);       df_dDef.Zero();
	Matrix tempintEq_du (4,13);  tempintEq_du.Zero();


	while ((loadStep < 1.0) && (totalCount < maxTotalCount))
	{
		count = 0;
		converge = 0;
		dtConverge = 0;
		while ((!converge) && (count < maxCount))
		{
			if (dLoadStep <= 1e-3)
			{
				dLoadStep = dLoadStep;
			}
			totalCount ++;
			count ++;
			
			for (int ic = 0; ic < 12; ic++ ) {
				u(ic) = uExt(ic) + duExt(ic);
			}
			u(12) = uInt(0);
			u(13) = uInt(1);
			u(14) = uInt(2);
			u(15) = uInt(3);

			getMatResponse(u,fSpring,kSpring);
		

		// performs internal equilibrium 

		intEq(0) = -fSpring(2)-fSpring(3)+fSpring(9)-fSpring(12)/elemHeight; 
		intEq(1) = fSpring(1)-fSpring(5)-fSpring(7)+fSpring(12)/elemWidth; 
		intEq(2) = -fSpring(4)-fSpring(8)+fSpring(10)+fSpring(12)/elemHeight; 
		intEq(3) = fSpring(0)-fSpring(6)-fSpring(11)-fSpring(12)/elemWidth; 

		matDiag(kSpring, df_dDef);

		//////////////////////// dintEq_du = dg_df*df_dDef*dDef_du
		tempintEq_du.addMatrixProduct(0.0,dg_df,df_dDef,1.0);
		dintEq_du.addMatrixProduct(0.0,tempintEq_du,dDef_du,1.0);
		normIntEq = intEq.Norm();
		normIntEqdU = 0.0;
		for (int jc = 0; jc<4 ; jc++)
		{
			normIntEqdU += intEq(jc)*duInt(jc);
		}
		normIntEqdU = fabs(normIntEqdU);

		if (totalCount == 1)
		{
			tolIntEq = (tol>tol*normIntEq) ? tol:tol*normIntEq;
			tolIntEqdU = tol;
		}
		else if (totalCount == 2)
		{
			tolIntEqdU = (tol>tol*normIntEqdU) ? tol:tol*normIntEqdU;
		}
		ctolIntEqdU = (tolIntEqdU*dLoadStep > tol) ? tolIntEqdU*dLoadStep:tol;
		ctolIntEq   = (tolIntEq*dLoadStep > tol) ? tolIntEq*dLoadStep:tol;

		// check for convergence starts  
		if ((normIntEq < tol) || ((normIntEqdU < tol) && (count >1)) || (normDuInt < toluInt) || (dLoadStep < 1e-3))
		{
		  	if ((normIntEq > ctolIntEq) || (normIntEqdU > tolIntEqdU) || (normDuInt > toluInt))
			{
				dtConverge = 1;
			}
			else
			{
				dtConverge = 0;
			}

			converge = 1;
			loadStep = loadStep + dLoadStep;
			if (fabs(1.0 - loadStep) < tol)
			{
				loadStep = 1.0;
			}
		}
		else
		{
			////////////// duInt = -dintEq_du/intEq
			dintEq_du.Solve(intEq,duInt);
			duInt *= -1;
			
			normDuInt = duInt.Norm();
			if (!linesearch)
			{
				uInt = uInt + duInt;
			}
			else
			{
				engrLast = 0.0;
				engr = 0.0;

				for (int jd = 0; jd<4 ; jd++)
				{
					engrLast += duInt(jd)*intEqLast(jd);
					engr += duInt(jd)*intEq(jd);
				}

				if (fabs(engr) > tol*engrLast)
				{
					duIntTemp = duInt;
					duIntTemp *= -1;
					// lineSearch algorithm requirement
					stepSize = getStepSize(engrLast,engr,uExt,duExt,uInt,duIntTemp,tol);
					
					if (fabs(stepSize) > 0.001)
					{
						uInt = uInt + stepSize*duInt;
					}
					else
					{
						uInt = uInt + duInt;
					}
				}
				else
				{
					uInt = uInt + duInt;
				}
				intEqLast = intEq;
			}
		}
	}

		if (!converge && loadStep < 1.0)
		{	
			incCount = 0;
			maxCount = 25;
			if (!linesearch)
			{
				linesearch = 1;
				uInt = uIntOld;
				duInt.Zero();
			}
			else
			{
				opserr << "WARNING : BeamColumnJoint::getGlobalDispls() - convergence problem in state determination" << endln;

				uInt = uIntOld;
				duInt.Zero();
				duExt = duExt*0.1;

				dLoadStep = dLoadStep*0.1;
			}
		}
		else if (loadStep < 1.0)
		{
			maxCount = 10;
			incCount ++;
			normDuInt = toluInt;
			if ((incCount < maxCount) || dtConverge)
			{
				uExt = uExt + duExt;
				if (loadStep + dLoadStep > 1.0)
				{
					duExt = duExt*(1.0 - loadStep)/dLoadStep;
					dLoadStep = 1.0 - loadStep;
					incCount = 9;
				}
			}
			else
			{
				incCount = 0;
				uExt = uExt + duExt;
				dLoadStep = dLoadStep*10;
				if (loadStep + dLoadStep > 1.0)
				{
					uExt = uExt + duExt*(1.0 - loadStep)/dLoadStep;
					dLoadStep = 1.0 - loadStep;
					incCount = 9;
				}
			}
		}
	}


	// determination of stiffness matrix and the residual force vector for the element

	formR(fSpring);

	formK(kSpring);

	for (int ig = 0; ig < 25; ig++ ) {
		if (ig<24)
		{
			dg(ig) = Ut(ig);
		}
	}


	dg(24) = uInt(0);
	dg(25) = uInt(1);
	dg(26) = uInt(2);
	dg(27) = uInt(3);

}
Example #18
0
void STBaselineTable::setApply(int irow, bool apply)
{
  applyCol_.put(uInt(irow), Bool(apply));
}
Example #19
0
			void init_(zip_format format, int level_, dict_type dict_, heap* h, int strategy_){
				if (h){
					zstream.zalloc = zip_malloc;
					zstream.zfree = zip_free;
					zstream.opaque = h;
				}
				if(deflateInit2(&zstream, level_, Z_DEFLATED, get_winbits(format, MAX_WBITS), MAX_MEM_LEVEL, strategy_) != Z_OK)
					AIO_THROW(deflate_exception)("deflateInit2 failed");

				if (!dict_.empty() && (deflateSetDictionary(&zstream, (const Bytef*)dict_.begin(), uInt(dict_.size())) != Z_OK))
					AIO_THROW(deflate_exception)("deflateSetDictionary failed");
			}
Example #20
0
bool Database::genDatabase(const std::string path_src, const std::string path_dest, const string movieDatabase, const string userDatabase)
{
    
    DIR *dp;
    struct dirent *fp;
    std::vector<std::string> fnames;
    if ((dp = opendir(path_src.c_str())) != NULL) {
        while ((fp = readdir(dp)) != NULL) {
            if(string(fp->d_name).find(".txt") != std::string::npos)
            {
                fnames.push_back(string(fp->d_name));
            }
        }
        closedir(dp);
    }
    
    if((dp = opendir(path_dest.c_str())) == NULL){
        if(mkdir(path_dest.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
        {
            cout << "mkdir failed!" << endl;
            return false;
        }
    }
    
    
    //for(vector<string>::iterator it = fnames.begin(); it != fnames.end(); ++ it)
    //    cout << *it << endl;
    //cout << fnames.size() << std::endl;
    //cout << "In Database" << endl;
    
    //remove files
    if(remove((path_dest + movieDatabase).c_str()) == 0)
        cout << "Remove " << movieDatabase << endl;
    if(remove((path_dest + userDatabase).c_str()) == 0)
        cout << "Remove " << userDatabase << endl;
    
    vector<mRatings> mRs;
    UserRatings *users = new UserRatings();
    
    //generate movie dataset
    for(vector<string>::iterator it = fnames.begin(); it != fnames.end(); ++ it)
    {
        ifstream myFile((path_src + *it).c_str());
        string line;
        int movieId;
        if(myFile.is_open())
        {
            getline(myFile, line);
            movieId = strToInt(line.substr(0, line.find(':') - 0));
            cout << "MovieID " << movieId << endl;
            while(getline(myFile, line))
            {
                //int start = 0;
                //cout << line.substr(start, line.find(',') - start) << " " << line.substr(line.find(',') + 1, line.find_last_of(',') - line.find(',') - 1) << endl;
                uInt uId = strToInt(line.substr(0, line.find(',') - 0));
                uByte rating = uByte(strToInt(line.substr(line.find(',') + 1, line.find_last_of(',') - line.find(',') - 1)));
                mRatings mRat = mRatings(uId, rating);
                int index = binarySearch<mRatings>(mRs, mRat);
                insert<mRatings>(mRs, mRat, index);
                //initilize user vectors
                users->addRating(mRs.back().getId(), uRatings(movieId, mRs.back().getValue()));
            }
            myFile.close();
            
            //generate user database
            ofstream movieWFile((path_dest + movieDatabase).c_str(), ios::out|ios::binary|ios::app);
            if(movieWFile.good())
            {
                if(movieWFile.is_open())
                {
                    unsigned short uIdHi = 0;
                    uByte rating = 0;
                    uInt size = int(mRs.size());
                    movieWFile.write((char *)&size, sizeof(uInt));
                    cout << size << endl;
                    for(vector<mRatings>::iterator it = mRs.begin(); it != mRs.end(); ++ it)
                    {
                        uIdHi = it->userIdHi;
                        rating = ((it->userIdLo) << 4) + uByte(it->value);
                        movieWFile.write((char *)&uIdHi, sizeof(unsigned short));
                        movieWFile.write((char *)&rating, sizeof(uByte));
                        cout << it->getId() << " " << it->getValue() << endl;
                    }
                }
                mRs.clear();
                movieWFile.close();
            }
            else
            {
                cout << "Failed!" << endl;
            }
        }
    }
    
    //generate user dataset
    ofstream userFile((path_dest + userDatabase).c_str(), ios::out|ios::binary|ios::ate);
    vector<uRatings> uRs;
    for(uInt i = 1; i <= users->getUserNum(); i ++)
    {
        uRs.clear();
        users->getRatings(i, uRs);
        if(userFile.good())
        {
            if(userFile.is_open())
            {
                unsigned short mId = 0;
                uByte rating = 0;
                uInt num = uInt(uRs.size());
                userFile.write((char* )&num, sizeof(unsigned int));
                for(vector<uRatings>::iterator it = uRs.begin(); it != uRs.end(); ++ it)
                {
                    mId = it->movieId;
                    rating = it->value;
                    userFile.write((char *)&mId, sizeof(unsigned short));
                    userFile.write((char *)&rating, sizeof(uByte));
                }
            }
        }
    }
    userFile.close();
    return true;
}
Example #21
0
bool Database::genProbeDatabase(const string path_src, const string path_dest, const string probeDatabase)
{
    ifstream probeFile(path_src.c_str());

    string line;
    unsigned short movieId = 0;
    vector<mRatings> pRs;
    
    ProbeRatings probes;
    //bool firstTime = true;
    
    if(probeFile.good())
    {
        cout << "Read Original Probe File" << endl;
        if(probeFile.is_open())
        {
            while(getline(probeFile, line))
            {
                if(!(line.find(':') == string::npos))
                {
                    if(pRs.size() != 0)
                        probes.addRatings(movieId, pRs);
                  
                    movieId = strToInt(line.substr(0, line.find(':') - 0));
                    pRs.clear();
                }
                else
                {
                    //int start = 0;
                    //cout << line.substr(start, line.find(',') - start) << " " << line.substr(line.find(',') + 1, line.find_last_of(',') - line.find(',') - 1) << endl;
                    
                    uInt uId = strToInt(line.substr(0, line.find(',') - 0));
                    uByte rating = uByte(strToInt(line.substr(line.find(',') + 1, line.find_last_of(',') - line.find(',') - 1)));
                    mRatings mRat = mRatings(uId, rating);
                    pRs.push_back(mRat);
                }
            }

        }
        //add the last one
        if(pRs.size() != 0)
            probes.addRatings(movieId, pRs);
        probeFile.close();
    }
    
    
    
    ofstream outFile((path_dest + probeDatabase).c_str(), ios::out|ios::binary|ios::app|ios::ate);
    if(outFile.good())
    {
        if(outFile.is_open())
        {
            cout << "size " << probes.getPredictedMovieNum() << endl;
            for(int i = 0; i < probes.getPredictedMovieNum(); i ++)
            {
                unsigned short uIdHi = 0;
                uByte rating = 0;
                unsigned short movieId = 0;
                
                vector<mRatings> mRsTemp;
                probes.getRatings(i, movieId, mRsTemp);
                uInt num = uInt(mRsTemp.size());
                if(num == 0)
                    break;
                outFile.write((char *)&movieId, sizeof(unsigned short));
                outFile.write((char *)&num, sizeof(uInt));
                
                for(vector<mRatings>::iterator it = mRsTemp.begin(); it != mRsTemp.end(); ++ it)
                {
                    uIdHi = it->userIdHi;
                    rating = (it->userIdLo << 4) + it->value;
                    outFile.write((char *)&uIdHi, sizeof(unsigned short));
                    outFile.write((char *)&rating, sizeof(uByte));
                }
            }
            outFile.close();
        }
    
    }
    
    return true;
}
Example #22
0
// Returns a random int between min and max, 
// default paramaters are INT_MIN and INT_MAX
int RNG::randInt(int min, int max){
	std::uniform_int_distribution<int> uInt(min, max);
	return uInt(rnd);
};