예제 #1
0
  Teuchos::RCP<CrsMatrixWrap> GenerateProblemMatrix(const Teuchos::RCP<const Map> map, Scalar a = 2.0, Scalar b = -1.0, Scalar c = -1.0) {
    Teuchos::RCP<CrsMatrixWrap> mtx = Galeri::Xpetra::MatrixTraits<Map,CrsMatrixWrap>::Build(map, 3);

    LocalOrdinal NumMyElements = map->getNodeNumElements();
    Teuchos::ArrayView<const GlobalOrdinal> MyGlobalElements = map->getNodeElementList();
    GlobalOrdinal NumGlobalElements = map->getGlobalNumElements();
    GlobalOrdinal nIndexBase = map->getIndexBase();

    GlobalOrdinal NumEntries;
    LocalOrdinal nnz=2;
    std::vector<Scalar> Values(nnz);
    std::vector<GlobalOrdinal> Indices(nnz);

    for (LocalOrdinal i = 0; i < NumMyElements; ++i)
    {
      if (MyGlobalElements[i] == nIndexBase)
      {
        // off-diagonal for first row
        Indices[0] = nIndexBase;
        NumEntries = 1;
        Values[0] = c;
      }
      else if (MyGlobalElements[i] == nIndexBase + NumGlobalElements - 1)
      {
        // off-diagonal for last row
        Indices[0] = nIndexBase + NumGlobalElements - 2;
        NumEntries = 1;
        Values[0] = b;
      }
      else
      {
        // off-diagonal for internal row
        Indices[0] = MyGlobalElements[i] - 1;
        Values[1] = b;
        Indices[1] = MyGlobalElements[i] + 1;
        Values[0] = c;
        NumEntries = 2;
      }

      // put the off-diagonal entries
      // Xpetra wants ArrayViews (sigh)
      Teuchos::ArrayView<Scalar> av(&Values[0],NumEntries);
      Teuchos::ArrayView<GlobalOrdinal> iv(&Indices[0],NumEntries);
      mtx->insertGlobalValues(MyGlobalElements[i], iv, av);

      // Put in the diagonal entry
      mtx->insertGlobalValues(MyGlobalElements[i],
          Teuchos::tuple<GlobalOrdinal>(MyGlobalElements[i]),
          Teuchos::tuple<Scalar>(a) );

    } //for (LocalOrdinal i = 0; i < NumMyElements; ++i)


    mtx->fillComplete(map,map);

    return mtx;
  }
예제 #2
0
/******************************************************************************
* Computes the largest time interval containing the given time during which the
* controller's value is constant.
******************************************************************************/
TimeInterval LookAtController::validityInterval(TimePoint time)
{
	TimeInterval iv(TimeInterval::infinite());
	if(rollController())
		iv.intersect(rollController()->validityInterval(time));
	if(targetNode())
		targetNode()->getWorldTransform(time, iv);
	return iv;
}
예제 #3
0
TEST_F(test_dvector, cast_ivector)
{
  dvector dv(1, 4);
  dv(1) = INT_MIN;
  dv(2) = INT_MIN/2;
  dv(3) = INT_MAX/2;
  dv(4) = INT_MAX;

  ivector iv(1, 2);
  iv(1) = 3;
  iv(2) = 1;

  dvector ret = dv(iv);
  EXPECT_EQ(iv.indexmin(), ret.indexmin());
  EXPECT_EQ(iv.indexmax(), ret.indexmax());
  EXPECT_DOUBLE_EQ(dv((int)iv(1)), ret(1));
  EXPECT_DOUBLE_EQ(dv((int)iv(2)), ret(2));
}
    Teuchos::RCP<Matrix>
    TriDiag_Helmholtz(const Teuchos::RCP<const Map> & map, const GlobalOrdinal nx,
                      const double h, const double omega, const Scalar shift) {

      Teuchos::RCP<Matrix> mtx = MatrixTraits<Map,Matrix>::Build(map, 3);
      LocalOrdinal NumMyElements = map->getNodeNumElements();
      Teuchos::ArrayView<const GlobalOrdinal> MyGlobalElements = map->getNodeElementList();
      Teuchos::RCP<const Teuchos::Comm<int> > comm = map->getComm();
      GlobalOrdinal NumGlobalElements = map->getGlobalNumElements();
      GlobalOrdinal NumEntries;
      LocalOrdinal nnz=2;
      std::vector<Scalar> Values(nnz);
      std::vector<GlobalOrdinal> Indices(nnz);
      Scalar one = (Scalar) 1.0;
      Scalar two = (Scalar) 2.0;
      comm->barrier();
      Teuchos::RCP<Teuchos::Time> timer = rcp(new Teuchos::Time("TriDiag global insert"));
      timer->start(true);
      for (LocalOrdinal i = 0; i < NumMyElements; ++i) {
        if (MyGlobalElements[i] == 0) {
          // off-diagonal for first row
          Indices[0] = 1;
          NumEntries = 1;
          Values[0] = -one;
        }
        else if (MyGlobalElements[i] == NumGlobalElements - 1) {
          // off-diagonal for last row
          Indices[0] = NumGlobalElements - 2;
          NumEntries = 1;
          Values[0] = -one;
        }
        else {
          // off-diagonal for internal row
          Indices[0] = MyGlobalElements[i] - 1;
          Indices[1] = MyGlobalElements[i] + 1;
          Values[0] = -one;
          Values[1] = -one;
          NumEntries = 2;
        }
        // put the off-diagonal entries
        // Xpetra wants ArrayViews (sigh)
        Teuchos::ArrayView<Scalar> av(&Values[0],NumEntries);
        Teuchos::ArrayView<GlobalOrdinal> iv(&Indices[0],NumEntries);
        mtx->insertGlobalValues(MyGlobalElements[i], iv, av);
        // Put in the diagonal entry
        mtx->insertGlobalValues(MyGlobalElements[i],
                                Teuchos::tuple<GlobalOrdinal>(MyGlobalElements[i]),
                                Teuchos::tuple<Scalar>(two-shift*omega*omega*h*h) );
      }
      timer->stop();
      timer = rcp(new Teuchos::Time("TriDiag fillComplete"));
      timer->start(true);
      mtx->fillComplete();
      timer->stop();
      return mtx;

    } //TriDiag_Helmholtz
예제 #5
0
파일: ludcmp.hpp 프로젝트: pwoo/admb
 cltudecomp_for_adjoint(int lb, int ub, int n, int m):indx(lb, ub),
     dfclu(lb, ub), pMpos(0)
 {
     ivector iv(lb + 1, ub);
     iv.fill_seqadd(lb, 1);
     L.allocate(lb + 1, ub, lb, iv, 1, n);
     ivector iv1(lb, ub);
     iv1.fill_seqadd(lb, 1);
     U.allocate(lb, ub, lb, iv1, 1, m);
 }
예제 #6
0
파일: ludcmp.hpp 프로젝트: pwoo/admb
 cltudecomp(int lb, int ub):indx(lb, ub), indx2(lb, ub)
 {
     ivector iv(lb + 1, ub);
     iv.fill_seqadd(lb, 1);
     L.allocate(lb + 1, ub, lb, iv);
     ivector iv1(lb, ub);
     iv1.fill_seqadd(lb, 1);
     U.allocate(lb, ub, lb, iv1);
     indx2.fill_seqadd(lb, 1);
 }
GMPErr
ClearKeyDecryptor::Decrypt(uint8_t* aBuffer, uint32_t aBufferSize,
                           const GMPEncryptedBufferMetadata* aMetadata)
{
  CK_LOGD("ClearKeyDecryptor::Decrypt");
  // If the sample is split up into multiple encrypted subsamples, we need to
  // stitch them into one continuous buffer for decryption.
  std::vector<uint8_t> tmp(aBufferSize);

  if (aMetadata->NumSubsamples()) {
    // Take all encrypted parts of subsamples and stitch them into one
    // continuous encrypted buffer.
    unsigned char* data = aBuffer;
    unsigned char* iter = &tmp[0];
    for (size_t i = 0; i < aMetadata->NumSubsamples(); i++) {
      data += aMetadata->ClearBytes()[i];
      uint32_t cipherBytes = aMetadata->CipherBytes()[i];

      memcpy(iter, data, cipherBytes);

      data += cipherBytes;
      iter += cipherBytes;
    }

    tmp.resize((size_t)(iter - &tmp[0]));
  } else {
    memcpy(&tmp[0], aBuffer, aBufferSize);
  }

  MOZ_ASSERT(aMetadata->IVSize() == 8 || aMetadata->IVSize() == 16);
  std::vector<uint8_t> iv(aMetadata->IV(), aMetadata->IV() + aMetadata->IVSize());
  iv.insert(iv.end(), CLEARKEY_KEY_LEN - aMetadata->IVSize(), 0);

  ClearKeyUtils::DecryptAES(mKey, tmp, iv);

  if (aMetadata->NumSubsamples()) {
    // Take the decrypted buffer, split up into subsamples, and insert those
    // subsamples back into their original position in the original buffer.
    unsigned char* data = aBuffer;
    unsigned char* iter = &tmp[0];
    for (size_t i = 0; i < aMetadata->NumSubsamples(); i++) {
      data += aMetadata->ClearBytes()[i];
      uint32_t cipherBytes = aMetadata->CipherBytes()[i];

      memcpy(data, iter, cipherBytes);

      data += cipherBytes;
      iter += cipherBytes;
    }
  } else {
    memcpy(aBuffer, &tmp[0], aBufferSize);
  }

  return GMPNoErr;
}
예제 #8
0
  bool AppWindow::
  rfctDraw()
  {
    for (View::registry_t::vector_t::const_iterator iv(View::registry.vector_.begin());
	 iv != View::registry.vector_.end(); ++iv) {
      if ( !(*iv)->rfctDraw()) {
	return false;
      }
    }
    return true;
  }
예제 #9
0
파일: paranoia.c 프로젝트: suborb/reelvdr
static inline long int 
try_sort_sync(cdrom_paranoia_t *p,
	      sort_info_t *A, unsigned char *Aflags,
	      c_block_t *B,
	      long int post,
	      long int *begin,
	      long int *end,
	      long *offset,
	      void (*callback)(long int, paranoia_cb_mode_t))
{
  
  long dynoverlap=p->dynoverlap;
  sort_link *ptr=NULL;
  unsigned char *Bflags=B->flags;

  /* block flag matches 0x02 (unmatchable) */
  if(Bflags==NULL || (Bflags[post-cb(B)]&2)==0){
    /* always try absolute offset zero first! */
    {
      long zeropos=post-ib(A);
      if (zeropos>=0 && zeropos<is(A)) {
	if ( cv(B)[post-cb(B)] == iv(A)[zeropos] ) {
	  if (do_const_sync(B, A, Aflags,
			    post-cb(B), zeropos,
			    begin, end, offset) ) {
	    
	    offset_add_value(p,&(p->stage1),*offset,callback);
	    
	    return(1);
	  }
	}
      }
    }
  } else
    return(0);
  
  ptr=sort_getmatch(A,post-ib(A),dynoverlap,cv(B)[post-cb(B)]);
  
  while(ptr){
    
    if(do_const_sync(B,A,Aflags,
		     post-cb(B),ipos(A,ptr),
		     begin,end,offset)){
      offset_add_value(p,&(p->stage1),*offset,callback);
      return(1);
    }
    ptr=sort_nextmatch(A,ptr);
  }
  
  *begin=-1;
  *end=-1;
  *offset=-1;
  return(0);
}
예제 #10
0
    // Perform a pick operation.
    bool pick( const double x, const double y,
            osgViewer::Viewer* viewer )
    {
        if (!viewer->getSceneData())
            // Nothing to pick.
            return false;

        double w( .05 ), h( .05 );
        osgUtil::PolytopeIntersector* picker =
                new osgUtil::PolytopeIntersector(
                    osgUtil::Intersector::PROJECTION,
                        x-w, y-h, x+w, y+h );

        osgUtil::IntersectionVisitor iv( picker );
        viewer->getCamera()->accept( iv );

        if (picker->containsIntersections())
        {
            const osg::NodePath& nodePath =
                    picker->getFirstIntersection().nodePath;
            unsigned int idx = nodePath.size();
            while (idx--)
            {
                // Find the LAST MatrixTransform in the node
                //   path; this will be the MatrixTransform
                //   to attach our callback to.
                osg::MatrixTransform* mt =
                        dynamic_cast<osg::MatrixTransform*>(
                            nodePath[ idx ] );
                if (mt == NULL)
                    continue;

                // If we get here, we just found a
                //   MatrixTransform in the nodePath.

                if (_selectedNode.valid())
                    // Clear the previous selected node's
                    //   callback to make it stop spinning.
                    _selectedNode->setUpdateCallback( NULL );

                _selectedNode = mt;
                _selectedNode->setUpdateCallback( new RotateCB );
                break;
            }
            if (!_selectedNode.valid())
                osg::notify() << "Pick failed." << std::endl;
        }
        else if (_selectedNode.valid())
        {
            _selectedNode->setUpdateCallback( NULL );
            _selectedNode = NULL;
        }
        return _selectedNode.valid();
    }
예제 #11
0
파일: ludcmp.hpp 프로젝트: pwoo/admb
 void allocate(int lb, int ub)
 {
     indx.allocate(lb, ub);
     indx2.allocate(lb, ub);
     ivector iv(lb + 1, ub);
     iv.fill_seqadd(lb, 1);
     L.allocate(lb + 1, ub, lb, iv);
     ivector iv1(lb, ub);
     iv1.fill_seqadd(lb, 1);
     U.allocate(lb, ub, lb, iv1);
     indx2.fill_seqadd(lb, 1);
 }
예제 #12
0
파일: ludcmp.hpp 프로젝트: pwoo/admb
 void allocate(int lb, int ub, int n, int m)
 {
     indx.allocate(lb, ub);
     indx2.allocate(lb, ub);
     dfclu.allocate(lb, ub);
     ivector iv(lb + 1, ub);
     iv.fill_seqadd(lb, 1);
     L.allocate(lb + 1, ub, lb, iv, 1, n);
     ivector iv1(lb, ub);
     iv1.fill_seqadd(lb, 1);
     U.allocate(lb, ub, lb, iv1, 1, m);
 }
void tst_QDoubleValidator::validateThouSep()
{
    QFETCH(QString, localeName);
    QFETCH(QString, value);
    QFETCH(QValidator::State, result);
    int dummy = 0;

    QDoubleValidator iv(-10000, 10000, 3, 0);
    iv.setNotation(QDoubleValidator::ScientificNotation);
    iv.setLocale(QLocale(localeName));

    QCOMPARE(iv.validate(value, dummy), result);
}
예제 #14
0
 ExecStatus
 Int<V0,V1,Idx,Val>::assigned_val(Space& home, IntSharedArray& c, 
                                  V0 x0, V1 x1) {
   Region r(home);
   int* v = r.alloc<int>(x0.size());
   int n = 0;
   for (ViewValues<V0> i(x0); i(); ++i)
     if (c[i.val()] != x1.val())
       v[n++]=i.val();
   Iter::Values::Array iv(v,n);
   GECODE_ME_CHECK(x0.minus_v(home,iv,false));
   return ES_OK;
 }
예제 #15
0
파일: Vector.C 프로젝트: seyko2/cfront-3
main()
{
	/*  Create a vector of VectorSize integers called "iv" and set
	**  each element of the vector to its subscript value.
	*/

	vector(int)	iv(VectorSize);

	for(int cnt = 0; cnt < VectorSize; cnt++){
		iv[cnt] = cnt;
	}

	/*  Now loop through the vector backwards and print each value.
	*/

	for(cnt = VectorSize - 1; cnt >= 0; cnt--){
		cout << iv[cnt] << " ";
	}
	cout << endl;

	/*  Specify an error handler to replace the default one provided
	**  by the vector(int) class.
	*/

	set_handler(vector,int, gotVectorError);

	/*  Cause a "subscript out of range" error in the vector(int)
	**  class.  If I were to do this in the vector(float) class now,
	**  the default message would print and then the program would
	**  be aborted.
	*/

	iv[VectorSize] = 99;

	/*  Specify an error handler to replace the default one provided
	**  by the vector(float) class.
	*/

	set_handler(vector,float, gotVectorError);

	/*  Now cause an error in the vector(float) class by trying to
	**  create a vector with a negative number of elements.
	*/

	vector(float)	rv(-3);

	/*  O.K. - enough fun for now.
	*/

	return 0;
}
예제 #16
0
void sorted_array_search(){
    cout<<endl<<"sorted_array_search :"<<endl;
    int ia[] = {0, 1,  3, 4,4,4,4, 5, 8, 11 };
    vector<int> iv(ia,ia+sizeof(ia)/sizeof(int));	vector<int>::iterator itr;
    cout<<iv<<endl;
    itr = lower_bound(iv.begin(),iv.end(), 8);
    cout<<"lower_bound: "<<*itr<<endl;
    itr = upper_bound(iv.begin(),iv.end(), 8);
    cout<<"upper_bound: "<<*itr<<endl;
    cout<<"binary_search: "<<binary_search(iv.begin(),iv.end(), 6)<<endl;
    vector<int>::iterator lowerb, upperb;
    pair<vector<int>::iterator, vector<int>::iterator> rst = equal_range(iv.begin(),iv.end(),4);
    cout<<"equal_range: "<<*rst.first<<" "<<*rst.second<<endl;
}
예제 #17
0
QByteArray Utils::decrypt(const QByteArray & msg, const QString & password)
{
    if (password.isEmpty()) return QByteArray();

    QCA::Cipher cipher(QString("aes128"), QCA::Cipher::CBC, QCA::Cipher::DefaultPadding);

    QCA::SymmetricKey key = QCA::SymmetricKey(password.toAscii());

    QCA::InitializationVector iv(msg.left(16));

    cipher.setup(QCA::Decode, key, iv);

    return cipher.process(msg.mid(16)).toByteArray();
}
예제 #18
0
QString QgsAuthCrypto::encryptdecrypt( QString passstr,
                                       QString cipheriv,
                                       QString textstr,
                                       bool encrypt )
{
  QString outtxt = QString();
  if ( QgsAuthCrypto::isDisabled() )
    return outtxt;

  QCA::InitializationVector iv( QCA::hexToArray( cipheriv ) );

  QCA::SymmetricKey key( QCA::SecureArray( QByteArray( passstr.toUtf8().constData() ) ) );

  if ( encrypt )
  {
    QCA::Cipher cipher = QCA::Cipher( CIPHER_TYPE, CIPHER_MODE, CIPHER_PADDING,
                                      QCA::Encode, key, iv,
                                      CIPHER_PROVIDER );

    QCA::SecureArray securedata( textstr.toUtf8() );
    QCA::SecureArray encrypteddata( cipher.process( securedata ) );
    if ( !cipher.ok() )
    {
      qDebug( "Encryption failed!" );
      return outtxt;
    }
    outtxt = QCA::arrayToHex( encrypteddata.toByteArray() );
    // qDebug( "Encrypted hex: %s", qPrintable( outtxt ) );
  }
  else
  {
    QCA::Cipher cipher = QCA::Cipher( CIPHER_TYPE, CIPHER_MODE, CIPHER_PADDING,
                                      QCA::Decode, key, iv,
                                      CIPHER_PROVIDER );

    QCA::SecureArray ciphertext( QCA::hexToArray( textstr ) );
    QCA::SecureArray decrypteddata( cipher.process( ciphertext ) );
    if ( !cipher.ok() )
    {
      qDebug( "Decryption failed!" );
      return outtxt;
    }

    outtxt = QString( decrypteddata.toByteArray() );
    // qDebug( "Decrypted text %s", qPrintable( outtxt ) ); // DO NOT LEAVE THIS LINE UNCOMMENTED
  }

  return outtxt;
}
예제 #19
0
static inline long do_const_sync(c_block *A,
				 sort_info *B,char *flagB,
				 long posA,long posB,
				 long *begin,long *end,long *offset){
  char *flagA=A->flags;
  long ret=0;

  if(flagB==NULL)
    ret=i_paranoia_overlap(cv(A),iv(B),posA,posB,
			   cs(A),is(B),begin,end);
  else
    if((flagB[posB]&2)==0)
      ret=i_paranoia_overlap2(cv(A),iv(B),flagA,flagB,posA,posB,cs(A),
			      is(B),begin,end);
	
  if(ret>MIN_WORDS_SEARCH){
    *offset=+(posA+cb(A))-(posB+ib(B));
    *begin+=cb(A);
    *end+=cb(A);
    return(ret);
  }
  
  return(0);
}
예제 #20
0
파일: Factor.cpp 프로젝트: cran/cxxPack
Factor::operator SEXP() {
    int numObs = getNumObservations();
    int numLevels = getNumLevels();
    Rcpp::IntegerVector iv(numObs); // allocates R memory
    Rcpp::CharacterVector cv(numLevels); // ditto
    SEXP RFactor = iv;
    for(int i=0; i < numObs; ++i)
	iv[i] = getObservedLevelNum(i);
    for(int i=0; i < numLevels; ++i)
	cv[i] = getLevelName(i);
    Rcpp::RObject ro(RFactor);
    ro.attr("class") = "factor";
    ro.attr("levels") = cv;
    return ro;
}
예제 #21
0
/**
 * @brief Decrypts input string stream using AES in GCM mode for
 *        confidentiality and authenticity.
 *
 * @param cipher const reference to a byte vector with encrypted data.
 * @param messageData reference to a byte vector to hold decrypted data.
 * @param key const reference to a byte vector with the decryption key.
 *
 * @return true, if decryption is successful.
 */
bool FileCryptopp::decrypt(
    const std::vector<uint8_t>& cipher,
    std::vector<uint8_t>& messageData,
    const std::vector<uint8_t>& key
) {

    // Initial Vector (IV) for AES to XOR.
    std::vector<uint8_t> iv(CryptoPP::AES::BLOCKSIZE);

    std::string decryptedtext; // store decrypted message


    try {
        // Initialize AES.
        CryptoPP::GCM< AES >::Decryption e;

        // Set AES Key and load IV.
        e.SetKeyWithIV(key.data(), key.size(), iv.data());

        /* Load encrypted data into an array source, then decrypt data using
         * a transformation filter. Dump the transformation using a string
         * sink into decryptedtext.
         */
        ArraySource ss2(
            cipher.data(),
            cipher.size(),
            true,
            new CryptoPP::AuthenticatedDecryptionFilter(
                e,
                new StringSink(decryptedtext)
            ) // StreamTransformationFilter
        ); // StringSource

    } catch (const CryptoPP::Exception& e) {
        // Failed decryption.
        std::cerr << "Error decrypting file: " << e.what() << std::endl;
        return false;
    }

    // Append messageData with bytes from decryptedtext.
    for (int i = 0; i < decryptedtext.size(); i++) {
        messageData.push_back(
            0xFF & static_cast<uint8_t>(decryptedtext[i])
        );
    }

    return true;
}
예제 #22
0
void OSGWidget::processSelection()
{
#ifdef WITH_SELECTION_PROCESSING
  QRect selectionRectangle = makeRectangle( selectionStart_, selectionEnd_ );
  int widgetHeight         = this->height();

  double xMin = selectionRectangle.left();
  double xMax = selectionRectangle.right();
  double yMin = widgetHeight - selectionRectangle.bottom();
  double yMax = widgetHeight - selectionRectangle.top();

  osgUtil::PolytopeIntersector* polytopeIntersector
      = new osgUtil::PolytopeIntersector( osgUtil::PolytopeIntersector::WINDOW,
                                          xMin, yMin,
                                          xMax, yMax );

  // This limits the amount of intersections that are reported by the
  // polytope intersector. Using this setting, a single drawable will
  // appear at most once while calculating intersections. This is the
  // preferred and expected behaviour.
  polytopeIntersector->setIntersectionLimit( osgUtil::Intersector::LIMIT_ONE_PER_DRAWABLE );

  osgUtil::IntersectionVisitor iv( polytopeIntersector );

  for( unsigned int viewIndex = 0; viewIndex < viewer_->getNumViews(); viewIndex++ )
  {
    osgViewer::View* view = viewer_->getView( viewIndex );

    if( !view )
      throw std::runtime_error( "Unable to obtain valid view for selection processing" );

    osg::Camera* camera = view->getCamera();

    if( !camera )
      throw std::runtime_error( "Unable to obtain valid camera for selection processing" );

    camera->accept( iv );

    if( !polytopeIntersector->containsIntersections() )
      continue;

    auto intersections = polytopeIntersector->getIntersections();

    for( auto&& intersection : intersections )
      qDebug() << "Selected a drawable:" << QString::fromStdString( intersection.drawable->getName() );
  }
#endif
}
예제 #23
0
  void AppWindow::
  Reshape(int width,
	  int height)
  {
    // Do NOT try to be smart and skip if width and height haven't
    // changed, because we do call Reshape() with unchanged sizes when
    // view get initialized.
    
    m_width = width;
    m_height = height;
    
    for (View::registry_t::vector_t::const_iterator iv(View::registry.vector_.begin());
	 iv != View::registry.vector_.end(); ++iv) {
      (*iv)->Reshape(width, height);
    }
  }
예제 #24
0
void test_heap() 
{
	int ia[] = { 0,1,2,3,4,7,9,8,5 };
	std::vector<int> iv(ia, ia + 9);

	std::make_heap(iv.begin(), iv.end());
	print(iv);

	iv.push_back(6);
	std::push_heap(iv.begin(), iv.end());
	print(iv);

	std::pop_heap(iv.begin(), iv.end());
	iv.pop_back();
	print(iv);
}
예제 #25
0
파일: STensor3.cpp 프로젝트: fmach/agros2d
// preserve orientation of m1 !!!
SMetric3 intersection_conserveM1 (const SMetric3 &m1, const SMetric3 &m2)
{
  // we should do
  // return intersection (m1,m2);
  fullMatrix<double> V(3,3);
  fullVector<double> S(3);
  m1.eig(V,S,true);
  SVector3 v0(V(0,0),V(1,0),V(2,0));
  SVector3 v1(V(0,1),V(1,1),V(2,1));
  SVector3 v2(V(0,2),V(1,2),V(2,2));
  double l0 = std::max(dot(v0,m1,v0),dot(v0,m2,v0));
  double l1 = std::max(dot(v1,m1,v1),dot(v1,m2,v1));
  double l2 = std::max(dot(v2,m1,v2),dot(v2,m2,v2));
  SMetric3 iv(l0,l1,l2,v0,v1,v2);
  return iv;
}
예제 #26
0
/**
 * @brief Encrypts input string stream using AES in GCM mode for
 *        confidentiality and authenticity.
 *
 * @param message const reference to a string stream with data.
 * @param cipherData reference to a byte vector to hold encrypted data.
 * @param key const reference to a byte vector with an encryption key.
 *
 * @return true, if encryption is successful.
 */
bool FileCryptopp::encrypt(
    const std::stringstream& message,
    std::vector<uint8_t>& cipherData,
    const std::vector<uint8_t>& key
) {

    // Initial Vector (IV) for AES to XOR.
    std::vector<uint8_t> iv(CryptoPP::AES::BLOCKSIZE);

    std::string plaintext = message.str(); // store message
    std::string ciphertext; // store encrypted message


    try {
        // Initialize AES.
        CryptoPP::GCM<AES>::Encryption e;

        // Set AES Key and load IV.
        e.SetKeyWithIV(key.data(), key.size(), iv.data());

        /* Load plain text into string source, then encrypt stream using
         * a transformation filter. Dump the transformation using a
         * string sink into ciphertext.
         */
        StringSource ss1(plaintext,
            true,
            new CryptoPP::AuthenticatedEncryptionFilter(
                e,
                new StringSink(ciphertext)
            ) // StreamTransformationFilter
        ); // StringSource

    } catch (const CryptoPP::Exception& e) {
        // Failed Encryption.
        std::cerr << "Error encrypting file: " << e.what() << std::endl;
        return false;
    }

    // Append cipherData with bytes from ciphertext.
    for (int i = 0; i < ciphertext.size(); i++) {
        cipherData.push_back(
            0xFF & static_cast<uint8_t>(ciphertext[i])
        );
    }

    return true;
}
예제 #27
0
파일: osgforest.cpp 프로젝트: yueying/osg
void ForestTechniqueManager::createTreeList(osg::Node* terrain,const osg::Vec3& origin, const osg::Vec3& size,unsigned int numTreesToCreate,TreeList& trees)
{

    float max_TreeHeight = sqrtf(size.length2()/(float)numTreesToCreate);
    float max_TreeWidth = max_TreeHeight*0.5f;

    float min_TreeHeight = max_TreeHeight*0.3f;
    float min_TreeWidth = min_TreeHeight*0.5f;

    trees.reserve(trees.size()+numTreesToCreate);


    for(unsigned int i=0;i<numTreesToCreate;++i)
    {
        Tree* tree = new Tree;
        tree->_position.set(random(origin.x(),origin.x()+size.x()),random(origin.y(),origin.y()+size.y()),origin.z());
        tree->_color.set(random(128,255),random(128,255),random(128,255),255);
        tree->_width = random(min_TreeWidth,max_TreeWidth);
        tree->_height = random(min_TreeHeight,max_TreeHeight);
        tree->_type = 0;

        if (terrain)
        {
            osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector =
                new osgUtil::LineSegmentIntersector(tree->_position,tree->_position+osg::Vec3(0.0f,0.0f,size.z()));

            osgUtil::IntersectionVisitor iv(intersector.get());

            terrain->accept(iv);

            if (intersector->containsIntersections())
            {
                osgUtil::LineSegmentIntersector::Intersections& intersections = intersector->getIntersections();
                for(osgUtil::LineSegmentIntersector::Intersections::iterator itr = intersections.begin();
                    itr != intersections.end();
                    ++itr)
                {
                    const osgUtil::LineSegmentIntersector::Intersection& intersection = *itr;
                    tree->_position = intersection.getWorldIntersectPoint();
                }
            }
        }

        trees.push_back(tree);
    }
}
예제 #28
0
void EncryptWrapper::cryptInit(QString pwd){
	QByteArray key(EVP_MAX_KEY_LENGTH,0);
	QByteArray iv(EVP_MAX_IV_LENGTH,0);

//	convert QString to unsigned char
	unsigned char *password = (unsigned char *)malloc(sizeof(unsigned char));
	memcpy(password, pwd.toStdString().c_str(),pwd.size());

	if(!EVP_BytesToKey(EVP_aes_256_cbc(),EVP_sha1(), NULL,
					   (unsigned char *) password,
					   strlen((const char *)password), 1, (unsigned char *)key.data(), (unsigned char *)iv.data())){
		emit errors("EVP_BytesToKey failed: Password "+pwd+" doesn't create.");
		return;
	}
	EVP_CIPHER_CTX_init(&encrypt);
	EVP_EncryptInit(&encrypt, EVP_aes_256_cbc(), (const unsigned char*)key.constData(), (const unsigned char*)iv.constData());
}
예제 #29
0
/** Compute intersections between a ray through the specified master cameras window/eye coords and a specified node.
 * Note, when a master cameras has slaves and no viewport itself its coordinate frame will be in clip space i.e. -1,-1 to 1,1,
 * while if its has a viewport the coordintates will be relative to its viewport dimensions. 
 * Mouse events handled by the view will automatically be attached into the master camera window/clip coords so can be passed
 * directly on to the computeIntersections method. */
bool ossimPlanetViewer::computeIntersections(float x,
                                                     float y, 
                                                     osgUtil::LineSegmentIntersector::Intersections& intersections,
                                                     osg::Node::NodeMask traversalMask)
{
   if (!_camera.valid()) return false;
   
   float local_x, local_y = 0.0;    
   const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
   if (!camera)
   {
      if(theIntersectWithMasterIfNotWithinAnyViewFlag)
      {
         camera = forceAdjustToMasterCamera(x, y, local_x, local_y);
         if(!camera) return false;
      }
      else
      {
         return false;
      }
   }
   
   osgUtil::LineSegmentIntersector::CoordinateFrame cf = camera->getViewport() ? osgUtil::Intersector::WINDOW : osgUtil::Intersector::PROJECTION;
   osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(cf, local_x, local_y);
   osg::Vec3d adjustedStart(picker->getStart());
#if 0
   if(thePlanet.valid())
   {
      adjustedStart[2]-=(5*thePlanet->model()->getInvNormalizationScale());
   }
   picker->setStart(adjustedStart);
#endif
   osgUtil::IntersectionVisitor iv(picker.get());
   iv.setTraversalMask(traversalMask);
   iv.setUseKdTreeWhenAvailable(true);
   
   const_cast<osg::Camera*>(camera)->accept(iv);
   
   if (picker->containsIntersections())
   {
      intersections = picker->getIntersections();
      return true;
   }
   intersections.clear();
   return false;
}
예제 #30
0
파일: Encrypt.cpp 프로젝트: ONLYOFFICE/core
        void Reset()
        {
            if (streamEncryption)
                delete streamEncryption;
            if (aesEncryption)
                delete aesEncryption;

			CryptoPP::RandomPool prng;
			CryptoPP::SecByteBlock iv(16);
			CryptoPP::OS_GenerateRandomBlock(false, iv, iv.size());
			prng.IncorporateEntropy(iv, iv.size());

			memcpy(streamInitialization, iv, iv.size());
			
			aesEncryption       = new CryptoPP::AES::Encryption(m_anEncryptionKey, 32);
            streamEncryption    = new CryptoPP::CBC_Mode_ExternalCipher::Encryption( *aesEncryption, streamInitialization);
        }