Exemple #1
0
HeapWord* PermGen::mem_allocate_in_gen(size_t size, Generation* gen) {
  GCCause::Cause next_cause = GCCause::_permanent_generation_full;
  GCCause::Cause prev_cause = GCCause::_no_gc;
  unsigned int gc_count_before, full_gc_count_before;
  HeapWord* obj;

  for (;;) {
    {
      MutexLocker ml(Heap_lock);
      if ((obj = gen->allocate(size, false)) != NULL) {
        return obj;
      }
      if (gen->capacity() < _capacity_expansion_limit ||
          prev_cause != GCCause::_no_gc) {
        obj = gen->expand_and_allocate(size, false);
      }
      if (obj != NULL || prev_cause == GCCause::_last_ditch_collection) {
        return obj;
      }
      if (GC_locker::is_active_and_needs_gc()) {
        // If this thread is not in a jni critical section, we stall
        // the requestor until the critical section has cleared and
        // GC allowed. When the critical section clears, a GC is
        // initiated by the last thread exiting the critical section; so
        // we retry the allocation sequence from the beginning of the loop,
        // rather than causing more, now probably unnecessary, GC attempts.
        JavaThread* jthr = JavaThread::current();
        if (!jthr->in_critical()) {
          MutexUnlocker mul(Heap_lock);
          // Wait for JNI critical section to be exited
          GC_locker::stall_until_clear();
          continue;
        } else {
          if (CheckJNICalls) {
            fatal("Possible deadlock due to allocating while"
                  " in jni critical section");
          }
          return NULL;
        }
      }
      // Read the GC count while holding the Heap_lock
      gc_count_before      = SharedHeap::heap()->total_collections();
      full_gc_count_before = SharedHeap::heap()->total_full_collections();
    }

    // Give up heap lock above, VMThread::execute below gets it back
    VM_GenCollectForPermanentAllocation op(size, gc_count_before, full_gc_count_before,
                                           next_cause);
    VMThread::execute(&op);
    if (!op.prologue_succeeded() || op.gc_locked()) {
      assert(op.result() == NULL, "must be NULL if gc_locked() is true");
      continue;  // retry and/or stall as necessary
    }
    obj = op.result();
    assert(obj == NULL || SharedHeap::heap()->is_in_reserved(obj),
           "result not in heap");
    if (obj != NULL) {
      return obj;
    }
    prev_cause = next_cause;
    next_cause = GCCause::_last_ditch_collection;
  }
}
Exemple #2
0
	void CClientFrameGenerator::generate( DataSerializer & serializer )
	{
		DataSerializer::WriteOp op( serializer );
		mFrameData.serialize( op );
	}
Exemple #3
0
bool IRInstruction::isEssential() const {
  return isControlFlow() ||
         opcodeHasFlags(op(), Essential);
}
Exemple #4
0
	request::request(const char *headln)
	{
		char type[10];
#define op(a) a = NULL
		op(this->header.accept.accept);
		op(this->header.accept.charset);
		op(this->header.accept.encoding);
		op(this->header.accept.language);
		op(this->header.clientinfo.referer);
		op(this->header.clientinfo.te);
		op(this->header.clientinfo.user_agent);
		op(this->header.hostinfo.authorization);
		op(this->header.hostinfo.expect);
		op(this->header.hostinfo.from);
		op(this->header.hostinfo.host);
		op(this->header.netinfo.max_forwards);
		op(this->header.netinfo.proxy_authorization);
		op(this->header.netinfo.range);
		op(this->header.sectif.match);
		op(this->header.sectif.modified_since);
		op(this->header.sectif.none_match);
		op(this->header.sectif.range);
		op(this->header.sectif.unmodified_since);
#undef  op
		sscanf(headln, "%s %s HTTP/1.%d", type, this->URI, &this->protocolversion);
#define op(a) (strcmp(type, a) == 0)
		if (op("OPTIONS"))
			this->requesttype = kOPTIONS;
		if (op("GET"))
			this->requesttype = kGET;
		if (op("HEAD"))
			this->requesttype = kHEAD;
		if (op("POST"))
			this->requesttype = kPOST;
		if (op("PUT"))
			this->requesttype = kPUT;
		if (op("DELETE"))
			this->requesttype = kDELETE;
		if (op("TRACE"))
			this->requesttype = kTRACE;
		if (op("CONNECT"))
			this->requesttype = kCONNECT;
#undef  op
		this->parseHTTPHeader(headln);
	}
void
  mitk::SlicedGeometry3D::ExecuteOperation(Operation* operation)
{
  switch ( operation->GetOperationType() )
  {
  case OpNOTHING:
    break;

  case OpROTATE:
    if ( m_EvenlySpaced )
    {
      // Need a reference frame to align the rotation
      if ( m_ReferenceGeometry )
      {
        // Clear all generated geometries and then rotate only the first slice.
        // The other slices will be re-generated on demand

        // Save first slice
        PlaneGeometry::Pointer geometry2D = m_PlaneGeometries[0];

        RotationOperation *rotOp = dynamic_cast< RotationOperation * >( operation );

        // Generate a RotationOperation using the dataset center instead of
        // the supplied rotation center. This is necessary so that the rotated
        // zero-plane does not shift away. The supplied center is instead used
        // to adjust the slice stack afterwards.
        Point3D center = m_ReferenceGeometry->GetCenter();

        RotationOperation centeredRotation(
          rotOp->GetOperationType(),
          center,
          rotOp->GetVectorOfRotation(),
          rotOp->GetAngleOfRotation()
          );

        // Rotate first slice
        geometry2D->ExecuteOperation( &centeredRotation );

        // Clear the slice stack and adjust it according to the center of
        // the dataset and the supplied rotation center (see documentation of
        // ReinitializePlanes)
        this->ReinitializePlanes( center, rotOp->GetCenterOfRotation() );

        geometry2D->SetSpacing(this->GetSpacing());

        if ( m_SliceNavigationController )
        {
          m_SliceNavigationController->SelectSliceByPoint(
            rotOp->GetCenterOfRotation() );
          m_SliceNavigationController->AdjustSliceStepperRange();
        }

        BaseGeometry::ExecuteOperation( &centeredRotation );
      }
      else
      {
        // we also have to consider the case, that there is no reference geometry available.
        if ( m_PlaneGeometries.size() > 0 )
        {
          // Reach through to all slices in my container
          for (auto iter = m_PlaneGeometries.begin();
            iter != m_PlaneGeometries.end();
            ++iter)
          {
            // Test for empty slices, which can happen if evenly spaced geometry
            if ((*iter).IsNotNull())
            {
              (*iter)->ExecuteOperation(operation);
            }
          }

          // rotate overall geometry
          RotationOperation *rotOp = dynamic_cast< RotationOperation * >( operation );
          BaseGeometry::ExecuteOperation( rotOp);
        }
      }
    }
    else
    {
      // Reach through to all slices
      for (auto iter = m_PlaneGeometries.begin();
        iter != m_PlaneGeometries.end();
        ++iter)
      {
        (*iter)->ExecuteOperation(operation);
      }
    }
    break;

  case OpORIENT:
    if ( m_EvenlySpaced )
    {
      // get operation data
      PlaneOperation *planeOp = dynamic_cast< PlaneOperation * >( operation );

      // Get first slice
      PlaneGeometry::Pointer planeGeometry = m_PlaneGeometries[0];

      // Need a PlaneGeometry, a PlaneOperation and a reference frame to
      // carry out the re-orientation. If not all avaialble, stop here
      if ( !m_ReferenceGeometry                                                                       ||
           ( !planeGeometry || dynamic_cast<AbstractTransformGeometry*>(planeGeometry.GetPointer()) ) ||
           !planeOp )
      {
        break;
      }

      // General Behavior:
      // Clear all generated geometries and then rotate only the first slice.
      // The other slices will be re-generated on demand

      //
      // 1st Step: Reorient Normal Vector of first plane
      //
      Point3D center = planeOp->GetPoint(); //m_ReferenceGeometry->GetCenter();
      mitk::Vector3D currentNormal = planeGeometry->GetNormal();
      mitk::Vector3D newNormal;
      if (planeOp->AreAxisDefined())
      {
        // If planeOp was defined by one centerpoint and two axis vectors
        newNormal = CrossProduct(planeOp->GetAxisVec0(), planeOp->GetAxisVec1());
      }
      else
      {
        // If planeOp was defined by one centerpoint and one normal vector
        newNormal = planeOp->GetNormal();
      }

      // Get Rotation axis und angle
      currentNormal.Normalize();
      newNormal.Normalize();
      ScalarType rotationAngle = angle(currentNormal.GetVnlVector(),newNormal.GetVnlVector());

      rotationAngle *= 180.0 / vnl_math::pi; // from rad to deg
      Vector3D rotationAxis = itk::CrossProduct( currentNormal, newNormal );
      if (std::abs(rotationAngle-180) < mitk::eps )
      {
        // current Normal and desired normal are not linear independent!!(e.g 1,0,0 and -1,0,0).
        // Rotation Axis should be ANY vector that is 90� to current Normal
        mitk::Vector3D helpNormal;
        helpNormal = currentNormal;
        helpNormal[0] += 1;
        helpNormal[1] -= 1;
        helpNormal[2] += 1;
        helpNormal.Normalize();
        rotationAxis = itk::CrossProduct( helpNormal, currentNormal );
      }

      RotationOperation centeredRotation(
        mitk::OpROTATE,
        center,
        rotationAxis,
        rotationAngle
        );

      // Rotate first slice
      planeGeometry->ExecuteOperation( &centeredRotation );

      // Reinitialize planes and select slice, if my rotations are all done.
      if (!planeOp->AreAxisDefined())
      {
        // Clear the slice stack and adjust it according to the center of
        // rotation and plane position (see documentation of ReinitializePlanes)
        this->ReinitializePlanes( center, planeOp->GetPoint() );

        if ( m_SliceNavigationController )
        {
          m_SliceNavigationController->SelectSliceByPoint( planeOp->GetPoint() );
          m_SliceNavigationController->AdjustSliceStepperRange();
        }
      }

      // Also apply rotation on the slicedGeometry - Geometry3D (Bounding geometry)
      BaseGeometry::ExecuteOperation( &centeredRotation );

      //
      // 2nd step. If axis vectors were defined, rotate the plane around its normal to fit these
      //

      if (planeOp->AreAxisDefined())
      {
        mitk::Vector3D vecAxixNew = planeOp->GetAxisVec0();
        vecAxixNew.Normalize();
        mitk::Vector3D VecAxisCurr = planeGeometry->GetAxisVector(0);
        VecAxisCurr.Normalize();

        ScalarType rotationAngle = angle(VecAxisCurr.GetVnlVector(),vecAxixNew.GetVnlVector());
        rotationAngle = rotationAngle * 180 / PI; // Rad to Deg

        // we rotate around the normal of the plane, but we do not know, if we need to rotate clockwise
        // or anti-clockwise. So we rotate around the crossproduct of old and new Axisvector.
        // Since both axis vectors lie in the plane, the crossproduct is the planes normal or the negative planes normal

        rotationAxis = itk::CrossProduct( VecAxisCurr, vecAxixNew  );
        if (std::abs(rotationAngle-180) < mitk::eps )
        {
          // current axisVec and desired axisVec are not linear independent!!(e.g 1,0,0 and -1,0,0).
          // Rotation Axis can be just plane Normal. (have to rotate by 180�)
          rotationAxis = newNormal;
        }

        // Perfom Rotation
        mitk::RotationOperation op(mitk::OpROTATE, center, rotationAxis, rotationAngle);
        planeGeometry->ExecuteOperation( &op );

        // Apply changes on first slice to whole slice stack
        this->ReinitializePlanes( center, planeOp->GetPoint() );

        if ( m_SliceNavigationController )
        {
          m_SliceNavigationController->SelectSliceByPoint( planeOp->GetPoint() );
          m_SliceNavigationController->AdjustSliceStepperRange();
        }

        // Also apply rotation on the slicedGeometry - Geometry3D (Bounding geometry)
        BaseGeometry::ExecuteOperation( &op );
      }
    }
    else
    {
      // Reach through to all slices
      for (auto iter = m_PlaneGeometries.begin();
        iter != m_PlaneGeometries.end();
        ++iter)
      {
        (*iter)->ExecuteOperation(operation);
      }
    }
    break;

  case OpRESTOREPLANEPOSITION:
    if ( m_EvenlySpaced )
    {
      // Save first slice
      PlaneGeometry::Pointer planeGeometry = m_PlaneGeometries[0];

      RestorePlanePositionOperation *restorePlaneOp = dynamic_cast< RestorePlanePositionOperation* >( operation );

      // Need a PlaneGeometry, a PlaneOperation and a reference frame to
      // carry out the re-orientation
      if ( m_ReferenceGeometry && (planeGeometry && dynamic_cast<AbstractTransformGeometry*>(planeGeometry.GetPointer()) == nullptr) && restorePlaneOp )
      {
        // Clear all generated geometries and then rotate only the first slice.
        // The other slices will be re-generated on demand

        // Rotate first slice
        planeGeometry->ExecuteOperation( restorePlaneOp );

        m_DirectionVector = restorePlaneOp->GetDirectionVector();

        double centerOfRotationDistance =
          planeGeometry->SignedDistanceFromPlane( m_ReferenceGeometry->GetCenter() );

        if ( centerOfRotationDistance > 0 )
        {
          m_DirectionVector = m_DirectionVector;
        }
        else
        {
          m_DirectionVector = -m_DirectionVector;
        }

        Vector3D spacing = restorePlaneOp->GetSpacing();

        Superclass::SetSpacing( spacing );

        // /*Now we need to calculate the number of slices in the plane's normal
        // direction, so that the entire volume is covered. This is done by first
        // calculating the dot product between the volume diagonal (the maximum
        // distance inside the volume) and the normal, and dividing this value by
        // the directed spacing calculated above.*/
        ScalarType directedExtent =
          std::abs( m_ReferenceGeometry->GetExtentInMM( 0 ) * m_DirectionVector[0] )
          + std::abs( m_ReferenceGeometry->GetExtentInMM( 1 ) * m_DirectionVector[1] )
          + std::abs( m_ReferenceGeometry->GetExtentInMM( 2 ) * m_DirectionVector[2] );

        if ( directedExtent >= spacing[2] )
        {
          m_Slices = static_cast< unsigned int >(directedExtent / spacing[2] + 0.5);
        }
        else
        {
          m_Slices = 1;
        }

        m_PlaneGeometries.assign( m_Slices, PlaneGeometry::Pointer( nullptr ) );

        if ( m_Slices > 0 )
        {
          m_PlaneGeometries[0] = planeGeometry;
        }

        m_SliceNavigationController->GetSlice()->SetSteps( m_Slices );

        this->Modified();

        //End Reinitialization

        if ( m_SliceNavigationController )
        {
          m_SliceNavigationController->GetSlice()->SetPos( restorePlaneOp->GetPos() );
          m_SliceNavigationController->AdjustSliceStepperRange();
        }
        BaseGeometry::ExecuteOperation(restorePlaneOp);
      }
    }
    else
    {
      // Reach through to all slices
      for (auto iter = m_PlaneGeometries.begin();
        iter != m_PlaneGeometries.end();
        ++iter)
      {
        (*iter)->ExecuteOperation(operation);
      }
    }
    break;

  case OpAPPLYTRANSFORMMATRIX:

    // Clear all generated geometries and then transform only the first slice.
    // The other slices will be re-generated on demand

    // Save first slice
    PlaneGeometry::Pointer geometry2D = m_PlaneGeometries[0];

    ApplyTransformMatrixOperation *applyMatrixOp = dynamic_cast< ApplyTransformMatrixOperation* >( operation );

    // Apply transformation to first plane
    geometry2D->ExecuteOperation( applyMatrixOp );

    // Generate a ApplyTransformMatrixOperation using the dataset center instead of
    // the supplied rotation center. The supplied center is instead used to adjust the
    // slice stack afterwards (see OpROTATE).
    Point3D center = m_ReferenceGeometry->GetCenter();

    // Clear the slice stack and adjust it according to the center of
    // the dataset and the supplied rotation center (see documentation of
    // ReinitializePlanes)
    this->ReinitializePlanes( center, applyMatrixOp->GetReferencePoint() );

    BaseGeometry::ExecuteOperation( applyMatrixOp );
    break;
  }

  this->Modified();
}
 // Operators to make my life easier
 int operator() (int const x, int const y) const {
     return op(x, y);
 }
Exemple #7
0
	const char *request::operator[](const char * val)
	{
#define op(a) (strcmp(val, a) == 0)
		if (op("Accept"))              return getAccept();
		else if (op("Accept-Charset"))      return getAccept_Charset();
		else if (op("Accept-Encoding"))     return getAccept_Encoding();
		else if (op("Accept-Language"))     return getAccept_Language();
		else if (op("Authorization"))       return getAuthorization();
		else if (op("Expect"))              return getExpect();
		else if (op("From"))                return getFrom();
		else if (op("If-Match"))            return getIf_Match();
		else if (op("If-Modified-Since"))   return getIf_Modified_since();
		else if (op("If-None-Match"))       return getIf_None_Match();
		else if (op("If-Range"))            return getIf_Range();
		else if (op("If-Unmodified-Since")) return getIf_Unmodified_Since();
		else if (op("Max-Forwards"))        return getMax_Forwards();
		else if (op("Proxy-Authorization")) return getProxy_Authorization();
		else if (op("Range"))               return getRange();
		else if (op("Referer"))             return getReferrer();
		else if (op("TE"))                  return getTE();
		else if (op("User-Agent"))          return getUser_Agent();
		else if (op("URI"))                 return this->URI;
		return NULL;
#undef op
	}
NodoArbol<Elemento *> * Operacion::descomponer() {

	Elemento * resultado;
	NodoArbol<Elemento *> * resultadoNodo;
	int indice = indiceMenorPrecedencia(operacion);
	string cen = operacion.substr(indice, 1);
	if (indice == -1) {
		resultado = new Operando(stod(operacion));
		//return new NodoArbol<Elemento *>(resultado);
	}
	else {		
		if (cen == "f"){
			resultado = new OperadorFunction();
			string a = operacion.substr(indice + 2, operacion.length() - indice - 1);
			istringstream op(a);
			string operando;
			while (getline(op, operando, ',')){
				resultadoNodo->setNode(new NodoArbol<Elemento *>(resultado));
				return resultadoNodo;
			}
		}
		else {
			if (cen == "s" || cen == "c" || cen == "t" || cen == "l"){
				string a = operacion.substr(indice, 1);
				string b = operacion.substr(indice + 1, operacion.length() - indice - 1);

				switch (cen[0]) {
				case 's':
					resultado = new OperadorSeno();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);// debe agregar nuevo nodo que contenga la operacion
					break;
				case 'c':
					resultado = new OperadorCoseno();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				case 't':
					resultado = new OperadorTangente();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				case 'l':
					resultado = new OperadorLogNatural();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				default:
					resultado = NULL;
					break;
				}
				resultadoNodo->setNode(new NodoArbol<Elemento *>(procesarStringHijo(b)));
				return resultadoNodo;
			}
			else {
				string a = operacion.substr(0, indice);
				string b = operacion.substr(indice, 1);
				string c = operacion.substr(indice + 1, operacion.length() - indice - 1);

				switch (cen[0]) {
				case '+':
					resultado = new OperadorSuma();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				case '-':
					resultado = new OperadorResta();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				case'*':
					resultado = new OperadorMultiplicacion();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				case '/':
					resultado = new OperadorDivision();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				case '^':
					resultado = new OperadorExponencial();
					resultadoNodo = new NodoArbol<Elemento *>(resultado);
					break;
				default:
					resultado = NULL;
					break;
				}
				resultadoNodo->setNode(new NodoArbol<Elemento *>(procesarStringHijo(a)));
				resultadoNodo->setNode(new NodoArbol<Elemento *>(procesarStringHijo(c)));
			}
		}
	}
	return resultadoNodo;
}
RegionDescPtr selectTraceletLegacy(const Transl::Tracelet& tlet) {
    typedef RegionDesc::Block Block;

    auto region = std::make_shared<RegionDesc>();
    SrcKey sk(tlet.m_sk);
    auto unit = tlet.func()->unit();

    const Func* topFunc = nullptr;
    Block* curBlock = nullptr;
    auto newBlock = [&](const Func* func, SrcKey start) {
        assert(curBlock == nullptr || curBlock->length() > 0);
        region->blocks.push_back(
            std::make_shared<Block>(func, start.offset(), 0));
        curBlock = region->blocks.back().get();
    };
    newBlock(tlet.func(), sk);

    for (auto ni = tlet.m_instrStream.first; ni; ni = ni->next) {
        assert(sk == ni->source);
        assert(ni->unit() == unit);

        curBlock->addInstruction();
        if ((curBlock->length() == 1 && ni->funcd != nullptr) ||
                ni->funcd != topFunc) {
            topFunc = ni->funcd;
            curBlock->setKnownFunc(sk, topFunc);
        }

        if (ni->calleeTrace && !ni->calleeTrace->m_inliningFailed) {
            assert(ni->op() == OpFCall);
            assert(ni->funcd == ni->calleeTrace->func());
            // This should be translated as an inlined call. Insert the blocks of the
            // callee in the region.
            auto const& callee = *ni->calleeTrace;
            curBlock->setInlinedCallee(ni->funcd);
            SrcKey cSk = callee.m_sk;
            Unit* cUnit = callee.func()->unit();

            newBlock(callee.func(), cSk);

            for (auto cni = callee.m_instrStream.first; cni; cni = cni->next) {
                assert(cSk == cni->source);
                assert(cni->op() == OpRetC ||
                       cni->op() == OpContRetC ||
                       cni->op() == OpNativeImpl ||
                       !instrIsNonCallControlFlow(cni->op()));

                curBlock->addInstruction();
                cSk.advance(cUnit);
            }

            if (ni->next) {
                sk.advance(unit);
                newBlock(tlet.func(), sk);
            }
            continue;
        }

        if (!ni->noOp && isFPassStar(ni->op())) {
            curBlock->setParamByRef(sk, ni->preppedByRef);
        }

        if (ni->next && ni->op() == OpJmp) {
            // A Jmp that isn't the final instruction in a Tracelet means we traced
            // through a forward jump in analyze. Update sk to point to the next NI
            // in the stream.
            auto dest = ni->offset() + ni->imm[0].u_BA;
            assert(dest > sk.offset()); // We only trace for forward Jmps for now.
            sk.setOffset(dest);

            // The Jmp terminates this block.
            newBlock(tlet.func(), sk);
        } else {
            sk.advance(unit);
        }
    }

    auto& frontBlock = *region->blocks.front();

    // Add tracelet guards as predictions on the first instruction. Predictions
    // and known types from static analysis will be applied by
    // Translator::translateRegion.
    for (auto const& dep : tlet.m_dependencies) {
        if (dep.second->rtt.isVagueValue() ||
                dep.second->location.isThis()) continue;

        typedef RegionDesc R;
        auto addPred = [&](const R::Location& loc) {
            auto type = Type::fromRuntimeType(dep.second->rtt);
            frontBlock.addPredicted(tlet.m_sk, {loc, type});
        };

        switch (dep.first.space) {
        case Transl::Location::Stack:
            addPred(R::Location::Stack{uint32_t(-dep.first.offset - 1)});
            break;

        case Transl::Location::Local:
            addPred(R::Location::Local{uint32_t(dep.first.offset)});
            break;

        default:
            not_reached();
        }
    }

    // Add reffiness dependencies as predictions on the first instruction.
    for (auto const& dep : tlet.m_refDeps.m_arMap) {
        RegionDesc::ReffinessPred pred{dep.second.m_mask,
                                       dep.second.m_vals,
                                       dep.first};
        frontBlock.addReffinessPred(tlet.m_sk, pred);
    }

    FTRACE(2, "Converted Tracelet:\n{}\nInto RegionDesc:\n{}\n",
           tlet.toString(), show(*region));
    return region;
}
Exemple #10
0
ex basic::operator[](size_t i) const
{
    return op(i);
}
Exemple #11
0
/** Check whether the expression matches a given pattern. For every wildcard
 *  object in the pattern, a pair with the wildcard as a key and matching
 *  expression as a value is added to repl_lst. */
bool basic::match(const ex & pattern, exmap& repl_lst) const
{
    /*
    	Sweet sweet shapes, sweet sweet shapes,
    	That's the key thing, right right.
    	Feed feed face, feed feed shapes,
    	But who is the king tonight?
    	Who is the king tonight?
    	Pattern is the thing, the key thing-a-ling,
    	But who is the king of Pattern?
    	But who is the king, the king thing-a-ling,
    	Who is the king of Pattern?
    	Bog is the king, the king thing-a-ling,
    	Bog is the king of Pattern.
    	Ba bu-bu-bu-bu bu-bu-bu-bu-bu-bu bu-bu
    	Bog is the king of Pattern.
    */

    if (is_exactly_a<wildcard>(pattern)) {

        // Wildcard matches anything, but check whether we already have found
        // a match for that wildcard first (if so, the earlier match must be
        // the same expression)
        for (exmap::const_iterator it = repl_lst.begin(); it != repl_lst.end(); ++it) {
            if (it->first.is_equal(pattern))
                return is_equal(ex_to<basic>(it->second));
        }
        repl_lst[pattern] = *this;
        return true;

    } else {

        // Expression must be of the same type as the pattern
        if (typeid(*this) != typeid(ex_to<basic>(pattern)))
            return false;

        // Number of subexpressions must match
        if (nops() != pattern.nops())
            return false;

        // No subexpressions? Then just compare the objects (there can't be
        // wildcards in the pattern)
        if (nops() == 0)
            return is_equal_same_type(ex_to<basic>(pattern));

        // Check whether attributes that are not subexpressions match
        if (!match_same_type(ex_to<basic>(pattern)))
            return false;

        // Even if the expression does not match the pattern, some of
        // its subexpressions could match it. For example, x^5*y^(-1)
        // does not match the pattern $0^5, but its subexpression x^5
        // does. So, save repl_lst in order to not add bogus entries.
        exmap tmp_repl = repl_lst;
        // Otherwise the subexpressions must match one-to-one
        for (size_t i=0; i<nops(); i++)
            if (!op(i).match(pattern.op(i), tmp_repl))
                return false;

        // Looks similar enough, match found
        repl_lst = tmp_repl;
        return true;
    }
}
Exemple #12
0
void
StorageDBThread::ThreadFunc()
{
  nsresult rv = InitDatabase();

  MonitorAutoLock lockMonitor(mThreadObserver->GetMonitor());

  if (NS_FAILED(rv)) {
    mStatus = rv;
    mStopIOThread = true;
    return;
  }

  // Create an nsIThread for the current PRThread, so we can observe runnables
  // dispatched to it.
  nsCOMPtr<nsIThread> thread = NS_GetCurrentThread();
  nsCOMPtr<nsIThreadInternal> threadInternal = do_QueryInterface(thread);
  MOZ_ASSERT(threadInternal); // Should always succeed.
  threadInternal->SetObserver(mThreadObserver);

  while (MOZ_LIKELY(!mStopIOThread || mPreloads.Length() ||
                    mPendingTasks.HasTasks() ||
                    mThreadObserver->HasPendingEvents())) {
    // Process xpcom events first.
    while (MOZ_UNLIKELY(mThreadObserver->HasPendingEvents())) {
      mThreadObserver->ClearPendingEvents();
      MonitorAutoUnlock unlock(mThreadObserver->GetMonitor());
      bool processedEvent;
      do {
        rv = thread->ProcessNextEvent(false, &processedEvent);
      } while (NS_SUCCEEDED(rv) && processedEvent);
    }

    if (MOZ_UNLIKELY(TimeUntilFlush() == 0)) {
      // Flush time is up or flush has been forced, do it now.
      UnscheduleFlush();
      if (mPendingTasks.Prepare()) {
        {
          MonitorAutoUnlock unlockMonitor(mThreadObserver->GetMonitor());
          rv = mPendingTasks.Execute(this);
        }

        if (!mPendingTasks.Finalize(rv)) {
          mStatus = rv;
          NS_WARNING("localStorage DB access broken");
        }
      }
      NotifyFlushCompletion();
    } else if (MOZ_LIKELY(mPreloads.Length())) {
      nsAutoPtr<DBOperation> op(mPreloads[0]);
      mPreloads.RemoveElementAt(0);
      {
        MonitorAutoUnlock unlockMonitor(mThreadObserver->GetMonitor());
        op->PerformAndFinalize(this);
      }

      if (op->Type() == DBOperation::opPreloadUrgent) {
        SetDefaultPriority(); // urgent preload unscheduled
      }
    } else if (MOZ_UNLIKELY(!mStopIOThread)) {
      lockMonitor.Wait(TimeUntilFlush());
    }
  } // thread loop

  mStatus = ShutdownDatabase();

  if (threadInternal) {
    threadInternal->SetObserver(nullptr);
  }
}
Exemple #13
0
void SlicesRotator::RotateToPoint( SliceNavigationController *rotationPlaneSNC,
                                   SliceNavigationController *rotatedPlaneSNC,
                                   const Point3D &point, bool linked )
{
    MITK_WARN << "Deprecated function! Use SliceNavigationController::ReorientSlices() instead";

    SliceNavigationController *thirdSNC = NULL;

    SNCVector::iterator iter;
    for ( iter = m_RotatableSNCs.begin(); iter != m_RotatableSNCs.end(); ++iter )
    {
        if ( ((*iter) != rotationPlaneSNC)
                && ((*iter) != rotatedPlaneSNC) )
        {
            thirdSNC = *iter;
            break;
        }
    }

    if ( thirdSNC == NULL )
    {
        return;
    }

    const PlaneGeometry *rotationPlane = rotationPlaneSNC->GetCurrentPlaneGeometry();
    const PlaneGeometry *rotatedPlane = rotatedPlaneSNC->GetCurrentPlaneGeometry();
    const PlaneGeometry *thirdPlane = thirdSNC->GetCurrentPlaneGeometry();

    if ( (rotationPlane == NULL) || (rotatedPlane == NULL)
            || (thirdPlane == NULL) )
    {
        return;
    }

    if ( rotatedPlane->DistanceFromPlane( point ) < 0.001 )
    {
        // Skip irrelevant rotations
        return;
    }

    Point3D projectedPoint;
    Line3D intersection;
    Point3D rotationCenter;

    if ( !rotationPlane->Project( point, projectedPoint )
            || !rotationPlane->IntersectionLine( rotatedPlane, intersection )
            || !thirdPlane->IntersectionPoint( intersection, rotationCenter ) )
    {
        return;
    }

    // All pre-requirements are met; execute the rotation

    Point3D referencePoint = intersection.Project( projectedPoint );

    Vector3D toProjected = referencePoint - rotationCenter;
    Vector3D toCursor    = projectedPoint - rotationCenter;

    // cross product: | A x B | = |A| * |B| * sin(angle)
    Vector3D axisOfRotation;
    vnl_vector_fixed< ScalarType, 3 > vnlDirection =
        vnl_cross_3d( toCursor.GetVnlVector(), toProjected.GetVnlVector() );
    axisOfRotation.SetVnlVector( vnlDirection );

    // scalar product: A * B = |A| * |B| * cos(angle)
    // tan = sin / cos
    ScalarType angle = - atan2(
                           (double)(axisOfRotation.GetNorm()),
                           (double)(toCursor * toProjected) );
    angle *= 180.0 / vnl_math::pi;

    // create RotationOperation and apply to all SNCs that should be rotated
    RotationOperation op(OpROTATE, rotationCenter, axisOfRotation, angle);

    if ( !linked )
    {
        BaseRenderer *renderer = rotatedPlaneSNC->GetRenderer();
        if ( renderer == NULL )
        {
            return;
        }

        DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry();

        Point2D point2DWorld, point2DDisplayPre, point2DDisplayPost;
        displayGeometry->Map( rotationCenter, point2DWorld );
        displayGeometry->WorldToDisplay( point2DWorld, point2DDisplayPre );

        TimeGeometry *timeGeometry= rotatedPlaneSNC->GetCreatedWorldGeometry();
        if ( !timeGeometry )
        {
            return;
        }

        timeGeometry->ExecuteOperation( &op );

        displayGeometry->Map( rotationCenter, point2DWorld );
        displayGeometry->WorldToDisplay( point2DWorld, point2DDisplayPost );
        Vector2D vector2DDisplayDiff = point2DDisplayPost - point2DDisplayPre;

        //Vector2D origin = displayGeometry->GetOriginInMM();

        displayGeometry->MoveBy( vector2DDisplayDiff );

        rotatedPlaneSNC->SendCreatedWorldGeometryUpdate();
    }
    else
    {
        SNCVector::iterator iter;
        for ( iter = m_RotatableSNCs.begin(); iter != m_RotatableSNCs.end(); ++iter )
        {
            BaseRenderer *renderer = (*iter)->GetRenderer();
            if ( renderer == NULL )
            {
                continue;
            }

            DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry();

            Point2D point2DWorld, point2DDisplayPre, point2DDisplayPost;
            displayGeometry->Map( rotationCenter, point2DWorld );
            displayGeometry->WorldToDisplay( point2DWorld, point2DDisplayPre );

            TimeGeometry* timeGeometry = (*iter)->GetCreatedWorldGeometry();
            if ( !timeGeometry )
            {
                continue;
            }

            timeGeometry->ExecuteOperation( &op );

            displayGeometry->Map( rotationCenter, point2DWorld );
            displayGeometry->WorldToDisplay( point2DWorld, point2DDisplayPost );
            Vector2D vector2DDisplayDiff = point2DDisplayPost - point2DDisplayPre;

            //Vector2D origin = displayGeometry->GetOriginInMM();

            displayGeometry->MoveBy( vector2DDisplayDiff );

            (*iter)->SendCreatedWorldGeometryUpdate();
        }
    }
} // end RotateToPoint
CIMHandleIndicationResponseMessage*
IndicationHandlerService::_handleIndication(
    CIMHandleIndicationRequestMessage* request)
{
    PEG_METHOD_ENTER(TRC_IND_HANDLER,
        "IndicationHandlerService::_handleIndication()");

    Boolean handleIndicationSuccess = true;
    CIMException cimException =
        PEGASUS_CIM_EXCEPTION(CIM_ERR_SUCCESS, String::EMPTY);

    CIMName className = request->handlerInstance.getClassName();
    CIMNamespaceName nameSpace = request->nameSpace;

    CIMInstance indication = request->indicationInstance;
    CIMInstance handler = request->handlerInstance;

    PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4,
        "Handler service received %s Indication %s for %s:%s.%s Handler",
        (const char*)(indication.getClassName().getString().getCString()),
        (const char*)(request->messageId.getCString()),
        (const char*)(request->nameSpace.getString().getCString()),
        (const char*)(handler.getClassName().getString().getCString()),
        (const char*)(handler.getProperty(handler.findProperty(
        PEGASUS_PROPERTYNAME_NAME)).getValue().toString().getCString())));
    Uint32 pos = PEG_NOT_FOUND;

    if (className.equal (PEGASUS_CLASSNAME_INDHANDLER_CIMXML) ||
        className.equal (PEGASUS_CLASSNAME_LSTNRDST_CIMXML))
    {
        pos = handler.findProperty(PEGASUS_PROPERTYNAME_LSTNRDST_DESTINATION);

        if (pos == PEG_NOT_FOUND)
        {
            cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED,
                MessageLoaderParms(
                    "HandlerService.IndicationHandlerService."
                        "CIMXML_HANDLER_WITHOUT_DESTINATION",
                    "CIMXml Handler missing Destination property"));
            handleIndicationSuccess = false;
        }
        else
        {
            CIMProperty prop = handler.getProperty(pos);
            String destination = prop.getValue().toString();

            if (destination.size() == 0)
            {
                cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED,
                    MessageLoaderParms(
                        "HandlerService.IndicationHandlerService."
                            "INVALID_DESTINATION",
                        "invalid destination"));
                handleIndicationSuccess = false;
            }
//compared index 10 is not :
            else if (destination.subString(0, 10) == String("localhost/"))
            {
                Uint32 exportServer =
                    find_service_qid(PEGASUS_QUEUENAME_EXPORTREQDISPATCHER);

                // Listener is build with Cimom, so send message to ExportServer
               AutoPtr<CIMExportIndicationRequestMessage> exportmessage( 
                    new CIMExportIndicationRequestMessage(
                        XmlWriter::getNextMessageId(),
                        //taking localhost/CIMListener portion out from reg
                        destination.subString(21),
                        indication,
                        QueueIdStack(exportServer, getQueueId()),
                        String::EMPTY,
                        String::EMPTY));

                exportmessage->operationContext.insert(
                    IdentityContainer(String::EMPTY));
                exportmessage->operationContext.set(
                    request->operationContext.get(
                    ContentLanguageListContainer::NAME)); 
                AutoPtr<AsyncOpNode> op( this->get_op());

                AutoPtr<AsyncLegacyOperationStart> asyncRequest(
                    new AsyncLegacyOperationStart(
                    op.get(),
                    exportServer,
                    exportmessage.get()));

                exportmessage.release();

                PEG_TRACE((TRC_IND_HANDLER, Tracer::LEVEL4,
                    "Indication handler forwarding message to %s",
                        ((MessageQueue::lookup(exportServer)) ?
                            ((MessageQueue::lookup(exportServer))->
                                getQueueName()):
                            "BAD queue name")));
                PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4,
                    "Sending %s Indication %s to destination %s",
                    (const char*) (indication.getClassName().getString().
                    getCString()),
                    (const char*)(request->messageId.getCString()),
                    (const char*) destination.getCString()));

                //SendAsync(op,
                //      exportServer[0],
                //      IndicationHandlerService::_handleIndicationCallBack,
                //      this,
                //      (void *)request->queueIds.top());
                AutoPtr<AsyncReply> asyncReply(SendWait(asyncRequest.get()));
                asyncRequest.release();

                // Return the ExportIndication results in HandleIndication 
                //response
                AutoPtr<CIMExportIndicationResponseMessage> exportResponse(
                    reinterpret_cast<CIMExportIndicationResponseMessage *>(
                        (static_cast<AsyncLegacyOperationResult *>(
                            asyncReply.get()))->get_result()));
                cimException = exportResponse->cimException;

                this->return_op(op.release());
            }
            else
            {
                handleIndicationSuccess = _loadHandler(request, cimException);
            }
        }
    }
    else if (className.equal (PEGASUS_CLASSNAME_INDHANDLER_SNMP))
    {
        pos = handler.findProperty(PEGASUS_PROPERTYNAME_LSTNRDST_TARGETHOST);

        if (pos == PEG_NOT_FOUND)
        {
            cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED,
                MessageLoaderParms(
                    "HandlerService.IndicationHandlerService."
                        "SNMP_HANDLER_WITHOUT_TARGETHOST",
                    "Snmp Handler missing Targethost property"));
            handleIndicationSuccess = false;
        }
        else
        {
            CIMProperty prop = handler.getProperty(pos);
            String destination = prop.getValue().toString();

            if (destination.size() == 0)
            {
                cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED,
                    MessageLoaderParms(
                        "HandlerService.IndicationHandlerService."
                            "INVALID_TARGETHOST",
                        "invalid targethost"));
                handleIndicationSuccess = false;
            }
            else
            {
                handleIndicationSuccess = _loadHandler(request, cimException);
            }
        }
    }
    else if ((className.equal (PEGASUS_CLASSNAME_LSTNRDST_SYSTEM_LOG)) ||
             (className.equal (PEGASUS_CLASSNAME_LSTNRDST_EMAIL)))
    {
        handleIndicationSuccess = _loadHandler(request, cimException);
    }

    // no success to handle indication
    // somewhere an exception message was build
    // time to write the error message to the log
    if (!handleIndicationSuccess)
    {
        Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::WARNING,
            MessageLoaderParms(
                "HandlerService.IndicationHandlerService."
                    "INDICATION_DELIVERY_FAILED",
                "Failed to deliver an indication: $0",
                cimException.getMessage()));
    }

    CIMHandleIndicationResponseMessage* response =
        dynamic_cast<CIMHandleIndicationResponseMessage*>(
            request->buildResponse());
    response->cimException = cimException;

    delete request;
    PEG_METHOD_EXIT();
    return response;
}
Exemple #15
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])
{
    double* m_dict;
    double* m_x;

    check_num_input_args(nrhs, 2, 6);
    check_num_output_args(nlhs, 0,1);

    check_is_double_matrix(A_IN, func_name, "A");
    check_is_double_matrix(B_IN,  func_name, "b");

    int max_iters = 0;
    if (nrhs > 2){
        check_is_double_scalar(ITER_IN,  func_name, "max_iters");
        // Read the value of max_iters
        max_iters = mxGetScalar(ITER_IN);
    }

    double tolerance = 0;
    if (nrhs > 3){
        check_is_double_scalar(EPS_IN,  func_name, "tolerance");
        tolerance  = mxGetScalar(EPS_IN);
    }

    int sparse_output = 1;
    if (nrhs > 4){
        check_is_double_scalar(SPARSE_IN, func_name,"sparse");
        sparse_output = (int) mxGetScalar(SPARSE_IN);
    }

    int verbose = 0;
    if (nrhs > 5){
        check_is_double_scalar(VERBOSE, func_name, "verbose");
        verbose = (int) mxGetScalar(VERBOSE);
    }

    m_dict = mxGetPr(A_IN);
    m_x = mxGetPr(B_IN);

    size_t M, N, S;
    // Number of signal space dimension
    M = mxGetM(A_IN);
    // Number of atoms
    N = mxGetN(A_IN);
    if (M != mxGetM(B_IN)){
        mexErrMsgTxt("Dimensions mismatch");
    }
    if (M != N) {
        mexErrMsgTxt("A must be symmetric positive definite");
    }
    // Number of signals
    S = mxGetN(B_IN);
    if (S != 1) {
        mexErrMsgTxt("Only one vector supported at the moment");
    }
    if(verbose){
        mexPrintf("M: %d, N:%d, S: %d, max_iters: %d, tolerance: %e, sparse: %d, verbose: %d\n",
         M, N, S, max_iters, tolerance, sparse_output, verbose);
    }
    // Create Sparse Representation Vector
    spx::MxArray op(A_IN);
    spx::CongugateGradients cg (op);
    if (max_iters > 0) {
        cg.set_max_iterations(max_iters);
    }
    if (tolerance > 0) {
        cg.set_tolerance(tolerance);
    }
    if (verbose > 0){
        cg.set_verbose( (spx::VERBOSITY) verbose);
    }
    cg(m_x);
    X_OUT = spx::d_vec_to_mx_array(cg.get_x());
}
Exemple #16
0
int mainTest(int argNumber, char* argString[])
{
    //Init Logger
    Logger::getInstance()->setLoggingLevel(eINFO);

    //We create a folder for background substraction configuration file. BGSLib will crash if that folder doesn't exist.
    boost::filesystem::create_directory("config");

    //We load the tracking configuration
    po::options_description fileConfig("Configuration file options");
    po::variables_map vm = LoadConfigurationSettings(argNumber, argString, fileConfig);
    if(vm.count("logging-level") >0)
    {
        unsigned int level = vm["logging-level"].as<unsigned int>();
        if(level >= 0 && level <= eNONE)
            Logger::getInstance()->setLoggingLevel(ELoggingLevel(level));
    }


    //We load the video
    bool overrideTotalNbFrame = false;
    unsigned int lastFrame = -1;
    InputFrameProviderIface* vfm = LoadVideo(vm, overrideTotalNbFrame, lastFrame);
    try
    {
        if(vfm && vfm->isOpen())
        {
            LOGINFO("Starting tracker");

            bool success = true;
            DrawableTimer dt;


            float pixelByMeter = 1;
            if(vm.count("scaleratio-filename") > 0 && vm["scaleratio-filename"].as<std::string>() != "none" && vm["scaleratio-filename"].as<std::string>() != "None")
            {
                success = Utils::IO::LoadScalar<float>(vm["scaleratio-filename"].as<std::string>(), pixelByMeter);
                if(!success)
                {
                    pixelByMeter = 1;
                    LOGWARNING("Can't load scale ratio file. Using 1px/m ratio");
                }
            }

            cv::Mat homography = cv::Mat::eye(3,3, CV_32FC1);
            if(vm.count("homography-filename") > 0 && vm["homography-filename"].as<std::string>() != "none" && vm["homography-filename"].as<std::string>() != "None")
            {
                success = Utils::IO::LoadMatrix<double>(vm["homography-filename"].as<std::string>(), homography);
                if(!success)
                {
                    homography = cv::Mat::eye(3,3, CV_32FC1);
                    LOGWARNING("Can't load homography file. Using identity.");
                }
            }
            cv::Mat mask;

            if(vm.count("mask-filename") > 0 && vm["mask-filename"].as<std::string>() != "none" && vm["mask-filename"].as<std::string>() != "None")
            {
                mask = cv::imread(vm["mask-filename"].as<std::string>());
                cv::cvtColor(mask, mask, CV_BGR2GRAY);
            }
            else
            {
                mask = cv::Mat(vfm->getHeight(), vfm->getWidth(), CV_8UC1);
                mask.setTo(cv::Scalar(255,255,255));
            }


            /*if(vm.count("aerialview-filename") > 0)
            {
                std::string aerialfn(vm["aerialview-filename"].as<std::string>());
                const cv::Mat aerialView = cv::imread(aerialfn);
            }*/


            DrawingFlags drawFlags = LoadDrawingFlags(vm);
            BlobTrackerAlgorithmParams algoParams = LoadTrackerParams(vm);
            DisplayInstruction();

            ApplicationContext context(mask, homography,(float)vfm->getNbFPS(), pixelByMeter, drawFlags, algoParams, vm["record-bgs"].as<bool>(), vfm);
            TrackerPersistance op(&context, vm["object-sqlite-filename"].as<std::string>());
            op.init();
            std::string bgsRecord = vm["bgs-filepath"].as<std::string>();
            context.setBGSPath(bgsRecord);
            std::string bgsType = vm["bgs-type"].as<std::string>();

            Tracker t(&context, bgsType);
            if(bgsType == "PlaybackBGS" && vm.count("bgs-filepath") > 0)
            {
                IBGS* bgs = t.getBlobDetector()->getBGS();
                PlaybackBGS* pbBGS = dynamic_cast<PlaybackBGS*>(bgs);
                if(pbBGS)
                    pbBGS->setPath(bgsRecord);
//                std::cout<<"remove playBackBgs\n";
//                exit(-1);
            }

            //bgs-filepath
            cv::Mat m;
            bool stepByStep = false;
            bool quit = false;
            bool displayMemory = vm["draw-memory"].as<bool>();


            if(!vfm->isOpen())
            {
                LOGERROR("Can't open video file");
                return 0;
            }
            int nbFrameProcess = 0;
            while(vfm->getNextFrame(m) && !quit && (!overrideTotalNbFrame || vfm->getNextFramePos() <= vfm->getNbFrame()) &&  (vfm->getNextFramePos() <= lastFrame || lastFrame == -1))
            {
                context.setCurrentFrame(m);
                dt.start();
                t.processFrame(m);
                dt.stop();
                if(context.getRefDrawingFlags()->mDrawFPS)
                    dt.drawFPS(m);

                cv::Mat trajectoryPictureClone = m.clone();
                if(drawFlags.mDrawPerspective)
                {
                    t.draw(m);
                    #ifdef _WIN32
                    if(displayMemory)
                    {
                        PROCESS_MEMORY_COUNTERS memCounter;
                        bool result = GetProcessMemoryInfo(GetCurrentProcess(), &memCounter, sizeof( memCounter ));
                        float nbMeg = memCounter.WorkingSetSize/(1048576.f);
                        cv::putText(m, Utils::String::toString(nbMeg)+ " Mo", cv::Point(0,m.rows-5), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0,255,255),2);
                    }
                    #endif
                    cv::imshow("Video", m);
                    int key;
                    if(stepByStep)
                    {
                        key = cv::waitKey();
                    }
                    else
                        key = cv::waitKey(1);

                    if(key == 's')
                    {
                        stepByStep = !stepByStep;
                    }
                    else if(key == 'm')
                    {
                        displayMemory = !displayMemory;
                    }
                    else if(key == 'q')
                    {
                        std::cout << "Quit was requested. Exiting...";
                        quit = true;
                    }
                    else
                        UpdateContextFromKeys(&context, key);
                }
                ++nbFrameProcess;
                if(nbFrameProcess %50 == 0)
                    std::cout << "Frame " << nbFrameProcess << std::endl;
            }
            delete vfm;
        }
        else
        {
            LOGWARNING("Config file not loaded");
            LOGINFO("Loaded options:\n" << getParameterDescription(fileConfig, vm));

            if (vm.count("help"))
            {
                std::cout << fileConfig << std::endl;
            }
        }
    }
    catch(std::exception& e)
    {
        LOGASSERT(false, "Unhandled exception: " << e.what());
    }



    Logger::getInstance()->cleanUp();
    return 0;
}
Exemple #17
0
method_id("add");
  ret(ieval(begin_splat(),
     arg(1), op("+"), arg(2), 
  end_splat()));
  

comment("see http://jsfiddle.net/4MmvW/1/");
Exemple #18
0
void async_console_read_line(boost::asio::windows::object_handle& object_handle, Handler handler)
{
	console_read_line_op<Handler> op(object_handle, handler);
}
Exemple #19
0
vector<ndim>& assign_op(vector<ndim>& a, const assign_t& t, oper_t op) {
  for (unsigned i = 0; i < ndim; ++i) {
    a[i] = op(t[i]);
  }
  return a;
}
Exemple #20
0
void invert_overlap(const int op_id, const int index_start) {
  operator * optr;
  void (*op)(spinor*,spinor*);
  static complex alpha={0,0};
  spinorPrecWS *ws;
  optr = &operator_list[op_id];
  op=&Dov_psi;

  /* here we need to (re)compute the kernel eigenvectors */
  /* for new gauge fields                                */

  if(g_proc_id == 0) {printf("# Not using even/odd preconditioning!\n"); fflush(stdout);}
  convert_eo_to_lexic(g_spinor_field[DUM_DERI], optr->sr0, optr->sr1);
  convert_eo_to_lexic(g_spinor_field[DUM_DERI+1], optr->prop0, optr->prop1);

  if(optr->solver == 13 ){
    optr->iterations = sumr(g_spinor_field[DUM_DERI+1],g_spinor_field[DUM_DERI] , optr->maxiter, optr->eps_sq);
  } 
  else if(optr->solver == 1 /* CG */) {

    gamma5(g_spinor_field[DUM_DERI+1], g_spinor_field[DUM_DERI], VOLUME);
  
    if(use_preconditioning==1 && g_precWS!=NULL){
      ws=(spinorPrecWS*)g_precWS;
      printf("# Using preconditioning (which one?)!\n");
    
      alpha.re=ws->precExpo[2];
      spinorPrecondition(g_spinor_field[DUM_DERI+1],g_spinor_field[DUM_DERI+1],ws,T,L,alpha,0,1);

      /* 	iter = cg_her(g_spinor_field[DUM_DERI], g_spinor_field[DUM_DERI+1], max_iter, precision,  */
      /* 		    rel_prec, VOLUME, &Q_pm_psi_prec); */
      optr->iterations = cg_her(g_spinor_field[DUM_DERI], g_spinor_field[DUM_DERI+1], optr->maxiter, optr->eps_sq,
				optr->rel_prec, VOLUME, &Qov_sq_psi_prec);
    
      alpha.re=ws->precExpo[0];
      spinorPrecondition(g_spinor_field[DUM_DERI],g_spinor_field[DUM_DERI],ws,T,L,alpha,0,1);
    
    } 
    else {
      printf("# Not using preconditioning (which one?)!\n");
      /* 	iter = cg_her(g_spinor_field[DUM_DERI], g_spinor_field[DUM_DERI+1], max_iter, precision,  */
      /* 		      rel_prec, VOLUME, &Q_pm_psi); */
      optr->iterations = cg_her(g_spinor_field[DUM_DERI], g_spinor_field[DUM_DERI+1], optr->maxiter, optr->eps_sq,
				optr->rel_prec, VOLUME, &Qov_sq_psi);
    }
  
  
    Qov_psi(g_spinor_field[DUM_DERI+1], g_spinor_field[DUM_DERI]);
  
    if(use_preconditioning == 1 && g_precWS!=NULL){
      ws=(spinorPrecWS*)g_precWS;
      alpha.re=ws->precExpo[1];
      spinorPrecondition(g_spinor_field[DUM_DERI+1],g_spinor_field[DUM_DERI+1],ws,T,L,alpha,0,1);
    }
  
  }
  
  op(g_spinor_field[4],g_spinor_field[DUM_DERI+1]);

  convert_eo_to_lexic(g_spinor_field[DUM_DERI], optr->sr0, optr->sr1);

  optr->reached_prec=diff_and_square_norm(g_spinor_field[4],g_spinor_field[DUM_DERI],VOLUME);
  
  convert_lexic_to_eo(optr->prop0, optr->prop1 , g_spinor_field[DUM_DERI+1]);

  return;
}
Exemple #21
0
	void request::parseHTTPHeader(const char *headln)
	{
#define op(a, b) \
if ((tmp = getfield(headln, b)) != NULL)\
{\
	a = (char *)malloc(strlen(tmp) + 1);\
	strcpy(a, tmp + strlen(b) + 2);\
	free(tmp);\
}
		char *tmp;
		this->header.recvtime = time(NULL);
		op(this->header.accept.accept, "Accept");
		op(this->header.accept.charset, "Accept-Charset");
		op(this->header.accept.encoding, "Accept-Encoding");
		op(this->header.accept.language, "Accept-Language");
		op(this->header.clientinfo.referer, "Referer");
		op(this->header.clientinfo.te, "TE");
		op(this->header.clientinfo.user_agent, "User-Agent");
		op(this->header.hostinfo.authorization, "Authorization");
		op(this->header.hostinfo.expect, "Expect");
		op(this->header.hostinfo.from, "From");
		op(this->header.hostinfo.host, "Host");
		op(this->header.netinfo.max_forwards, "Max-Forwards");
		op(this->header.netinfo.proxy_authorization, "Proxy-Authorization");
		op(this->header.netinfo.range, "Range");
		op(this->header.sectif.match, "If-Match");
		op(this->header.sectif.modified_since, "If-Modified-Since");
		op(this->header.sectif.none_match, "If-None-Match");
		op(this->header.sectif.range, "If-Range");
		op(this->header.sectif.unmodified_since, "If-Unmodified-Since");
#undef  op
	}
Exemple #22
0
/**
 * Parses the given string into a sequence of Tokens
 */
nsresult
txExprLexer::parse(const nsASingleFragmentString& aPattern)
{
  iterator start, end;
  start = aPattern.BeginReading(mPosition);
  aPattern.EndReading(end);

  //-- initialize previous token, this will automatically get
  //-- deleted when it goes out of scope
  Token nullToken(nullptr, nullptr, Token::NULL_TOKEN);

  Token::Type defType;
  Token* newToken = nullptr;
  Token* prevToken = &nullToken;
  bool isToken;

  while (mPosition < end) {

    defType = Token::CNAME;
    isToken = true;

    if (*mPosition == DOLLAR_SIGN) {
      if (++mPosition == end || !XMLUtils::isLetter(*mPosition)) {
        return NS_ERROR_XPATH_INVALID_VAR_NAME;
      }
      defType = Token::VAR_REFERENCE;
    } 
    // just reuse the QName parsing, which will use defType 
    // the token to construct

    if (XMLUtils::isLetter(*mPosition)) {
      // NCName, can get QName or OperatorName;
      //  FunctionName, NodeName, and AxisSpecifier may want whitespace,
      //  and are dealt with below
      start = mPosition;
      while (++mPosition < end && XMLUtils::isNCNameChar(*mPosition)) {
        /* just go */
      }
      if (mPosition < end && *mPosition == COLON) {
        // try QName or wildcard, might need to step back for axis
        if (++mPosition == end) {
          return NS_ERROR_XPATH_UNEXPECTED_END;
        }
        if (XMLUtils::isLetter(*mPosition)) {
          while (++mPosition < end && XMLUtils::isNCNameChar(*mPosition)) {
            /* just go */
          }
        }
        else if (*mPosition == '*' && defType != Token::VAR_REFERENCE) {
          // eat wildcard for NameTest, bail for var ref at COLON
          ++mPosition;
        }
        else {
          --mPosition; // step back
        }
      }
      if (nextIsOperatorToken(prevToken)) {
        nsDependentSubstring op(Substring(start, mPosition));
        if (nsGkAtoms::_and->Equals(op)) {
          defType = Token::AND_OP;
        }
        else if (nsGkAtoms::_or->Equals(op)) {
          defType = Token::OR_OP;
        }
        else if (nsGkAtoms::mod->Equals(op)) {
          defType = Token::MODULUS_OP;
        }
        else if (nsGkAtoms::div->Equals(op)) {
          defType = Token::DIVIDE_OP;
        }
        else {
          // XXX QUESTION: spec is not too precise
          // badops is sure an error, but is bad:ops, too? We say yes!
          return NS_ERROR_XPATH_OPERATOR_EXPECTED;
        }
      }
      newToken = new Token(start, mPosition, defType);
    }
    else if (isXPathDigit(*mPosition)) {
      start = mPosition;
      while (++mPosition < end && isXPathDigit(*mPosition)) {
        /* just go */
      }
      if (mPosition < end && *mPosition == '.') {
        while (++mPosition < end && isXPathDigit(*mPosition)) {
          /* just go */
        }
      }
      newToken = new Token(start, mPosition, Token::NUMBER);
    }
    else {
      switch (*mPosition) {
        //-- ignore whitespace
      case SPACE:
      case TX_TAB:
      case TX_CR:
      case TX_LF:
        ++mPosition;
        isToken = false;
        break;
      case S_QUOTE :
      case D_QUOTE :
        start = mPosition;
        while (++mPosition < end && *mPosition != *start) {
          // eat literal
        }
        if (mPosition == end) {
          mPosition = start;
          return NS_ERROR_XPATH_UNCLOSED_LITERAL;
        }
        newToken = new Token(start + 1, mPosition, Token::LITERAL);
        ++mPosition;
        break;
      case PERIOD:
        // period can be .., .(DIGITS)+ or ., check next
        if (++mPosition == end) {
          newToken = new Token(mPosition - 1, Token::SELF_NODE);
        }
        else if (isXPathDigit(*mPosition)) {
          start = mPosition - 1;
          while (++mPosition < end && isXPathDigit(*mPosition)) {
            /* just go */
          }
          newToken = new Token(start, mPosition, Token::NUMBER);
        }
        else if (*mPosition == PERIOD) {
          ++mPosition;
          newToken = new Token(mPosition - 2, mPosition, Token::PARENT_NODE);
        }
        else {
          newToken = new Token(mPosition - 1, Token::SELF_NODE);
        }
        break;
      case COLON: // QNames are dealt above, must be axis ident
        if (++mPosition >= end || *mPosition != COLON ||
            prevToken->mType != Token::CNAME) {
          return NS_ERROR_XPATH_BAD_COLON;
        }
        prevToken->mType = Token::AXIS_IDENTIFIER;
        ++mPosition;
        isToken = false;
        break;
      case FORWARD_SLASH :
        if (++mPosition < end && *mPosition == FORWARD_SLASH) {
          ++mPosition;
          newToken = new Token(mPosition - 2, mPosition, Token::ANCESTOR_OP);
        }
        else {
          newToken = new Token(mPosition - 1, Token::PARENT_OP);
        }
        break;
      case BANG : // can only be !=
        if (++mPosition < end && *mPosition == EQUAL) {
          ++mPosition;
          newToken = new Token(mPosition - 2, mPosition, Token::NOT_EQUAL_OP);
          break;
        }
        // Error ! is not not()
        return NS_ERROR_XPATH_BAD_BANG;
      case EQUAL:
        newToken = new Token(mPosition, Token::EQUAL_OP);
        ++mPosition;
        break;
      case L_ANGLE:
        if (++mPosition == end) {
          return NS_ERROR_XPATH_UNEXPECTED_END;
        }
        if (*mPosition == EQUAL) {
          ++mPosition;
          newToken = new Token(mPosition - 2, mPosition,
                               Token::LESS_OR_EQUAL_OP);
        }
        else {
          newToken = new Token(mPosition - 1, Token::LESS_THAN_OP);
        }
        break;
      case R_ANGLE:
        if (++mPosition == end) {
          return NS_ERROR_XPATH_UNEXPECTED_END;
        }
        if (*mPosition == EQUAL) {
          ++mPosition;
          newToken = new Token(mPosition - 2, mPosition,
                               Token::GREATER_OR_EQUAL_OP);
        }
        else {
          newToken = new Token(mPosition - 1, Token::GREATER_THAN_OP);
        }
        break;
      case HYPHEN :
        newToken = new Token(mPosition, Token::SUBTRACTION_OP);
        ++mPosition;
        break;
      case ASTERIX:
        if (nextIsOperatorToken(prevToken)) {
          newToken = new Token(mPosition, Token::MULTIPLY_OP);
        }
        else {
          newToken = new Token(mPosition, Token::CNAME);
        }
        ++mPosition;
        break;
      case L_PAREN:
        if (prevToken->mType == Token::CNAME) {
          const nsDependentSubstring& val = prevToken->Value();
          if (val.EqualsLiteral("comment")) {
            prevToken->mType = Token::COMMENT_AND_PAREN;
          }
          else if (val.EqualsLiteral("node")) {
            prevToken->mType = Token::NODE_AND_PAREN;
          }
          else if (val.EqualsLiteral("processing-instruction")) {
            prevToken->mType = Token::PROC_INST_AND_PAREN;
          }
          else if (val.EqualsLiteral("text")) {
            prevToken->mType = Token::TEXT_AND_PAREN;
          }
          else {
            prevToken->mType = Token::FUNCTION_NAME_AND_PAREN;
          }
          isToken = false;
        }
        else {
          newToken = new Token(mPosition, Token::L_PAREN);
        }
        ++mPosition;
        break;
      case R_PAREN:
        newToken = new Token(mPosition, Token::R_PAREN);
        ++mPosition;
        break;
      case L_BRACKET:
        newToken = new Token(mPosition, Token::L_BRACKET);
        ++mPosition;
        break;
      case R_BRACKET:
        newToken = new Token(mPosition, Token::R_BRACKET);
        ++mPosition;
        break;
      case COMMA:
        newToken = new Token(mPosition, Token::COMMA);
        ++mPosition;
        break;
      case AT_SIGN :
        newToken = new Token(mPosition, Token::AT_SIGN);
        ++mPosition;
        break;
      case PLUS:
        newToken = new Token(mPosition, Token::ADDITION_OP);
        ++mPosition;
        break;
      case VERT_BAR:
        newToken = new Token(mPosition, Token::UNION_OP);
        ++mPosition;
        break;
      default:
        // Error, don't grok character :-(
        return NS_ERROR_XPATH_ILLEGAL_CHAR;
      }
    }
    if (isToken) {
      NS_ENSURE_TRUE(newToken, NS_ERROR_OUT_OF_MEMORY);
      NS_ENSURE_TRUE(newToken != mLastItem, NS_ERROR_FAILURE);
      prevToken = newToken;
      addToken(newToken);
    }
  }

  // add a endToken to the list
  newToken = new Token(end, end, Token::END);
  if (!newToken) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  addToken(newToken);

  return NS_OK;
}
bool AffineInteractor3D
::ExecuteAction( Action *action, StateEvent const *stateEvent )
{
  bool ok = false;

  // Get data object
  BaseData *data = m_DataNode->GetData();
  if ( data == NULL )
  {
    MITK_ERROR << "No data object present!";
    return ok;
  }

  // Get Event and extract renderer
  const Event *event = stateEvent->GetEvent();
  BaseRenderer *renderer = NULL;
  vtkRenderWindow *renderWindow = NULL;
  vtkRenderWindowInteractor *renderWindowInteractor = NULL;
  vtkRenderer *currentVtkRenderer = NULL;
  vtkCamera *camera = NULL;

  if ( event != NULL )
  {
    renderer = event->GetSender();
    if ( renderer != NULL )
    {
      renderWindow = renderer->GetRenderWindow();
      if ( renderWindow != NULL )
      {
        renderWindowInteractor = renderWindow->GetInteractor();
        if ( renderWindowInteractor != NULL )
        {
          currentVtkRenderer = renderWindowInteractor
            ->GetInteractorStyle()->GetCurrentRenderer();
          if ( currentVtkRenderer != NULL )
          {
            camera = currentVtkRenderer->GetActiveCamera();
          }
        }
      }
    }
  }

  // Check if we have a DisplayPositionEvent
  const DisplayPositionEvent *dpe =
    dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
  if ( dpe != NULL )
  {
    m_CurrentPickedPoint = dpe->GetWorldPosition();
    m_CurrentPickedDisplayPoint = dpe->GetDisplayPosition();
  }

  // Get the timestep to also support 3D+t
  int timeStep = 0;
  ScalarType timeInMS = 0.0;
  if ( renderer != NULL )
  {
    timeStep = renderer->GetTimeStep( data );
    timeInMS = renderer->GetTime();
  }

  // If data is an mitk::Surface, extract it
  Surface *surface = dynamic_cast< Surface * >( data );
  vtkPolyData *polyData = NULL;
  if ( surface != NULL )
  {
    polyData = surface->GetVtkPolyData( timeStep );

    // Extract surface normal from surface (if existent, otherwise use default)
    vtkPointData *pointData = polyData->GetPointData();
    if ( pointData != NULL )
    {
      vtkDataArray *normal = polyData->GetPointData()->GetVectors( "planeNormal" );
      if ( normal != NULL )
      {
        m_ObjectNormal[0] = normal->GetComponent( 0, 0 );
        m_ObjectNormal[1] = normal->GetComponent( 0, 1 );
        m_ObjectNormal[2] = normal->GetComponent( 0, 2 );
      }
    }
  }

  // Get geometry object
  m_Geometry = data->GetGeometry( timeStep );


  // Make sure that the data (if time-resolved) has enough entries;
  // if not, create the required extra ones (empty)
  data->Expand( timeStep+1 );


  switch (action->GetActionId())
  {
  case AcDONOTHING:
    ok = true;
    break;


  case AcCHECKOBJECT:
    {
      // Re-enable VTK interactor (may have been disabled previously)
      if ( renderWindowInteractor != NULL )
      {
        renderWindowInteractor->Enable();
      }

      // Check if we have a DisplayPositionEvent
      const DisplayPositionEvent *dpe =
        dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
      if ( dpe == NULL )
      {
        ok = true;
        break;
      }

      // Check if an object is present at the current mouse position
      DataNode *pickedNode = dpe->GetPickedObjectNode();
      StateEvent *newStateEvent;
      if ( pickedNode == m_DataNode )
      {
        // Yes: object will be selected
        newStateEvent = new StateEvent( EIDYES );
      }
      else
      {
        // No: back to start state
        newStateEvent = new StateEvent( EIDNO );
      }

      this->HandleEvent( newStateEvent );

      ok = true;
      break;
    }

  case AcDESELECTOBJECT:
    {
      // Color object white
      m_DataNode->SetColor( 1.0, 1.0, 1.0 );
      RenderingManager::GetInstance()->RequestUpdateAll();

      // Colorize surface / wireframe as inactive
      this->ColorizeSurface( polyData,
        m_CurrentPickedPoint, -1.0 );

      ok = true;
      break;
    }

  case AcSELECTPICKEDOBJECT:
    {
      // Color object red
      m_DataNode->SetColor( 1.0, 0.0, 0.0 );
      RenderingManager::GetInstance()->RequestUpdateAll();

      // Colorize surface / wireframe dependend on distance from picked point
      this->ColorizeSurface( polyData,
        m_CurrentPickedPoint, 0.0 );

      ok = true;
      break;
    }

  case AcINITMOVE:
    {
      // Disable VTK interactor until MITK interaction has been completed
      if ( renderWindowInteractor != NULL )
      {
        renderWindowInteractor->Disable();
      }

      // Check if we have a DisplayPositionEvent
      const DisplayPositionEvent *dpe =
        dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
      if ( dpe == NULL )
      {
        ok = true;
        break;
      }

      //DataNode *pickedNode = dpe->GetPickedObjectNode();

      m_InitialPickedPoint = m_CurrentPickedPoint;
      m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;

      if ( currentVtkRenderer != NULL )
      {
        vtkInteractorObserver::ComputeDisplayToWorld(
          currentVtkRenderer,
          m_InitialPickedDisplayPoint[0],
          m_InitialPickedDisplayPoint[1],
          0.0, //m_InitialInteractionPickedPoint[2],
          m_InitialPickedPointWorld );
      }


      // Make deep copy of current Geometry3D of the plane
      data->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
      m_OriginalGeometry = static_cast< BaseGeometry * >(
        data->GetGeometry( timeStep )->Clone().GetPointer() );

      ok = true;
      break;
    }

  case AcMOVE:
    {
      // Check if we have a DisplayPositionEvent
      const DisplayPositionEvent *dpe =
        dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() );
      if ( dpe == NULL )
      {
        ok = true;
        break;
      }

      if ( currentVtkRenderer != NULL )
      {
        vtkInteractorObserver::ComputeDisplayToWorld(
          currentVtkRenderer,
          m_CurrentPickedDisplayPoint[0],
          m_CurrentPickedDisplayPoint[1],
          0.0, //m_InitialInteractionPickedPoint[2],
          m_CurrentPickedPointWorld );
      }


      Vector3D interactionMove;
      interactionMove[0] = m_CurrentPickedPointWorld[0] - m_InitialPickedPointWorld[0];
      interactionMove[1] = m_CurrentPickedPointWorld[1] - m_InitialPickedPointWorld[1];
      interactionMove[2] = m_CurrentPickedPointWorld[2] - m_InitialPickedPointWorld[2];

      if ( m_InteractionMode == INTERACTION_MODE_TRANSLATION )
      {
        Point3D origin = m_OriginalGeometry->GetOrigin();

        Vector3D transformedObjectNormal;
        data->GetGeometry( timeStep )->IndexToWorld(
          m_ObjectNormal, transformedObjectNormal );

        data->GetGeometry( timeStep )->SetOrigin(
          origin + transformedObjectNormal * (interactionMove * transformedObjectNormal) );
      }
      else if ( m_InteractionMode == INTERACTION_MODE_ROTATION )
      {
        if ( camera )
        {
          double vpn[3];
          camera->GetViewPlaneNormal( vpn );

          Vector3D viewPlaneNormal;
          viewPlaneNormal[0] = vpn[0];
          viewPlaneNormal[1] = vpn[1];
          viewPlaneNormal[2] = vpn[2];

          Vector3D rotationAxis =
            itk::CrossProduct( viewPlaneNormal, interactionMove );
          rotationAxis.Normalize();

          int *size = currentVtkRenderer->GetSize();
          double l2 =
            (m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) *
            (m_CurrentPickedDisplayPoint[0] - m_InitialPickedDisplayPoint[0]) +
            (m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]) *
            (m_CurrentPickedDisplayPoint[1] - m_InitialPickedDisplayPoint[1]);

          double rotationAngle = 360.0 * sqrt(l2/(size[0]*size[0]+size[1]*size[1]));

          // Use center of data bounding box as center of rotation
          Point3D rotationCenter = m_OriginalGeometry->GetCenter();;

          // Reset current Geometry3D to original state (pre-interaction) and
          // apply rotation
          RotationOperation op( OpROTATE, rotationCenter, rotationAxis, rotationAngle );
          BaseGeometry::Pointer newGeometry = static_cast< BaseGeometry * >(
            m_OriginalGeometry->Clone().GetPointer() );
          newGeometry->ExecuteOperation( &op );
          data->SetClonedGeometry(newGeometry, timeStep);
        }
      }

      RenderingManager::GetInstance()->RequestUpdateAll();
      ok = true;
      break;
    }



  default:
    return Superclass::ExecuteAction( action, stateEvent );
  }

  return ok;
}
	static void make_update_group_qqnumber_op(boost::shared_ptr<WebQQ> webqq, boost::shared_ptr<qqGroup> group, webqq::webqq_handler_t handler)
	{
		update_group_qqnumber_op op(webqq, group, handler);
	}
Exemple #25
0
void Game_Loop::update_state_stack() {
  for (auto op : stack_ops)
    op();
  stack_ops.clear();
}
HeapWord* GenCollectorPolicy::mem_allocate_work(size_t size,
                                        bool is_tlab,
                                        bool* gc_overhead_limit_was_exceeded) {
  GenCollectedHeap *gch = GenCollectedHeap::heap();

  debug_only(gch->check_for_valid_allocation_state());
  assert(gch->no_gc_in_progress(), "Allocation during gc not allowed");

  // In general gc_overhead_limit_was_exceeded should be false so
  // set it so here and reset it to true only if the gc time
  // limit is being exceeded as checked below.
  *gc_overhead_limit_was_exceeded = false;

  HeapWord* result = NULL;

  // Loop until the allocation is satisified,
  // or unsatisfied after GC.
  for (int try_count = 1; /* return or throw */; try_count += 1) {
    HandleMark hm; // discard any handles allocated in each iteration

    // First allocation attempt is lock-free.
    Generation *gen0 = gch->get_gen(0);
    assert(gen0->supports_inline_contig_alloc(),
      "Otherwise, must do alloc within heap lock");
    if (gen0->should_allocate(size, is_tlab)) {
      result = gen0->par_allocate(size, is_tlab);
      if (result != NULL) {
        assert(gch->is_in_reserved(result), "result not in heap");
        return result;
      }
    }
    unsigned int gc_count_before;  // read inside the Heap_lock locked region
    {
      MutexLocker ml(Heap_lock);
      if (PrintGC && Verbose) {
        gclog_or_tty->print_cr("TwoGenerationCollectorPolicy::mem_allocate_work:"
                      " attempting locked slow path allocation");
      }
      // Note that only large objects get a shot at being
      // allocated in later generations.
      bool first_only = ! should_try_older_generation_allocation(size);

      result = gch->attempt_allocation(size, is_tlab, first_only);
      if (result != NULL) {
        assert(gch->is_in_reserved(result), "result not in heap");
        return result;
      }

      if (GC_locker::is_active_and_needs_gc()) {
        if (is_tlab) {
          return NULL;  // Caller will retry allocating individual object
        }
        if (!gch->is_maximal_no_gc()) {
          // Try and expand heap to satisfy request
          result = expand_heap_and_allocate(size, is_tlab);
          // result could be null if we are out of space
          if (result != NULL) {
            return result;
          }
        }

        // If this thread is not in a jni critical section, we stall
        // the requestor until the critical section has cleared and
        // GC allowed. When the critical section clears, a GC is
        // initiated by the last thread exiting the critical section; so
        // we retry the allocation sequence from the beginning of the loop,
        // rather than causing more, now probably unnecessary, GC attempts.
        JavaThread* jthr = JavaThread::current();
        if (!jthr->in_critical()) {
          MutexUnlocker mul(Heap_lock);
          // Wait for JNI critical section to be exited
          GC_locker::stall_until_clear();
          continue;
        } else {
          if (CheckJNICalls) {
            fatal("Possible deadlock due to allocating while"
                  " in jni critical section");
          }
          return NULL;
        }
      }

      // Read the gc count while the heap lock is held.
      gc_count_before = Universe::heap()->total_collections();
    }

    VM_GenCollectForAllocation op(size,
                                  is_tlab,
                                  gc_count_before);
    VMThread::execute(&op);
    if (op.prologue_succeeded()) {
      result = op.result();
      if (op.gc_locked()) {
         assert(result == NULL, "must be NULL if gc_locked() is true");
         continue;  // retry and/or stall as necessary
      }

      // Allocation has failed and a collection
      // has been done.  If the gc time limit was exceeded the
      // this time, return NULL so that an out-of-memory
      // will be thrown.  Clear gc_overhead_limit_exceeded
      // so that the overhead exceeded does not persist.

      const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
      const bool softrefs_clear = all_soft_refs_clear();
      assert(!limit_exceeded || softrefs_clear, "Should have been cleared");
      if (limit_exceeded && softrefs_clear) {
        *gc_overhead_limit_was_exceeded = true;
        size_policy()->set_gc_overhead_limit_exceeded(false);
        if (op.result() != NULL) {
          CollectedHeap::fill_with_object(op.result(), size);
        }
        return NULL;
      }
      assert(result == NULL || gch->is_in_reserved(result),
             "result not in heap");
      return result;
    }

    // Give a warning if we seem to be looping forever.
    if ((QueuedAllocationWarningCount > 0) &&
        (try_count % QueuedAllocationWarningCount == 0)) {
          warning("TwoGenerationCollectorPolicy::mem_allocate_work retries %d times \n\t"
                  " size=%d %s", try_count, size, is_tlab ? "(TLAB)" : "");
    }
  }
}
Exemple #27
0
TEUCHOS_UNIT_TEST(interlaced_op, test)
{
#ifdef HAVE_MPI
   Teuchos::RCP<const Epetra_Comm> comm = Teuchos::rcp(new Epetra_MpiComm(MPI_COMM_WORLD));
#else
   Teuchos::RCP<const Epetra_Comm> comm = Teuchos::rcp(new Epetra_SerialComm);
#endif

   //int rank = comm->MyPID();
   int numProc = comm->NumProc();

   int num_KL = 1;
   int porder = 5;
   bool full_expansion = false;

   Teuchos::RCP<const Stokhos::CompletePolynomialBasis<int,double> > basis = buildBasis(num_KL,porder);
   Teuchos::RCP<Stokhos::Sparse3Tensor<int,double> > Cijk;
   Teuchos::RCP<Stokhos::ParallelData> sg_parallel_data;
   Teuchos::RCP<Stokhos::OrthogPolyExpansion<int,double> > expansion; 
   {
      if(full_expansion)
         Cijk = basis->computeTripleProductTensor();
      else
        Cijk = basis->computeLinearTripleProductTensor();
   
      Teuchos::ParameterList parallelParams;
      parallelParams.set("Number of Spatial Processors", numProc);
      sg_parallel_data = Teuchos::rcp(new Stokhos::ParallelData(basis, Cijk, comm,
                                                                parallelParams));

      expansion = Teuchos::rcp(new Stokhos::AlgebraicOrthogPolyExpansion<int,double>(basis,
		 							             Cijk));
   }
   Teuchos::RCP<const EpetraExt::MultiComm> sg_comm = sg_parallel_data->getMultiComm();

   // determinstic PDE graph
   Teuchos::RCP<Epetra_Map> determRowMap = Teuchos::rcp(new Epetra_Map(-1,10,0,*comm));
   Teuchos::RCP<Epetra_CrsGraph> determGraph = Teuchos::rcp(new Epetra_CrsGraph(Copy,*determRowMap,1));
   for(int row=0;row<determRowMap->NumMyElements();row++) {
      int gid = determRowMap->GID(row);
      determGraph->InsertGlobalIndices(gid,1,&gid);
   }
   for(int row=1;row<determRowMap->NumMyElements()-1;row++) {
      int gid = determRowMap->GID(row);
      int indices[2] = {gid-1,gid+1};
      determGraph->InsertGlobalIndices(gid,2,indices);
   }
   determGraph->FillComplete();
   
   Teuchos::RCP<Teuchos::ParameterList> params = Teuchos::rcp(new Teuchos::ParameterList);
   params->set("Scale Operator by Inverse Basis Norms", false);
   params->set("Include Mean", true);
   params->set("Only Use Linear Terms", false);

   Teuchos::RCP<Stokhos::EpetraSparse3Tensor> epetraCijk = 
         Teuchos::rcp(new Stokhos::EpetraSparse3Tensor(basis,Cijk,sg_comm));
   Teuchos::RCP<Stokhos::EpetraOperatorOrthogPoly> W_sg_blocks = 
     Teuchos::rcp(new Stokhos::EpetraOperatorOrthogPoly(basis, epetraCijk->getStochasticRowMap(), determRowMap, determRowMap, sg_comm));
   for(int i=0; i<W_sg_blocks->size(); i++) {
      Teuchos::RCP<Epetra_CrsMatrix> crsMat = Teuchos::rcp(new Epetra_CrsMatrix(Copy,*determGraph));
      crsMat->PutScalar(1.0 + i);
      W_sg_blocks->setCoeffPtr(i,crsMat); // allocate a bunch of matrices   
   }

   Teuchos::RCP<const Epetra_Map> sg_map = 
     Teuchos::rcp(EpetraExt::BlockUtility::GenerateBlockMap(
		    *determRowMap, *(epetraCijk->getStochasticRowMap()), 
		    *(epetraCijk->getMultiComm())));

   // build an interlaced operator (object under test) and a benchmark
   // fully assembled operator
   ///////////////////////////////////////////////////////////////////////

   Stokhos::InterlacedOperator op(sg_comm,basis,epetraCijk,determGraph,params);
   op.PutScalar(0.0);
   op.setupOperator(W_sg_blocks);  

   Stokhos::FullyAssembledOperator full_op(sg_comm,basis,epetraCijk,determGraph,sg_map,sg_map,params);
   full_op.PutScalar(0.0);
   full_op.setupOperator(W_sg_blocks);  

   // here we test interlaced operator against the fully assembled operator
   ///////////////////////////////////////////////////////////////////////
   bool result = true;
   for(int i=0;i<100;i++) {
      // build vector for fully assembled operator (blockwise)
      Teuchos::RCP<Stokhos::EpetraVectorOrthogPoly> x_vec_blocks = 
            Teuchos::rcp(new Stokhos::EpetraVectorOrthogPoly(basis,epetraCijk->getStochasticRowMap(),determRowMap,epetraCijk->getMultiComm()));
      Teuchos::RCP<Stokhos::EpetraVectorOrthogPoly> f_vec_blocks = 
            Teuchos::rcp(new Stokhos::EpetraVectorOrthogPoly(basis,epetraCijk->getStochasticRowMap(),determRowMap,epetraCijk->getMultiComm()));
      Teuchos::RCP<Epetra_Vector> x_vec_blocked = x_vec_blocks->getBlockVector(); 
      Teuchos::RCP<Epetra_Vector> f_vec_blocked = f_vec_blocks->getBlockVector(); 
      x_vec_blocked->Random();       // build an initial vector
      f_vec_blocked->PutScalar(0.0);

      // build interlaced vectors
      Teuchos::RCP<Epetra_Vector> x_vec_inter = Teuchos::rcp(new Epetra_Vector(op.OperatorDomainMap()));
      Teuchos::RCP<Epetra_Vector> f_vec_inter = Teuchos::rcp(new Epetra_Vector(op.OperatorRangeMap()));
      Teuchos::RCP<Epetra_Vector> f_vec_blk_inter = Teuchos::rcp(new Epetra_Vector(op.OperatorRangeMap()));
      Stokhos::SGModelEvaluator_Interlaced::copyToInterlacedVector(*x_vec_blocks,*x_vec_inter); // copy random x to 
      f_vec_inter->PutScalar(0.0);

      full_op.Apply(*x_vec_blocked,*f_vec_blocked); 
      op.Apply(*x_vec_inter,*f_vec_inter); 

      // copy blocked action to interlaced for comparison
      Stokhos::SGModelEvaluator_Interlaced::copyToInterlacedVector(*f_vec_blocks,*f_vec_blk_inter); 

      // compute norm
      double error = 0.0;
      double true_norm = 0.0;
      f_vec_blk_inter->NormInf(&true_norm);
      f_vec_blk_inter->Update(-1.0,*f_vec_inter,1.0);
      f_vec_blk_inter->NormInf(&error);

      out << "rel error = " << error/true_norm << " ( " << true_norm << " ), ";
      result &= (error/true_norm < 1e-14);
   }
   out << std::endl;

   TEST_ASSERT(result);
}
Exemple #28
0
// Attempt to deliver requests to the transport layer.
//
// Tries to find HTTP requests for each policy class with
// available capacity.  Starts with the retry queue first
// looking for requests that have waited long enough then
// moves on to the ready queue.
//
// If all queues are empty, will return an indication that
// the worker thread may sleep hard otherwise will ask for
// normal polling frequency.
//
// Implements a client-side request rate throttle as well.
// This is intended to mimic and predict throttling behavior
// of grid services but that is difficult to do with different
// time bases.  This also represents a rigid coupling between
// viewer and server that makes it hard to change parameters
// and I hope we can make this go away with pipelining.
//
HttpService::ELoopSpeed HttpPolicy::processReadyQueue()
{
	const HttpTime now(totalTime());
	HttpService::ELoopSpeed result(HttpService::REQUEST_SLEEP);
	HttpLibcurl & transport(mService->getTransport());
	
	for (int policy_class(0); policy_class < mClasses.size(); ++policy_class)
	{
		ClassState & state(*mClasses[policy_class]);
		HttpRetryQueue & retryq(state.mRetryQueue);
		HttpReadyQueue & readyq(state.mReadyQueue);

		if (state.mStallStaging)
		{
			// Stalling but don't sleep.  Need to complete operations
			// and get back to servicing queues.  Do this test before
			// the retryq/readyq test or you'll get stalls until you
			// click a setting or an asset request comes in.
			result = HttpService::NORMAL;
			continue;
		}
		if (retryq.empty() && readyq.empty())
		{
			continue;
		}
		
		const bool throttle_enabled(state.mOptions.mThrottleRate > 0L);
		const bool throttle_current(throttle_enabled && now < state.mThrottleEnd);

		if (throttle_current && state.mThrottleLeft <= 0)
		{
			// Throttled condition, don't serve this class but don't sleep hard.
			result = HttpService::NORMAL;
			continue;
		}

		int active(transport.getActiveCountInClass(policy_class));
		int active_limit(state.mOptions.mPipelining > 1L
						 ? (state.mOptions.mPerHostConnectionLimit
							* state.mOptions.mPipelining)
						 : state.mOptions.mConnectionLimit);
		int needed(active_limit - active);		// Expect negatives here

		if (needed > 0)
		{
			// First see if we have any retries...
			while (needed > 0 && ! retryq.empty())
			{
				HttpOpRequest * op(retryq.top());
				if (op->mPolicyRetryAt > now)
					break;
			
				retryq.pop();
				
				op->stageFromReady(mService);
				op->release();

				++state.mRequestCount;
				--needed;
				if (throttle_enabled)
				{
					if (now >= state.mThrottleEnd)
					{
						// Throttle expired, move to next window
						LL_DEBUGS(LOG_CORE) << "Throttle expired with " << state.mThrottleLeft
											<< " requests to go and " << state.mRequestCount
											<< " requests issued." << LL_ENDL;
						state.mThrottleLeft = state.mOptions.mThrottleRate;
						state.mThrottleEnd = now + HttpTime(1000000);
					}
					if (--state.mThrottleLeft <= 0)
					{
						goto throttle_on;
					}
				}
			}
			
			// Now go on to the new requests...
			while (needed > 0 && ! readyq.empty())
			{
				HttpOpRequest * op(readyq.top());
				readyq.pop();

				op->stageFromReady(mService);
				op->release();
					
				++state.mRequestCount;
				--needed;
				if (throttle_enabled)
				{
					if (now >= state.mThrottleEnd)
					{
						// Throttle expired, move to next window
						LL_DEBUGS(LOG_CORE) << "Throttle expired with " << state.mThrottleLeft
											<< " requests to go and " << state.mRequestCount
											<< " requests issued." << LL_ENDL;
						state.mThrottleLeft = state.mOptions.mThrottleRate;
						state.mThrottleEnd = now + HttpTime(1000000);
					}
					if (--state.mThrottleLeft <= 0)
					{
						goto throttle_on;
					}
				}
			}
		}

	throttle_on:
		
		if (! readyq.empty() || ! retryq.empty())
		{
			// If anything is ready, continue looping...
			result = HttpService::NORMAL;
		}
	} // end foreach policy_class

	return result;
}
Exemple #29
0
bool IRInstruction::isTerminal() const {
  return opcodeHasFlags(op(), Terminal);
}
Exemple #30
0
int main(int argc, char **argv) {
  double *numbers;
  int i, j, n, r, o;
  int compare_mode = 0;
  int nopdiffs = 0, nansdiffs = 0, nxdiffs = 0, nclsdiffs = 0;
  int *numansdiffs, opansdiffs[4] = {0, 0, 0, 0};
  int rndansdiffs[4] = {0, 0, 0, 0};
  int *numxdiffs, opxdiffs[4] = {0, 0, 0, 0}, rndxdiffs[4] = {0, 0, 0, 0};
  int *numt, opt[4] = {0, 0, 0, 0}, rndt[4] = {0, 0, 0, 0};
  int oprndansdiffs[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  int oprndxdiffs[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  int oprndt[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  char *compare_file;
  FILE *fp = NULL;

  if(argc == 1) {
    fprintf(stderr, "Usage: %s [-test | -cmp <file> | <list of floats....>]\n",
	    argv[0]);
    exit(1);
  }
  
  if(argc >= 2) {
    if(strcmp(argv[1], "-cmp") == 0) {
      if(argc < 3) {
	fprintf(stderr, "You must supply a file to compare with\n");
	exit(1);
      }
      else if(argc > 3) {
	fprintf(stderr, "WARNING: ignoring arguments after %s\n", argv[3]);
      }
      compare_mode = 1;
      compare_file = argv[2];
      fp = fopen(compare_file, "r");
      if(fp == NULL) {
	fprintf(stderr, "Error opening comparison file ");
	perror(compare_file);
	abort();
      }
    }
    else if(strcmp(argv[1], "-test") == 0) {
      return test_functions();
    }
  }

  if(compare_mode) {
    if(fscanf(fp, "Numbers: %d", &n) != 1) {
      printf("Problem reading comparison file %s\n", compare_file);
      abort();
    }
  }
  else {
    n = argc - 1;
    printf("Numbers: %d\n", n);
  }
  numbers = malloc(n * sizeof(double));
  if(numbers == NULL) {
    perror("Memory allocation");
    abort();
  }
  numansdiffs = malloc(n * sizeof(int));
  if(numansdiffs == NULL) {
    perror("Memory allocation");
    abort();
  }
  numxdiffs = malloc(n * sizeof(int));
  if(numxdiffs == NULL) {
    perror("Memory allocation");
    abort();
  }
  numt = malloc(n * sizeof(int));
  if(numt == NULL) {
    perror("Memory allocation");
    abort();
  }
  
  for(i = 0; i < n; i++) {
    if(compare_mode) {
      if(fscanf(fp, "%lf", &numbers[i]) != 1) {
	printf("Problem reading comparison file %s\n", compare_file);
	abort();
      }
    }
    else {
      numbers[i] = atof(argv[i + 1]);
      printf("%s\n", argv[i + 1]);
    }
    numansdiffs[i] = 0;
    numxdiffs[i] = 0;
    numt[i] = 0;
  }

  for(i = 0; i < n; i++) {
    for(j = 0; j < n; j++) {
      for(o = 0; o <= 3; o++) {
	for(r = 0; r <= 3; r++) {
	  int pansdiffs = nansdiffs;
	  int pxdiffs = nxdiffs;

	  op(numbers[i], numbers[j], o, r, fp,
	     &nopdiffs, &nansdiffs, &nxdiffs, &nclsdiffs);

	  if(pansdiffs != nansdiffs) {
	    numansdiffs[i]++;
	    numansdiffs[j]++;
	    opansdiffs[o]++;
	    rndansdiffs[r]++;
	    oprndansdiffs[(o * 4) + r]++;
	  }
	  if(pxdiffs != nxdiffs) {
	    numxdiffs[i]++;
	    numxdiffs[j]++;
	    opxdiffs[o]++;
	    rndxdiffs[r]++;
	    oprndxdiffs[(o * 4) + r]++;
	  }
	  numt[i]++;
	  numt[j]++;
	  opt[o]++;
	  rndt[r]++;
	  oprndt[(o * 4) + r]++;
	}
      }
    }
  }

  if(compare_mode) {
    fclose(fp);
    printf("Summary of differences between comparison file and this run:\n");
    printf("\t(Each is a count of the number of calculations concerned)\n");
    printf("\t%d\t-- different representation of one or more operands\n",
	   nopdiffs);
    printf("\t%d\t-- different answer where operands represented the same\n",
	   nansdiffs);
    printf("\t%d\t-- different exceptions where answer the same\n",
	   nxdiffs);
    printf("\t%d\t-- different fpclasses where answer the same\n",
	   nclsdiffs);
    printf("Breakdown of differences by number, operator and rounding "
	   "direction:\n");
    printf("\t% 8s % 15s % 6s % 9s % 5s\n", "Type", "Data", "Answer",
	   "Exception", "Total");
    for(i = 0; i < n; i++) {
      printf("\t% 8s % 15g % 6d % 9d % 5d\n", "Number", numbers[i],
	     numansdiffs[i], numxdiffs[i], numt[i]);
    }
    for(i = 0; i < 4; i++) {
      printf("\t% 8s % 15s % 6d % 9d % 5d\n", "Operator", operators[i],
	     opansdiffs[i], opxdiffs[i], opt[i]);
    }
    for(i = 0; i < 4; i++) {
      printf("\t% 8s % 15s % 6d % 9d % 5d\n", "Round", rnddir[i],
	     rndansdiffs[i], rndxdiffs[i], rndt[i]);
    }
    for(o = 0; o < 4; o++) {
      for(r = 0; r < 4; r++) {
	printf("\t% 8s % 14s%s % 6d % 9d % 5d\n", "Op&Round", operators[o],
	       rnddir[r], oprndansdiffs[(o * 4) + r], oprndxdiffs[(o * 4) + r],
	       oprndt[(o * 4) + r]);
      }
    }
  }

  free(numbers);
  free(numansdiffs);
  free(numxdiffs);
  free(numt);

  return 0;
}