Beispiel #1
0
        PaStiX(
                MPI_Comm mpi_comm,
                int n_local_rows,
                const PRng &p_ptr,
                const CRng &p_col,
                const VRng &p_val,
                const params& = params()
                )
            : comm(mpi_comm), nrows(n_local_rows), pastix_data(0),
              ptr(boost::begin(p_ptr), boost::end(p_ptr)),
              col(boost::begin(p_col), boost::end(p_col)),
              val(boost::begin(p_val), boost::end(p_val)),
              row(nrows), perm(nrows)
        {
            std::vector<int> domain(comm.size + 1, 0);
            MPI_Allgather(&nrows, 1, MPI_INT, &domain[1], 1, MPI_INT, comm);
            boost::partial_sum(domain, domain.begin());

            boost::copy(
                    boost::irange(domain[comm.rank], domain[comm.rank + 1]),
                    row.begin()
                    );

            // PaStiX needs 1-based matrices:
            BOOST_FOREACH(pastix_int_t &p, ptr) ++p;
            BOOST_FOREACH(pastix_int_t &c, col) ++c;
            BOOST_FOREACH(pastix_int_t &r, row) ++r;

            // Initialize parameters with default values:
            iparm[IPARM_MODIFY_PARAMETER] = API_NO;
            call_pastix(API_TASK_INIT, API_TASK_INIT);

            // Factorize the matrix.
            iparm[IPARM_VERBOSE        ] = API_VERBOSE_NOT;
            iparm[IPARM_RHS_MAKING     ] = API_RHS_B;
            iparm[IPARM_SYM            ] = API_SYM_NO;
            iparm[IPARM_FACTORIZATION  ] = API_FACT_LU;
            iparm[IPARM_TRANSPOSE_SOLVE] = API_YES;
#ifdef _OPENMP
            iparm[IPARM_THREAD_NBR]      = omp_get_max_threads();
#endif
            call_pastix(API_TASK_ORDERING, API_TASK_NUMFACT);
        }
Beispiel #2
0
Sim1D::Sim1D(vector<Domain1D*>& domains) :
    OneDim(domains)
{
    // resize the internal solution vector and the work array, and perform
    // domain-specific initialization of the solution vector.

    m_x.resize(size(), 0.0);
    m_xnew.resize(size(), 0.0);
    for (size_t n = 0; n < m_nd; n++) {
        domain(n)._getInitialSoln(DATA_PTR(m_x) + start(n));
    }

    // set some defaults
    m_tstep = 1.0e-5;
    m_steps.push_back(1);
    m_steps.push_back(2);
    m_steps.push_back(5);
    m_steps.push_back(10);
}
Beispiel #3
0
  /** 
   * Return a LP for the specified mesh. This function implements the
   * prob() pure virtual function of class LPTestBase.
   */
  LinearProblem prob(const Mesh& mesh) const
    {
      const double pi = 4.0*atan(1.0);
      CellFilter left = domain().left();

      Expr u = new UnknownFunction(new Lagrange(2), "u");
      Expr v = new TestFunction(new Lagrange(2), "v");
      Expr dx = gradient(1);
      Expr x = coord(0);

      QuadratureFamily quad = new GaussianQuadrature(4);

      Expr eqn = Integral(interior(), (dx*v)*(dx*u), quad)
        + Integral(interior(), -0.25*pi*pi*sin(pi*x/2.0)*v, quad);

      Expr bc = EssentialBC(left, v*u, quad);
      
      return LinearProblem(mesh, eqn, bc, v, u, vecType());
    }
Beispiel #4
0
void main( int argc, char ** argv )
{
   Environment env(argc, argv);
   WALBERLA_UNUSED(env);
   walberla::mpi::MPIManager::instance()->useWorldComm();

   //init domain partitioning
   auto forest = blockforest::createBlockForest( AABB(0,0,0,20,20,20), // simulation domain
                                                 Vector3<uint_t>(2,2,2), // blocks in each direction
                                                 Vector3<bool>(false, false, false) // periodicity
                                                 );
   domain::BlockForestDomain domain(forest);

   //init data structures
   data::ParticleStorage ps(100);

   //initialize particle
   auto uid = createSphere(ps, domain);
   WALBERLA_LOG_DEVEL_ON_ROOT("uid: " << uid);

   //init kernels
   mpi::ReduceProperty    RP;
   mpi::SyncNextNeighbors SNN;

   //sync
   SNN(ps, domain);

   auto pIt = ps.find(uid);
   if (pIt != ps.end())
   {
      pIt->getForceRef() += Vec3(real_c(walberla::mpi::MPIManager::instance()->rank()));
   }

   RP.operator()<ForceTorqueNotification>(ps);

   if (walberla::mpi::MPIManager::instance()->rank() == 0)
   {
      WALBERLA_CHECK_FLOAT_EQUAL( pIt->getForce(), Vec3(real_t(28)) );
   } else
   {
      WALBERLA_CHECK_FLOAT_EQUAL( pIt->getForce(), Vec3(real_t(walberla::mpi::MPIManager::instance()->rank())) );
   }
}
  void image() const
  {
    typedef CGAL::Image_3 Image;
    typedef CGAL::Labeled_image_mesh_domain_3<Image, K_e_i> Mesh_domain;

    typedef typename CGAL::Mesh_triangulation_3<
      Mesh_domain,
      CGAL::Kernel_traits<Mesh_domain>::Kernel,
      Concurrency_tag>::type Tr;
    typedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;

    typedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;
    typedef typename Mesh_criteria::Facet_criteria Facet_criteria;
    typedef typename Mesh_criteria::Cell_criteria Cell_criteria;

    //-------------------------------------------------------
    // Data generation
    //-------------------------------------------------------
    Image image;
    image.read("data/liver.inr.gz");

    std::cout << "\tSeed is\t"
      << CGAL::get_default_random().get_seed() << std::endl;
    Mesh_domain domain(image, 1e-9, &CGAL::get_default_random());

    // Set mesh criteria
    Facet_criteria facet_criteria(25, 20*image.vx(), 5*image.vx());
    Cell_criteria cell_criteria(4, 25*image.vx());
    Mesh_criteria criteria(facet_criteria, cell_criteria);

    // Mesh generation
    C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria,
                                        CGAL::parameters::no_exude(),
                                        CGAL::parameters::no_perturb());

    // Verify
    this->verify_c3t3_volume(c3t3, 1772330*0.95, 1772330*1.05);
    this->verify(c3t3,domain,criteria, Bissection_tag());

    typedef typename Mesh_domain::Surface_patch_index Patch_id;
    CGAL_static_assertion(CGAL::Output_rep<Patch_id>::is_specialized);
    CGAL_USE_TYPE(Patch_id);
  }
Beispiel #6
0
std::string IPeakFunction::getCentreParameterName() const {
  FunctionParameterDecorator_sptr fn =
      boost::dynamic_pointer_cast<FunctionParameterDecorator>(
          FunctionFactory::Instance().createFunction("PeakParameterFunction"));

  if (!fn) {
    throw std::runtime_error(
        "PeakParameterFunction could not be created successfully.");
  }

  fn->setDecoratedFunction(this->name());

  FunctionDomain1DVector domain(std::vector<double>(4, 0.0));
  TempJacobian jacobian(4, fn->nParams());

  fn->functionDeriv(domain, jacobian);

  return parameterName(jacobian.maxParam(0));
}
Beispiel #7
0
void KCookieJar::loadConfig(KConfig *_config, bool reparse )
{
    if ( reparse )
        _config->reparseConfiguration();

    _config->setGroup("Cookie Dialog");
    m_showCookieDetails = _config->readBoolEntry( "ShowCookieDetails" );
    m_preferredPolicy = _config->readNumEntry( "PreferredPolicy", 0 );

    _config->setGroup("Cookie Policy");
    QStringList domainSettings = _config->readListEntry("CookieDomainAdvice");
    m_rejectCrossDomainCookies = _config->readBoolEntry( "RejectCrossDomainCookies", true );
    m_autoAcceptSessionCookies = _config->readBoolEntry( "AcceptSessionCookies", true );
    m_ignoreCookieExpirationDate = _config->readBoolEntry( "IgnoreExpirationDate", false );
    QString value = _config->readEntry("CookieGlobalAdvice", L1("Ask"));
    m_globalAdvice = strToAdvice(value);

    // Reset current domain settings first.
    for ( QStringList::Iterator it=m_domainList.begin(); it != m_domainList.end(); )
    {
         // Make sure to update iterator before calling setDomainAdvice()
         // setDomainAdvice() might delete the domain from domainList.
         QString domain = *it++;
         setDomainAdvice(domain, KCookieDunno);
    }

    // Now apply the domain settings read from config file...
    for ( QStringList::Iterator it=domainSettings.begin();
          it != domainSettings.end(); )
    {
        const QString &value = *it++;

        int sepPos = value.findRev(':');

        if (sepPos <= 0)
          continue;

        QString domain(value.left(sepPos));
        KCookieAdvice advice = strToAdvice( value.mid(sepPos + 1) );
        setDomainAdvice(domain, advice);
    }
}
Beispiel #8
0
int launchNewton(){
    std::cout << "Launch Newton" << std::endl;

    char** argv = NULL;
    GLUTWindowManagers::init(0, argv);

    int w = 800;
    int h = 800;

    DomaineMaths domain(-w / 2, - h / 2, w, h);

    NewtonImageSequential* functionalImage = new NewtonImageSequential(w, h, domain);
    FractaleGLImage* functionSelections = new FractaleGLImage(functionalImage);

    GLUTWindowManagers* windowManager = GLUTWindowManagers::getInstance();
    windowManager->createWindow(functionSelections);
    windowManager->runALL(); //This call is blocking

    return 0;
}
 void
 ArccosineExpression::evaluateImpl(
     const MatrixID<const Interval>& parameterID,
     const MatrixID<Interval>& resultID,
     ExpressionCompiler<Interval>& expressionCompiler
 ) const {
     expressionCompiler.evaluate(operand(), parameterID, resultID);
     expressionCompiler.compute(
         resultID,
         [] (IntervalMatrixViewXd results) {
             results.setMap(
                 results,
                 [] (Interval value) {
                     Interval domain(-1, 1);
                     return opensolid::acos(value.intersection(domain));
                 }
             );
         }
     );
 }
Beispiel #10
0
/*! We pass the global maximum as a parameter to ensure the containment of the
density form of the original Levy target as an "energy" function inside the
number screen.  We get the density from energy by exponentiating its negative.  
This allows ease of likelihood inference and can be circumvented in several 
ways.  For eg we can find the global min first for the Levy target energy and 
then use it as the global max parameter GlbMx to the density form (actually the
shape without the normalizing constant).  Here we have already computed the 
Global max parameter GlbMx using C-XSC Toolbox.
*/
FLevy2D::FLevy2D (real T, real GlbMx, real C1, real C2, 
                  real DomainLimit, bool LogPi)
:
Temperature (T), GlobalMax (GlbMx), Center1 (C1), Center2 (C2)
{
  setUsingLogDensity (LogPi);

  PriorType = 0;// Uniform PriorType is an inherited member from Fobj
  // set up the domain list
  ivector domain (1, 2);
  LabBox  Ldomain;
  for (int i = 1; i <= 2; i++)
  {
    domain[i] = interval (-DomainLimit, DomainLimit);
  }
  Ldomain.Box = domain;
  Ldomain.L = 0;
  LabDomainList.push_back (Ldomain);

}
Beispiel #11
0
FLevy2D_Lkl_Tfrom1data::FLevy2D_Lkl_Tfrom1data (ivector & data, 
                                                real GlbMx, real C1, real C2, 
                                                interval DomainLimit, 
                                                bool LogPi)
:
Data (data), GlobalMax (GlbMx), Center1 (C1), Center2 (C2)
{
  setUsingLogDensity (LogPi);
  //PriorType = 0;// Uniform PriorType is an inherited member from Fobj
  //domain for the temperature parameter in the likelihood
  ivector domain (1, 1);
  LabBox Ldomain;
  for (int i = 1; i <= 1; i++)
  {
    domain[i] = DomainLimit;
  }
  Ldomain.Box = domain;
  Ldomain.L = 0;
  LabDomainList.push_back (Ldomain);

}
Beispiel #12
0
inline void benchSequential(rgba* image){
    DomaineMaths domain(0, 0, DIM_W, DIM_H);

    float dx = (float) (domain.dx / (float) DIM_W);
    float dy = (float) (domain.dy / (float) DIM_H);
    float y = domain.y0;

    for(int i = 1; i <= DIM_W; ++i){
	float x = domain.x0;

	for(int j = 1; j <= DIM_H; ++j){
	    float c = perlinNoise(x,y, 1);

	    setFloatRGBA(image, i, j, 135, 206, 250, c * 255.0);

	    x += dx;
	}

	y += dy;
    }
}
Beispiel #13
0
static bool x_GetAccountNameBySid(PSID sid, string* account, int* domatch = 0)
{
    _ASSERT(account);

    // Use predefined buffers for account/domain names to avoid additional
    // step to get its sizes. According to MSDN max account/domain size
    // do not exceed MAX_ACCOUNT_LEN symbols (char or wchar).

    TXChar   account_name[MAX_ACCOUNT_LEN + 2];
    TXChar   domain_name [MAX_ACCOUNT_LEN + 2];
    DWORD    account_size = sizeof(account_name)/sizeof(account_name[0]) - 1;
    DWORD    domain_size  = sizeof(domain_name)/sizeof(domain_name[0]) - 1;
    SID_NAME_USE use;

    // Always get both account & domain name, even we don't need last.
    // Because if domain name is NULL, this function can throw unhandled
    // exception in Unicode builds on some platforms.
    if ( !LookupAccountSid(NULL, sid, 
                           account_name, &account_size,
                           domain_name,  &domain_size, &use) ) {
        CNcbiError::SetFromWindowsError();
        return false;
    }

    // Save account information
    account_name[account_size] = _TX('\0');
    account->assign(_T_STDSTRING(account_name));

    if (domatch) {
        domain_name[domain_size] = _TX('\0');
        string domain(_T_STDSTRING(domain_name));
        if (*domatch != int(use)  ||  domain.empty()
            ||  NStr::EqualNocase(domain, "builtin")
            ||  NStr::FindNoCase(domain, " ") != NPOS
            /*||  x_DomainIsLocalComputer(domain_name)*/) {
            *domatch = 0;
        }
    }
    return true;
}
Beispiel #14
0
int launchNewtonOMP(){
    omp_set_num_threads(THREADS);

    std::cout << "Launch Newton with OMP" << std::endl;

    char** argv = NULL;
    GLUTWindowManagers::init(0, argv);

    int w = 800;
    int h = 800;

    DomaineMaths domain(-w / 2, - h / 2, w, h);

    NewtonImageOMP* functionalImage = new NewtonImageOMP(w, h, domain);
    FractaleGLImage* functionSelections = new FractaleGLImage(functionalImage);

    GLUTWindowManagers* windowManager = GLUTWindowManagers::getInstance();
    windowManager->createWindow(functionSelections);
    windowManager->runALL(); //This call is blocking

    return 0;
}
/** \brief Start the operation
 */
slay_err_t	slay_resp_btjamrc4_t::start(const slay_resp_arg_t &resp_arg)		throw()
{
	// sanity check - slay_resp_arg_t MUST be valid
	DBG_ASSERT( resp_arg.is_valid() );
	// sanity check - resp_arg.domain() MUST be the local one
	DBG_ASSERT( resp_arg.domain() == domain() );
	
	// if resp_arg.profile_present(), copy it
	if( resp_arg.profile_present() )	m_slay_profile	= resp_arg.profile();

	// set the tls_profile_t to m_btjamrc4_resp
	const slay_profile_btjamrc4_t & dom_profile	= slay_profile_btjamrc4_t::from_slay(resp_arg.profile());
	m_btjamrc4_resp.profile( dom_profile.bt_jamrc4() );

	// start the bt_jamrc4_resp_t
	bt_err_t	bt_err;
	bt_err		= m_btjamrc4_resp.start();
	if( bt_err.failed() )	return slay_err_from_bt(bt_err);
	
	// return no error	
	return slay_err_t::OK;
}
/*
 * Write files to the given output.  This implementation does *not* create
 * a standalone archive suitable for restore on its own.  In particular, the identification of
 * the application's name etc is not in-band here; it's assumed that the calling code has
 * taken care of supplying that information previously in the output stream.
 *
 * The file format is 'tar's, with special semantics applied by use of a "fake" directory
 * hierarchy within the tar stream:
 *
 * apps/packagename/a/Filename.apk - this is an actual application binary, which will be
 *   installed on the target device at restore time.  These need to appear first in the tar
 *   stream.
 * apps/packagename/obb/[relpath] - OBB containers belonging the app
 * apps/packagename/r/[relpath] - these are files at the root of the app's data tree
 * apps/packagename/f/[relpath] - this is a file within the app's getFilesDir() tree, stored
 *   at [relpath] relative to the top of that tree.
 * apps/packagename/db/[relpath] - as with "files" but for the getDatabasePath() tree
 * apps/packagename/sp/[relpath] - as with "files" but for the getSharedPrefsFile() tree
 * apps/packagename/c/[relpath] - as with "files" but for the getCacheDir() tree
 *
 * and for the shared storage hierarchy:
 *
 * shared/[relpaths] - files belonging in the device's shared storage location.  This will
 *    *not* include .obb files; those are saved with their owning apps.
 *
 * This method writes one file data block.  'domain' is the name of the appropriate pseudo-
 * directory to be applied for this file; 'linkdomain' is the pseudo-dir for a relative
 * symlink's antecedent.
 *
 * packagename: the package name to use as the top level directory tag
 * domain:      which semantic name the file is to be stored under (a, r, f, db, etc)
 * linkdomain:  where a symlink points for purposes of rewriting; current unused
 * rootpath:    prefix to be snipped from full path when encoding in tar
 * path:        absolute path to the file to be saved
 * dataOutput:  the BackupDataOutput object that we're saving into
 */
static int backupToTar(JNIEnv* env, jobject clazz, jstring packageNameObj,
        jstring domainObj, jstring linkdomain,
        jstring rootpathObj, jstring pathObj, jobject dataOutputObj) {
    int ret;

    // Extract the various strings, allowing for null object pointers
    const char* packagenamechars = (packageNameObj) ? env->GetStringUTFChars(packageNameObj, NULL) : NULL;
    const char* rootchars = (rootpathObj) ? env->GetStringUTFChars(rootpathObj, NULL) : NULL;
    const char* pathchars = (pathObj) ? env->GetStringUTFChars(pathObj, NULL) : NULL;
    const char* domainchars = (domainObj) ? env->GetStringUTFChars(domainObj, NULL) : NULL;

    String8 packageName(packagenamechars ? packagenamechars : "");
    String8 rootpath(rootchars ? rootchars : "");
    String8 path(pathchars ? pathchars : "");
    String8 domain(domainchars ? domainchars : "");

    if (domainchars) env->ReleaseStringUTFChars(domainObj, domainchars);
    if (pathchars) env->ReleaseStringUTFChars(pathObj, pathchars);
    if (rootchars) env->ReleaseStringUTFChars(rootpathObj, rootchars);
    if (packagenamechars) env->ReleaseStringUTFChars(packageNameObj, packagenamechars);

    // Extract the data output fd
    BackupDataWriter* writer = (BackupDataWriter*) env->GetIntField(dataOutputObj,
            sBackupDataOutput.mBackupWriter);

    // Validate
    if (!writer) {
        LOGE("No output stream provided [%s]", path.string());
        return -1;
    }

    if (path.length() < rootpath.length()) {
        LOGE("file path [%s] shorter than root path [%s]",
                path.string(), rootpath.string());
        return -1;
    }

    return write_tarfile(packageName, domain, rootpath, path, writer);
}
Beispiel #17
0
TEST(DISABLED_Boundary, inner_soild) {
	//
	const st dim = 2;
	// new shape--------------------
	Shape2D shape;
	CreatCircle(shape, 0.001, 0.001, 1.501, 10);

	Shape2D inner_shape;
	CreatCircle(inner_shape, 0.4, 0.6, 0.4, 3);
	std::list<Shape2D*> lis;
	lis.push_back(&inner_shape);
	Shape2D inner_shape2;
	CreatCircle(inner_shape2, .5, -0.1, 0.3, 6);
	lis.push_back(&inner_shape2);
	//Float x1 = 1.5, y1 = 1.5, x2 = 3.5, y2 = 3.5;
	//CreatCube(shape, x1, y1, x2, y2);
	// shape is out bound
	// define unit length
	Float UL = 1.0;
	// build grid ------------------
	Domain_<Float, Float, dim> domain(&shape, lis, UL, 2, 4);
	domain.build();
	// show ================================
	std::list<Gnuplot_actor> lga;
	Gnuplot_actor ga;
	GnuplotActor_LeafNodes(ga, domain.grid());
	lga.push_back(ga);
	GnuplotActor_GhostNodes(ga, domain.ghost());
	lga.push_back(ga);
	GnuplotActor_GhostNodesContour_BoundaryIndex(ga, domain.ghost());
	lga.push_back(ga);
	GnuplotActor_Shape2D(ga, shape, 0);
	lga.push_back(ga);

	Gnuplot gp;
	gp.set_equal_ratio();
	gp.plot(lga);
	//delete shape
}
Beispiel #18
0
//
// This function sets the advice for all cookies originating from
// _domain.
//
void KCookieJar::setDomainAdvice(const QString &_domain, KCookieAdvice _advice)
{
    QString domain(_domain);
    KHttpCookieList *cookieList = m_cookieDomains[domain];

    if (cookieList)
    {
        if (cookieList->getAdvice() != _advice)
        {
           m_configChanged = true;
           // domain is already known
           cookieList->setAdvice( _advice);
        }

        if ((cookieList->isEmpty()) &&
            (_advice == KCookieDunno))
        {
            // This deletes cookieList!
            m_cookieDomains.remove(domain);
            m_domainList.remove(domain);
        }
    }
    else
    {
        // domain is not yet known
        if (_advice != KCookieDunno)
        {
            // We should create a domain entry
            m_configChanged = true;
            // Make a new cookie list
            cookieList = new KHttpCookieList();
            cookieList->setAutoDelete(true);
            cookieList->setAdvice( _advice);
            m_cookieDomains.insert( domain, cookieList);
            // Update the list of domains
            m_domainList.append( domain);
        }
    }
}
Beispiel #19
0
/*---------------------------------------------------------------------*/
int main(int count, char *strings[])
{
	signal(SIGCHLD, sigchild);
	if ( count != 3 )
	{
		printf("usage: %s <addr:port> <peer:port>\n", strings[0]);
		exit(1);
	}
	HostAddress addr(strings[1]);
	HostAddress domain(strings[2]);

	try
	{
		Socket *channel = new Broadcast(addr);
		if ( !fork() )
			receiver(channel);
		channel->CloseInput();
		TextMessage msg(1024);
		do
		{
			char line[100];
			fgets(line, sizeof(line), stdin);
			msg = line;
			channel->Send(domain, msg);
		}
		while ( !done );
		delete channel;
	}
	catch (Exception& err)
	{
		printf("[PARENT]");
		err.PrintException();
	}
	catch (...)
	{
		fprintf(stderr, "Unknown error\n");
	}
	return 0;
}
Beispiel #20
0
Real
PiecewiseConstant::value(Real t, const Point & p)
{
  Real func_value(0);
  Real x = t;
  if (_has_axis)
  {
    x = p(_axis);
  }

  unsigned i = 1;
  const unsigned len = functionSize();
  const Real toler = 1e-14;

  // endpoint cases
  if ( (_direction == LEFT  && x < (1+toler) * domain(0)) ||
       (_direction == RIGHT && x < (1-toler) * domain(0)) )
  {
    func_value = range(0);
    i = len;
  }
  if ( (_direction == LEFT  && x > (1+toler) * domain(len-1)) ||
       (_direction == RIGHT && x > (1-toler) * domain(len-1)) )
  {
    func_value = range(len-1);
    i = len;
  }

  for ( ; i < len; ++i )
  {
    if ( _direction == LEFT &&
         x < (1+toler) * domain(i) )
    {
      func_value = range(i-1);
      break;
    }
    else if ( (_direction == RIGHT &&
               x < (1-toler) * domain(i)) )
    {
      func_value = range(i);
      break;
    }
  }

  return _scale_factor * func_value;
}
Beispiel #21
0
bool Interconnects::createObject(Broker& broker, const std::string& type, const std::string& name, const qpid::types::Variant::Map& properties,
                                 const std::string& /*userId*/, const std::string& /*connectionId*/)
{
    if (type == DOMAIN_TYPE) {
        qpid::sys::ScopedLock<qpid::sys::Mutex> l(lock);
        DomainMap::iterator i = domains.find(name);
        if (i == domains.end()) {
            boost::shared_ptr<Domain> domain(new Domain(name, properties, broker));
            domains[name] = domain;
            if (domain->isDurable()) broker.getStore().create(*domain);
            return true;
        } else {
            return false;
        }
    } else if (type == INCOMING_TYPE || type == OUTGOING_TYPE) {
        QPID_LOG(notice, "Creating interconnect " << name << ", " << properties);
        boost::shared_ptr<Domain> domain;
        {
            qpid::sys::ScopedLock<qpid::sys::Mutex> l(lock);
            qpid::types::Variant::Map::const_iterator p = properties.find(DOMAIN_TYPE);
            if (p != properties.end()) {
                std::string domainName = p->second;
                DomainMap::iterator i = domains.find(domainName);
                if (i != domains.end()) {
                    domain = i->second;
                } else {
                    throw qpid::Exception(QPID_MSG("No such domain: " << domainName));
                }
            } else {
                throw qpid::Exception(QPID_MSG("Domain must be specified"));
            }
        }
        domain->connect(type == INCOMING_TYPE, name, properties, *context);
        return true;
    } else {
        return false;
    }
}
void cpp_from_cloog::process( clast_for* loop )
{
    isl::set domain( isl_set_from_cloog_domain(loop->domain) );
    isl::printer p(domain.ctx());
    cout << "Generating loop for domain: ";  p.print(domain); cout << endl;

    auto iterator = make_shared<id_expression>(loop->iterator);
    auto iterator_decl =
            make_shared<variable_decl>(make_shared<basic_type>("int"),
                                       loop->iterator);
    auto iterator_decl_expr = make_shared<var_decl_expression>(iterator_decl);

    auto for_stmt = new for_statement;

    for_stmt->initialization =
            make_shared<bin_op_expression>(op::assign,
                                           iterator_decl_expr,
                                           process(loop->LB));
    for_stmt->condition =
            make_shared<bin_op_expression>(op::lesser_or_equal,
                                           iterator,
                                           process(loop->UB));

    for_stmt->update =
            make_shared<bin_op_expression>(op::assign_add,
                                           iterator,
                                           literal(loop->stride));

    auto body = make_shared<block_statement>();

    m_ctx->push(&body->statements);
    process_list(loop->body);
    m_ctx->pop();

    for_stmt->body = body;

    m_ctx->add(statement_ptr(for_stmt));
}
Beispiel #23
0
extern "C" JNIEXPORT bool JNICALL
Java_com_felspar_android_Setting_fromJSON(
    JNIEnv *env, jobject self, jstring jdomain, jstring j_string
) {
    try {
        fostlib::string cppstring(fostlib::jni_cast<fostlib::string>(env, j_string)),
            domain(fostlib::jni_cast<fostlib::string>(env, jdomain));
        fostlib::json parsed(fostlib::json::parse(cppstring));
        g_settings.push_back(
            std::unique_ptr<fostlib::settings>(
                new fostlib::settings(domain, parsed)));
        g_sinks.reset(new fostlib::log::global_sink_configuration(c_logging.value()));
        fostlib::log::info(c_module)
            ("domain", domain)
            ("settings", parsed);
        return true;
    } catch ( fostlib::exceptions::exception &e ) {
        fostlib::log::info(c_module)
            ("exception", e.what())
            ("data", e.data());
        return false;
    }
}
Beispiel #24
0
/**
 * Calculates the 1D diffractogram based on the supplied function
 *
 * This method takes a fit function and checks whether it implements the
 * IPoldiFunction1D interface. If that's the case, it calculates the
 * diffractogram based on the function.
 *
 * @param fitFunction :: IFunction that also implements IPoldiFunction1D.
 * @param workspace :: Workspace with POLDI raw data.
 * @return :: Q-based diffractogram.
 */
MatrixWorkspace_sptr PoldiFitPeaks2D::get1DSpectrum(
    const IFunction_sptr &fitFunction,
    const API::MatrixWorkspace_sptr &workspace) const {

  // Check whether the function is of correct type
  boost::shared_ptr<IPoldiFunction1D> poldiFunction =
      boost::dynamic_pointer_cast<IPoldiFunction1D>(fitFunction);

  if (!poldiFunction) {
    throw std::invalid_argument("Can only process Poldi2DFunctions.");
  }

  // And that we have an instrument available
  if (!m_poldiInstrument) {
    throw std::runtime_error("No POLDI instrument available.");
  }

  PoldiAbstractDetector_sptr detector(new PoldiDeadWireDecorator(
      workspace->detectorInfo(), m_poldiInstrument->detector()));
  std::vector<int> indices = detector->availableElements();

  // Create the grid for the diffractogram and corresponding domain/values
  double lambdaMin = getProperty("LambdaMin");
  double lambdaMax = getProperty("LambdaMax");

  PoldiDGrid grid(detector, m_poldiInstrument->chopper(), m_deltaT,
                  std::make_pair(lambdaMin, lambdaMax));

  FunctionDomain1DVector domain(grid.grid());
  FunctionValues values(domain);

  // Calculate 1D function
  poldiFunction->poldiFunction1D(indices, domain, values);

  // Create and return Q-based workspace with spectrum
  return getQSpectrum(domain, values);
}
/* static */
nsresult
sbURIChecker::CheckURI(nsACString& aDomain,
                       nsACString& aPath,
                       nsIURI* aURI)
{
#ifdef PR_LOGGING
  if (!gURICheckerLog) {
    gURICheckerLog = PR_NewLogModule("sbURIChecker");
  }
  LOG(("sbURIChecker::CheckURI(domain:%s path:%s)",
       aDomain.BeginReading(), aPath.BeginReading()));
#endif
  NS_ENSURE_ARG_POINTER(aURI);
  
  nsCString domain(aDomain);
  nsresult rv = CheckDomain( domain, aURI );
  if ( NS_FAILED(rv) ) {
    LOG(("sbURIChecker::CheckURI() -- FAILED domain Check"));
    return rv;
  }

  nsCString path(aPath);
  rv = CheckPath( path, aURI );
  if ( NS_FAILED(rv) ) {
    LOG(("sbURIChecker::CheckURI() -- FAILED path Check"));
    return rv;
  }

  // everything passed, assign into the inputs
  if ( aDomain.IsEmpty() ) {
    aDomain.Assign(domain);
  }
  if ( aPath.IsEmpty() ) {
    aPath.Assign(path);
  }
  return NS_OK;
}
String^ GetTokenUsername(HANDLE hToken)
{
	std::vector<unsigned char> tokenUsername = GetTokenInfo(hToken, TokenUser);

	if (tokenUsername.size() > 0)
	{
		PTOKEN_USER user = reinterpret_cast<PTOKEN_USER>(&tokenUsername[0]);

		std::vector<wchar_t> name(MAX_NAME);
		std::vector<wchar_t> domain(MAX_NAME);
		DWORD dwNameSize = MAX_NAME;
		DWORD dwDomainSize = MAX_NAME;
		SID_NAME_USE sidNameUse;
		String^ ret = "";

		if (LookupAccountSid(nullptr, user->User.Sid, &name[0], &dwNameSize, &domain[0], &dwDomainSize, &sidNameUse))
		{
			ret = gcnew String(&domain[0]);
			ret += "\\";
			ret += gcnew String(&name[0]);			
		}
		else
		{
			LPWSTR lpSid;

			if (ConvertSidToStringSidW(user->User.Sid, &lpSid))
			{
				ret = gcnew String(lpSid);
				LocalFree(lpSid);
			}
		}

		return ret;
	}
	
	return "";
}
Beispiel #27
0
void MeshOpt::trustRegion(hier::Patch<NDIM>& patch)
{
    MsqError err;
    MeshImpl* mesh = createLocalMesh(patch);

    PlanarDomain domain(PlanarDomain::XY);
    IdealWeightInverseMeanRatio inverse_mean_ratio(err);
    LPtoPTemplate obj_func(&inverse_mean_ratio,2,err);
    TrustRegion t_region(&obj_func);
    t_region.use_global_patch();
    TerminationCriterion tc_inner;
    tc_inner.add_absolute_gradient_L2_norm(1e-6);
    tc_inner.add_iteration_limit(1);
    t_region.set_inner_termination_criterion(&tc_inner);
    QualityAssessor m_ratio_qa(&inverse_mean_ratio);
    m_ratio_qa.disable_printing_results();

    InstructionQueue queue;
    queue.add_quality_assessor(&m_ratio_qa,err);
    queue.set_master_quality_improver(&t_region,err);
    queue.add_quality_assessor(&m_ratio_qa,err);
    MeshDomainAssoc mesh_and_domain = MeshDomainAssoc(mesh,&domain);
    queue.run_instructions(&mesh_and_domain,err);
    tbox::pout<< "Shape optimization completed." << std::endl;

//    std::string file_name = "2__patch_3.vtk";
//    mesh->write_vtk(file_name.c_str(), err);

    transformMeshtoPatch(mesh,patch,err);



    d_flag =2;

    return;
}
/** \brief Start the operation
 */
socket_err_t	socket_resp_udp_t::start()					throw()
{
	inet_err_t	inet_err;
	nlay_err_t	nlay_err;
	// sanity check - the mandatory parameter MUST be set
	DBG_ASSERT( !listen_addr().is_null() );
	DBG_ASSERT( !type().is_null() );
	DBG_ASSERT(  callback );
	// sanity check - the profile MUST valid
	DBG_ASSERT( profile().check().succeed() );

// SETUP UDP_RESP_T
	udp_resp	= nipmem_new udp_resp_t();
	// get the listen address
	ipport_addr_t	ipport_addr	= socket_helper_udp_t::ipport_addr(listen_addr());
	// start the udp_resp_t
	inet_err	= udp_resp->start(ipport_addr, this, NULL);
	if( inet_err.failed() )	return socket_err_from_inet(inet_err, "Can't start udp_resp due to " );

	// reread the listen_addr() once the responder is bound, in case of dynamic part
	m_listen_addr	= socket_addr_t(domain().to_string() + "://" + udp_resp->get_listen_addr().to_string());
	DBG_ASSERT( !listen_addr().is_null() );
	
// SETUP NLAY_RESP_T
	// start the nlay_resp_t
	socket_profile_udp_t &	profile_dom	= socket_profile_udp_t::from_socket(m_socket_profile);
	nlay_resp	= nipmem_new nlay_resp_t(&profile_dom, type().to_nlay(), nlay_type_t::DGRAM);
	nlay_err  	= nlay_resp->start();
	if( nlay_err.failed() ){
		nipmem_zdelete udp_resp;
		return socket_err_from_nlay(nlay_err, "Can't start nlay_resp due to ");
	}
	
	// return no error	
	return socket_err_t::OK;
}
Beispiel #29
0
/*
 * Find the next node to forward a meassage to
 */
static int routing_next(node_t node, int dest) {
  int closest = closest_in_namespace_set(node, dest);
  int res = -1;
  if (closest!=-1)
    return closest;

  int l = shl(node->id, dest);
  res = node->routing_table[l][domain(dest, l)];
  if (res!=-1)
    return res;

  //rare case
  int dist = abs(node->id - dest);
  int i,j;
  for (i=l; i<LEVELS_COUNT; i++) {
    for (j=0; j<LEVEL_SIZE; j++) {
      res = node->routing_table[i][j];
      if (res!=-1 && abs(res - dest)<dist)
        return res;
    }
  }

  for (i=0; i<NEIGHBORHOOD_SIZE; i++) {
    res = node->neighborhood_set[i];
    if (res!=-1 && shl(res, dest)>=l && abs(res - dest)<dist)
        return res;
  }

  for (i=0; i<NAMESPACE_SIZE; i++) {
    res = node->namespace_set[i];
    if (res!=-1 && shl(res, dest)>=l && abs(res - dest)<dist)
        return res;
  }

  return node->id;
}
Beispiel #30
0
void benchSequentialNewton(rgba* image){
    float xMin = -1.7;
    float xMax = +1.7;
    float yMin = -1.1;
    float yMax = +1.1;

    DomaineMaths domain(xMin, yMin, xMax - xMin, yMax - yMin);

    float dx = (float) (domain.dx / (float) DIM_W);
    float dy = (float) (domain.dy / (float) DIM_H);
    float y = domain.y0;

    float acc = 0;

    for(int i = 1; i <= DIM_H; ++i){
    	float x = domain.x0;

    	for(int j = 1; j <= DIM_W; ++j){
	    int color = newton_bench::real_newton(x, y);

	    if(color == 0){
		setFloatRGBA(image, i, j, 0, 0, 0, 0);
	    } else if(color == 1){
		setFloatRGBA(image, i, j, 1, 0, 0, 0);
	    } else if(color == 2){
		setFloatRGBA(image, i, j, 0, 1, 0, 0);
	    } else if(color == 3){
		setFloatRGBA(image, i, j, 0, 0, 1, 0);
	    }

    	    x += dx;
    	}

    	y += dy;
    }
}