Beispiel #1
0
int LDA::sampleFullConditional(int m,int n) {
    double u,topic=z(m,n);
    VectorXd p(K);
    nw((*documents)(m,n),topic)--;
    nd(m,topic)--;
    nwsum(topic)--;
    ndsum(m)--;
    for(int k=0; k<K; k++)
        p(k)=((nw((*documents)(m,n),k)+beta)/(nwsum(k)+V*beta)) * ((nd(m,k)+alpha)/(ndsum(m)+K*alpha));

    for(int i=1; i<p.size(); i++)
        p(i)+=p(i-1);


    u = ((double) rand() / (RAND_MAX))*p(K-1);

    for(topic=0; topic<p.size(); topic++)
        if(u<p(topic)) break;

    nw((*documents)(m,n),topic)++;
    nd(m,topic)++;
    nwsum(topic)++;
    ndsum(m)++;
    return topic;

}
Beispiel #2
0
int main(){
	Simple_window win(Point(100, 100), 600, 400, "test");

	Circle c(Point(300, 200), 100);
	Graph_lib::Ellipse el(Point(300, 200), 100, 200);

	Open_polyline poly1, poly2;
	poly1.add(n(c));
	poly1.add(s(c));
	poly1.add(e(c));
	poly1.add(w(c));
	poly1.add(center(c));
	poly1.add(ne(c));
	poly1.add(se(c));
	poly1.add(sw(c));
	poly1.add(nw(c));

	poly2.add(n(el));
	poly2.add(s(el));
	poly2.add(e(el));
	poly2.add(w(el));
	poly2.add(center(el));
	poly2.add(ne(el));
	poly2.add(se(el));
	poly2.add(sw(el));
	poly2.add(nw(el));

	win.attach(c);
	win.attach(el);
	win.attach(poly1);
	win.attach(poly2);
	win.wait_for_button();
}
Beispiel #3
0
Rect32 TransformTools::newRect(const Rect32 &oldRect, const TransformStruct &transform, Point32 *newHotspot) {
	Point32 nw(oldRect.left, oldRect.top);
	Point32 ne(oldRect.right, oldRect.top);
	Point32 sw(oldRect.left, oldRect.bottom);
	Point32 se(oldRect.right, oldRect.bottom);

	FloatPoint nw1, ne1, sw1, se1;

	nw1 = transformPoint(nw - transform._hotspot, transform._angle, transform._zoom);
	ne1 = transformPoint(ne - transform._hotspot, transform._angle, transform._zoom);
	sw1 = transformPoint(sw - transform._hotspot, transform._angle, transform._zoom);
	se1 = transformPoint(se - transform._hotspot, transform._angle, transform._zoom);

	float top = MIN(nw1.y, MIN(ne1.y, MIN(sw1.y, se1.y)));
	float bottom = MAX(nw1.y, MAX(ne1.y, MAX(sw1.y, se1.y)));
	float left = MIN(nw1.x, MIN(ne1.x, MIN(sw1.x, se1.x)));
	float right = MAX(nw1.x, MAX(ne1.x, MAX(sw1.x, se1.x)));

	if (newHotspot) {
		newHotspot->y = (uint32)(-floor(top));
		newHotspot->x = (uint32)(-floor(left));
	}

	Rect32 res;
	res.top = (int32)(floor(top)) + transform._hotspot.y;
	res.bottom = (int32)(ceil(bottom)) + transform._hotspot.y;
	res.left = (int32)(floor(left)) + transform._hotspot.x;
	res.right = (int32)(ceil(right)) + transform._hotspot.x;

	return res;
}
Beispiel #4
0
int main(int argc, char *argv[])
{
  QTranslator qtTranslator;
  QTranslator nooTranslator;
  QApplication a(argc, argv);
  a.setApplicationName("Nootini");
  gl = new Tglobals(); // load configuration from temp file
  gl->path = Tglobals::getInstPath(qApp->applicationDirPath());
  if (!initCoreLibrary())
    return 110;
  prepareTranslations(&a, qtTranslator, nooTranslator);
  if (!loadNootkaFont(&a))
    return 111;

  QString fName = "";
  if (a.arguments().size() > 1)
    fName = a.arguments()[1];
  NootiniWindow nw(fName);
  nw.show();

  int exitCode = a.exec();

  delete gl;
  return exitCode;
}
Beispiel #5
0
char *ht(char *c)
{

  char *x;
   int  e =0;
   int  i;

  if(c[0] == 0x22 || c[0] == 0x27 || c[0] == '`'){
    for(i=1;c[i]!='\0';i++){
      if(c[i] == 0x22 || c[i] == 0x27 || c[i] == '`'){
        e = i; break;
      }
    }
  } else{
    for(i=0;c[i]!='\0';i++){
      if(nw(c[i])){
        e = i; break;
      }
    }
  }

  if(e == 0){ return NULL; }

  if((x = (char *)malloc(e+1)) == NULL){
    return NULL;
  }

  strncpy(x,c,e);

  x[e] = '\0';

  return x;

}
Beispiel #6
0
void testLampGetSrcDstObject(const string &dst, bool has_direction_support)
{
	Udm::SmartDataNetwork nw(LampDiagram::diagram);
	nw.CreateNew(dst, "LampDiagram", LampDiagram::RootFolder::meta, Udm::CHANGES_LOST_DEFAULT);

	LampDiagram::RootFolder rf = LampDiagram::RootFolder::Cast(nw.GetRootObject());
	LampDiagram::Lamp lamp = LampDiagram::Lamp::Create(rf);

	LampDiagram::ControlLink cl = LampDiagram::ControlLink::Create(lamp);
	LampDiagram::Bulb bulb = LampDiagram::Bulb::Create(lamp);
	LampDiagram::Switch mswitch = LampDiagram::Switch::Create(lamp, LampDiagram::Lamp::meta_MainSwitch);
	
	cl.src_end() = bulb;
	cl.dst_end() = mswitch;

	if (has_direction_support) {
		CPPUNIT_ASSERT( cl.getSrcObject() == bulb );
		CPPUNIT_ASSERT( cl.getDstObject() == mswitch );
	} else {
		CPPUNIT_ASSERT( cl.getSrcObject() == &Udm::_null );
		CPPUNIT_ASSERT( cl.getDstObject() == &Udm::_null );
	}

	nw.CloseNoUpdate();
}
Beispiel #7
0
vectori sampleDisc(const vectorf &weights, const uint num) {
	vectori inds(num, 0);
	int maxind = (int) weights.size() - 1;

	// normalize weights
	vectorf nw(weights.size());

	nw[0] = weights[0];
	for (uint k = 1; k < weights.size(); k++)
		nw[k] = nw[k - 1] + weights[k];

	// get uniform random numbers
	static vectorf r;
	r = randfloatvec(num);

	//#pragma omp parallel for
	for (int k = 0; k < (int) num; k++)
		for (uint j = 0; j < weights.size(); j++) {
			if (r[k] > nw[j] && inds[k] < maxind)
				inds[k]++;
			else
				break;
		}

	return inds;

}
TEST_F(CoordinateGridBasicTest, FourPosInitializationCornersOk) {

  vposition sw( 0.00,0.00);
  vposition nw( 0.30,0.10);
  vposition ne( 0.30,0.35);
  vposition se(-0.01,0.30);

  /*
    std::cout << format::dd;
    std::cout << sw << std::endl;
    std::cout << nw << std::endl;
    std::cout << ne << std::endl;
    std::cout << se << std::endl;
  */

  CoordinateGrid cg(sw,nw,ne,se);

  // Expect the "middle" point to be within boundries.

  ASSERT_GT(cg.getCenter().coords.a[0],cg.getSW().coords.a[0]);
  ASSERT_GT(cg.getCenter().coords.a[1],cg.getSW().coords.a[1]);

  ASSERT_LT(cg.getCenter().coords.a[0],cg.getNE().coords.a[0]);
  ASSERT_LT(cg.getCenter().coords.a[1],cg.getNE().coords.a[1]);

  ASSERT_LT(cg.getCenter().coords.a[0],cg.getNW().coords.a[0]);
  ASSERT_GT(cg.getCenter().coords.a[1],cg.getNW().coords.a[1]);

  ASSERT_GT(cg.getCenter().coords.a[0],cg.getSE().coords.a[0]);
  ASSERT_LT(cg.getCenter().coords.a[1],cg.getSE().coords.a[1]);
}
Beispiel #9
0
/*
  1.26 ClipEar implements the Clipping-Ear-Algorithm.
  It finds an "Ear" in this Face, clips it and returns it as separate face.
  Note that the original Face is modified by this method!
  It is mainly used to implement evaporisation of faces
 
*/
Face Face::ClipEar() {
    Face ret;

    if (v.size() <= 3) {
        // Nothing to do if this Face consists only of three points
        return Face(v);
    } else {
        Pt a, b, c;
        unsigned int n = v.size();

        // Go through the corner-points, which are sorted counter-clockwise
        for (unsigned int i = 0; i < n; i++) {
            // Take the next three points
            a = v[(i + 0) % n].s;
            b = v[(i + 1) % n].s;
            c = v[(i + 2) % n].s;
            if (Pt::sign(a, b, c) < 0) {
                // If the third point c is right of the segment (a b), then
                // the three points don't form an "Ear"
                continue;
            }

            // Otherwise check, if any point is inside the triangle (a b c)
            bool inside = false;
            for (unsigned int j = 0; j < (n - 3); j++) {
                Pt x = v[(i + j + 3) % n].s;
                inside = Pt::insideTriangle(a, b, c, x) &&
                        !(a == x) && !(b == x) && !(c == x);
                if (inside) {
                    // If a point inside was found, we haven't found an ear.
                    break;
                }
            }

            if (!inside) {
                // No point was inside, so build the Ear-Face in "ret",
                ret.AddSeg(v[i + 0]);
                ret.AddSeg(v[(i + 1)%n]);
                Seg nw(v[(i + 1)%n].e, v[i + 0].s);
                ret.AddSeg(nw);
                
                // remove the Face-Segment (a b),
                v.erase(v.begin() + i);
                
                // and finally replace the segment (b c) by (a c)
                v[i].s = nw.e;
                v[i].e = nw.s;
                hullSeg.valid = 0;

                return ret;
            }
        }
    }
    
    DEBUG(2, "No ear found on face " << ToString());
    // If we are here it means we haven't found an ear. This shouldn't happen.
    // One reason could be that the face wasn't valid in the first place.
    return ret;
}
Beispiel #10
0
int main()
{
        knob_ctl_img kc(1350, 512, 20, 20);
        number_writer nw(kc, 100, 200, 24, 20);
        mudd_hacks::clock ck(nw);
        
        ck.run();
}
Beispiel #11
0
void deque::ensure_capacity(size_t need_size) {
	if (need_size >= capacity) {
		need_size *= 2;
		deque nw(need_size);
		for (const_iterator it = cbegin(); it != cend(); ++it) {
			nw.push_back(*it);
		}
		swap(*this, nw);
	}
}
Beispiel #12
0
void DrawPolar(QPainter *p,pigalePaint *paint)
  {TopologicalGraph G(paint->GCP);
  Prop<Tpoint> Vcoord(G.Set(tvertex()),PROP_DRAW_COORD);
  Prop<Tpoint> Epoint1(G.Set(tedge()),PROP_DRAW_POINT_1);
  Prop<Tpoint> Epoint2(G.Set(tedge()),PROP_DRAW_POINT_2);
  Prop<Tpoint> Epoint11(G.Set(tedge()),PROP_DRAW_POINT_3);
  Prop<Tpoint> Epoint12(G.Set(tedge()),PROP_DRAW_POINT_4);
  Prop<Tpoint> Epoint21(G.Set(tedge()),PROP_DRAW_POINT_5);
  Prop<Tpoint> Epoint22(G.Set(tedge()),PROP_DRAW_POINT_6);
  Prop<double> Erho   (G.Set(tedge()),PROP_DRAW_DBLE_1);
  Prop<double> Etheta1(G.Set(tedge()),PROP_DRAW_DBLE_2);
  Prop<double> Etheta2(G.Set(tedge()),PROP_DRAW_DBLE_3);
  Prop1<double> nw(G.Set(),PROP_DRAW_DBLE_1);
  Prop<short> vcolor(G.Set(tvertex()),PROP_COLOR);
  int m = G.ne(); 
  int ox,oy,nx,ny,theta,dt;
  QPen pn = p->pen();pn.setWidth(1);

  for (tedge ee=1; ee<=m; ee++)
      {if (Erho[ee]==-1)
          {paint->DrawSeg(p,Epoint1[ee],Epoint2[ee],Red);
          continue;
          }
      if (Epoint11[ee]!=Tpoint(-1,-1))
          {paint->DrawSeg(p,Epoint1[ee],Epoint11[ee],Blue);
          paint->DrawSeg(p,Epoint11[ee],Epoint12[ee],Blue);
          }
      else if (Epoint12[ee]!=Tpoint(-1,-1))
          paint->DrawSeg(p,Epoint1[ee],Epoint12[ee],Blue);
      if (Epoint21[ee]!=Tpoint(-1,-1))
          {paint->DrawSeg(p,Epoint2[ee],Epoint21[ee],Blue);
          paint->DrawSeg(p,Epoint21[ee],Epoint22[ee],Blue);
          }
      else if (Epoint22[ee]!=Tpoint(-1,-1))
          paint->DrawSeg(p,Epoint2[ee],Epoint22[ee],Blue);
	  
      pn.setColor(color[Blue]);pn.setWidth(2);p->setPen(pn);
      ox = paint->to_x(-Erho[ee]);
      oy = paint->to_y(Erho[ee]);
      nx = (int)(2*Erho[ee]*paint->xscale + .5);
      ny = (int)(2*Erho[ee]*paint->yscale + .5);
      theta = (int)(Etheta1[ee]*16*180/PI+.5);
      dt = (int)((Etheta2[ee] - Etheta1[ee])*16*180/PI+.5); 
      p->drawArc(ox,oy,nx,ny,theta,dt);
      }
  
  // Draw the vertices
  double dx = .001;
  for(tvertex v = 1;v <= G.nv();v++)
      {double x = Vcoord[v].x()-dx*.5;
      double y = Vcoord[v].y()-dx*.5;
      Tpoint pt(x,y);
      paint->DrawText(p,pt, v,vcolor[v],1);
      }
  }
Beispiel #13
0
/**
 * Loads the mission data from a YAML node.
 * @param node YAML node.
 */
void RuleAlienMission::load(const YAML::Node &node)
{
	_type = node["type"].as<std::string>(_type);
	_points = node["points"].as<int>(_points);
	_waves = node["waves"].as< std::vector<MissionWave> >(_waves);
	//Only allow full replacement of mission racial distribution.
	if (const YAML::Node &weights = node["raceWeights"])
	{
		typedef std::map<unsigned, WeightedOptions*> Associative;
		typedef std::vector<std::pair<unsigned, WeightedOptions*> > Linear;

		Associative assoc;
		//Place in the associative container so we can index by month and keep entries sorted.
		for (Linear::iterator ii = _raceDistribution.begin(); ii != _raceDistribution.end(); ++ii)
		{
			assoc.insert(*ii);
		}

		// Now go through the node contents and merge with existing data.
		for (YAML::const_iterator nn = weights.begin(); nn != weights.end(); ++nn)
		{
			unsigned month = nn->first.as<unsigned>();
			Associative::iterator existing = assoc.find(month);
			if (assoc.end() == existing)
			{
				// New entry, load and add it.
				std::auto_ptr<WeightedOptions> nw(new WeightedOptions);
				nw->load(nn->second);
				assoc.insert(std::make_pair(month, nw.release()));
			}
			else
			{
				// Existing entry, update it.
				existing->second->load(nn->second);
			}
		}

		// Now replace values in our actual member variable!
		_raceDistribution.clear();
		_raceDistribution.reserve(assoc.size());
		for (Associative::iterator ii = assoc.begin(); ii != assoc.end(); ++ii)
		{
			if (ii->second->empty())
			{
				// Don't keep empty lists.
				delete ii->second;
			}
			else
			{
				// Place it
				_raceDistribution.push_back(*ii);
			}
		}
	}
}
Beispiel #14
0
//'@rdname neighbours
//'@export
// [[Rcpp::export]]
DataFrame gh_neighbours(CharacterVector hashes){

  unsigned int input_size = hashes.size();
  CharacterVector north(input_size);
  CharacterVector ne(input_size);
  CharacterVector east(input_size);
  CharacterVector se(input_size);
  CharacterVector south(input_size);
  CharacterVector sw(input_size);
  CharacterVector west(input_size);
  CharacterVector nw(input_size);
  std::vector < std::string > holding(8);

  for(unsigned int i = 0; i < input_size; i++){

    if((i % 10000) == 0){
      Rcpp::checkUserInterrupt();
    }

    if(CharacterVector::is_na(hashes[i])){
      north[i] = NA_REAL;
      ne[i] = NA_REAL;
      east[i] = NA_REAL;
      se[i] = NA_REAL;
      south[i] = NA_REAL;
      sw[i] = NA_REAL;
      west[i] = NA_REAL;
      nw[i] = NA_REAL;
    } else {

      holding = cgeohash::all_neighbours(Rcpp::as<std::string>(hashes[i]));

      north[i] = holding[0];
      ne[i] =  holding[1];
      east[i] =  holding[2];
      se[i] =  holding[3];
      south[i] =  holding[4];
      sw[i] =  holding[5];
      west[i] =  holding[6];
      nw[i] =  holding[7];
    }

  }

  return DataFrame::create(_["north"] = north,
                           _["northeast"] = ne,
                           _["east"] = east,
                           _["southeast"] = se,
                           _["south"] = south,
                           _["southwest"] = sw,
                           _["west"] = west,
                           _["northwest"] = nw,
                           _["stringsAsFactors"] = false);

}
Beispiel #15
0
MatrixXd LDA::getPhi(void) {

    if(SAMPLE_LAG >0) {
        return phisum*(1.0/numstats);
    } else {
        MatrixXd phi(K,V);
        for(int k=0; k<K; k++)
            for(int w=0; w<V; w++)
                phi(k,w)=(nw(w,k)+beta)/(nwsum(k)+V*beta);
        return phi;
    }
}
Beispiel #16
0
void LDA::updateParams(void) {
    for(int m=0; m<documentsSize(); m++) {
        for(int k=0; k<K; k++) {
            thetasum(m,k)+=(nd(m,k)+alpha)/(ndsum(m)+K*alpha);
        }
    }
    for(int k=0; k<K; k++) {
        for(int w=0; w<V; w++) {
            phisum(k,w)+= (nw(w,k)+beta)/(nwsum(k)+V*beta);
        }
    }
    numstats++;
}
Beispiel #17
0
void GFXDrawUtil::drawRect( const Point2F &upperLeft, const Point2F &lowerRight, const ColorI &color )
{
   //
   // Convert Box   a----------x
   //               |          |
   //               x----------b
   //
   // Into Triangle-Strip Outline
   //               v0-----------v2
   //               | a         x |
   //               |  v1-----v3  |
   //               |   |     |   |
   //               |  v7-----v5  |
   //               | x         b |
   //               v6-----------v4
   //

   // NorthWest and NorthEast facing offset vectors
   // These adjust the thickness of the line, it'd be neat if one day
   // they were passed in as arguments.
   Point2F nw(-0.5f,-0.5f); /*  \  */
   Point2F ne(0.5f,-0.5f); /*  /  */

   GFXVertexBufferHandle<GFXVertexPC> verts (mDevice, 10, GFXBufferTypeVolatile );
   verts.lock();

   F32 ulOffset = 0.5f - mDevice->getFillConventionOffset();

   verts[0].point.set( upperLeft.x + ulOffset + nw.x, upperLeft.y + ulOffset + nw.y, 0.0f );
   verts[1].point.set( upperLeft.x + ulOffset - nw.x, upperLeft.y + ulOffset - nw.y, 0.0f );
   verts[2].point.set( lowerRight.x + ne.x, upperLeft.y + ulOffset + ne.y, 0.0f );
   verts[3].point.set( lowerRight.x - ne.x, upperLeft.y + ulOffset - ne.y, 0.0f );
   verts[4].point.set( lowerRight.x - nw.x, lowerRight.y - nw.y, 0.0f );
   verts[5].point.set( lowerRight.x + nw.x, lowerRight.y + nw.y, 0.0f );
   verts[6].point.set( upperLeft.x + ulOffset - ne.x, lowerRight.y - ne.y, 0.0f );
   verts[7].point.set( upperLeft.x + ulOffset + ne.x, lowerRight.y + ne.y, 0.0f );
   verts[8].point.set( upperLeft.x + ulOffset + nw.x, upperLeft.y + ulOffset + nw.y, 0.0f ); // same as 0
   verts[9].point.set( upperLeft.x + ulOffset - nw.x, upperLeft.y + ulOffset - nw.y, 0.0f ); // same as 1

   for (S32 i=0; i<10; i++)
      verts[i].color = color;

   verts.unlock();
   mDevice->setVertexBuffer( verts );

   mDevice->setStateBlock(mRectFillSB);
   mDevice->setupGenericShaders();
   mDevice->drawPrimitive( GFXTriangleStrip, 0, 8 );
}
Beispiel #18
0
/*
 * Provide a series of lat/lon coordinates/waypoints, and the object
 * automatically generates a bounding rectangle, and determines how to
 * translate between lat/lon and cartesian x/y
 */
void Mapping::init(int count, GeoPosition *p)
{
    double latMin = 360;
    double latMax = -360;
    double lonMin = 360;
    double lonMax = -360;
    
    // Find minimum and maximum lat/lon
    for (int i=0; i < count; i++, p++) {
        //fprintf(stdout, "%d (%.6f, %.6f)\n", i, p->latitude(), p->longitude());
        if (p->latitude() > latMax)
            latMax = p->latitude();
        if (p->latitude() < latMin)
            latMin = p->latitude();
            
        if (p->longitude() > lonMax)
            lonMax = p->longitude();
        if (p->longitude() < lonMin)
            lonMin = p->longitude();
    }

    // Set the arbitrary cartesian origin to southwest corner
    lonZero = lonMin;
    latZero = latMin;

    //fprintf(stdout, "min: (%.6f, %.6f)\n", latMin, lonMin);
    //fprintf(stdout, "max: (%.6f, %.6f)\n", latMax, lonMax);

    // Three positions required to scale
    GeoPosition sw(latMin, lonMin);
    GeoPosition nw(latMax, lonMin);
    GeoPosition se(latMin, lonMax);
    
    // Find difference between lat and lon min/max
    float dlat = (latMax - latMin);
    float dlon = (lonMax - lonMin);
    
    //fprintf(stdout, "dlat=%.6f dlon=%.6f\n", dlat, dlon);
    
    // Compute scale based on distances between edges of rectangle
    // and difference between min/max lat and min/max lon
    lonToX = sw.distanceTo(se) / dlon;
    latToY = sw.distanceTo(nw) / dlat;

    //fprintf(stdout, "lonToX=%.10f\nlatToY=%.10f\n", lonToX, latToY);

    return;    
}
Beispiel #19
0
int main(int argc, char* argv[])
{
    std::vector<std::string> args;

    for (int i = 1; i < argc; ++i)
        args.push_back(argv[i]);

    try
    {
        pdal::nitfwrap::NitfWrap nw(args);
    }
    catch (pdal::nitfwrap::error err)
    {
        std::cerr << "nitfwrap: " << err.what() << "\n";
    }
}
Beispiel #20
0
bool Topology::isUpstream(const Identity &id) const
{
	if (isRoot(id))
		return true;
	std::vector< SharedPtr<Network> > nws(RR->node->allNetworks());
	for(std::vector< SharedPtr<Network> >::const_iterator nw(nws.begin());nw!=nws.end();++nw) {
		SharedPtr<NetworkConfig> nc((*nw)->config2());
		if (nc) {
			for(std::vector< std::pair<Address,InetAddress> >::const_iterator r(nc->relays().begin());r!=nc->relays().end();++r) {
				if (r->first == id.address())
					return true;
			}
		}
	}
	return false;
}
Beispiel #21
0
// Transform tMapExtents
tMapExtents tMap2dTransform::Transform( tMapExtents& Extents )
{
    // Create nw and se extents
    tVector2l nw( Extents.m_Sw.x, Extents.m_Ne.y );
    tVector2l se( Extents.m_Ne.x, Extents.m_Sw.y );

    tMapExtents newExtents;

    // Transform all 4 corners

    newExtents.AdjustExtents( Transform2dVector( Extents.m_Sw ) ); 
    newExtents.AdjustExtents( Transform2dVector( Extents.m_Ne ) ); 
    newExtents.AdjustExtents( Transform2dVector( nw ) ); 
    newExtents.AdjustExtents( Transform2dVector( se ) ); 

    return newExtents;
}
int main() {
	Simple_window win1{x,800,600,"Rectangle functions"};
	Graph_lib::Rectangle r{Point {200,200},150,250};
	Graph_lib::Marks m{"x"};
	m.add(n(r));
	m.add(w(r));
	m.add(s(r));
	m.add(e(r));
	m.add(center(r));
	m.add(nw(r));
	m.add(ne(r));
	m.add(sw(r));
	m.add(se(r));
	win1.attach(r);
	win1.attach(m);
	win1.wait_for_button();
}
Beispiel #23
0
void LDA::initialState(int K) {
    int M=documentsSize(),N=(*documents).cols();
    nw = MatrixXi::Zero(V,K);
    nd = MatrixXi::Zero(M,K);
    nwsum = VectorXi::Zero(K);
    ndsum = VectorXi(M);

    z=(MatrixXd::Random(M,N).cwiseAbs()*K).cast<int>();
    ndsum.fill(N);
    for(int i=0; i<M; i++) {
        for(int j=0; j<N; j++) {
            nw((*documents)(i,j),z(i,j))++;
            nd(i,z(i,j))++;
            nwsum(z(i,j))++;
        }
    }

}
double ImageAnalysis::HistogramCompare(IplImage* n, IplImage *p)
{
    //Сравнение гистограмм

     Mat nw(n);
     Mat pr(p);
     Mat hvs_nw,hvs_pr;

     /// Convert to HSV
     cvtColor( nw, hvs_nw, COLOR_BGR2HSV );
     cvtColor( pr, hvs_pr, COLOR_BGR2HSV );

     int h_bins = 50; int s_bins = 60;
     int histSize[] = { h_bins, s_bins };

     // hue varies from 0 to 179, saturation from 0 to 255
     float h_ranges[] = { 0, 180 };
     float s_ranges[] = { 0, 256 };

     const float* ranges[] = { h_ranges, s_ranges };

     // Use the o-th and 1-st channels
     int channels[] = { 0, 1 };

     MatND hist_nw;
     MatND hist_pr;

     /// Calculate the histograms for the HSV images
     calcHist( &hvs_nw, 1, channels, Mat(), hist_nw, 2, histSize, ranges, true, false );
     normalize( hist_nw, hist_nw, 0, 1, NORM_MINMAX, -1, Mat() );

     calcHist( &hvs_pr, 1, channels, Mat(), hist_pr, 2, histSize, ranges, true, false );
     normalize( hist_pr, hist_pr, 0, 1, NORM_MINMAX, -1, Mat() );

     double percent=compareHist( hist_nw, hist_pr, 0);//using Correlation method
     nw.release();
     pr.release();
     hist_nw.release();
     hist_pr.release();
     hvs_nw.release();
     hvs_pr.release();

     return percent;
}
Beispiel #25
0
bool MethodWriter::call_gene( const String &method, Type *type_0, const Mos &arg_0, const String &ret, bool abort_if_not_found ) {
    MethodWriter nw( this );
    nw.type[ 0 ] = type_0;
    nw.arg [ 0 ] = arg_0;
    nw.ret_ins = ret.size() ? ret : ret_ins;
    #define DECL_MET( T, N ) \
        if ( method == #N ) { \
            typedef MethodFinder<MethodName_##N> MF; \
            if ( MF::Item *item = MF::find_item( type_0, 0, 0, abort_if_not_found, true ) ) { \
                item->gene( nw ); \
                return true; \
            } \
            return false; \
        }
    #include "DeclMethodsUnary.h"
    #undef DECL_MET
    ERROR( "unknown method name %s (assuming nb_arg == 1)", method.c_str() );
    return false;
}
Beispiel #26
0
void set_pivot_from_preferences(gfx::Transformation& t)
{
  gfx::Transformation::Corners corners;
  t.transformBox(corners);
  gfx::PointT<double> nw(corners[gfx::Transformation::Corners::LEFT_TOP]);
  gfx::PointT<double> ne(corners[gfx::Transformation::Corners::RIGHT_TOP]);
  gfx::PointT<double> sw(corners[gfx::Transformation::Corners::LEFT_BOTTOM]);
  gfx::PointT<double> se(corners[gfx::Transformation::Corners::RIGHT_BOTTOM]);
  gfx::PointT<double> pivotPos((nw + se) / 2);

  app::gen::PivotPosition pivot = Preferences::instance().selection.pivotPosition();
  switch (pivot) {
    case app::gen::PivotPosition::NORTHWEST:
      pivotPos = nw;
      break;
    case app::gen::PivotPosition::NORTH:
      pivotPos = (nw + ne) / 2.0;
      break;
    case app::gen::PivotPosition::NORTHEAST:
      pivotPos = ne;
      break;
    case app::gen::PivotPosition::WEST:
      pivotPos = (nw + sw) / 2.0;
      break;
    case app::gen::PivotPosition::EAST:
      pivotPos = (ne + se) / 2.0;
      break;
    case app::gen::PivotPosition::SOUTHWEST:
      pivotPos = sw;
      break;
    case app::gen::PivotPosition::SOUTH:
      pivotPos = (sw + se) / 2.0;
      break;
    case app::gen::PivotPosition::SOUTHEAST:
      pivotPos = se;
      break;
  }

  t.displacePivotTo(gfx::PointF(pivotPos));
}
Beispiel #27
0
  /** Add walkers to the end of the ensemble of walkers.  
   * @param nwalkers number of walkers to add
   */
  void 
  QMCDriver::addWalkers(int nwalkers) {

    if(nwalkers>0) {
      //add nwalkers walkers to the end of the ensemble
      int nold = W.getActiveWalkers();

      app_log() << "  Adding " << nwalkers << " walkers to " << nold << " existing sets" << endl;

      W.createWalkers(nwalkers);
      if(nold)
      {
        int iw=nold;
        for(MCWalkerConfiguration::iterator it=W.begin()+nold; it != W.end(); ++it,++iw)
          (*it)->R=W[iw%nold]->R;//assign existing walker configurations when the number of walkers change
      }

    } else if(nwalkers<0) {
      W.destroyWalkers(-nwalkers);
      app_log() << "  Removed " << -nwalkers << " walkers. Current number of walkers =" << W.getActiveWalkers() << endl;
    } else {
      app_log() << "  Using the current " << W.getActiveWalkers() << " walkers." <<  endl;
    }

    //update the global number of walkers
    //int nw=W.getActiveWalkers();
    //myComm->allreduce(nw);
    vector<int> nw(myComm->size(),0),nwoff(myComm->size()+1,0);
    nw[myComm->rank()]=W.getActiveWalkers();
    myComm->allreduce(nw);

    for(int ip=0; ip<myComm->size(); ip++) nwoff[ip+1]=nwoff[ip]+nw[ip];
    W.setGlobalNumWalkers(nwoff[myComm->size()]);
    W.setWalkerOffsets(nwoff);

    app_log() << "  Total number of walkers: " << W.EnsembleProperty.NumSamples  <<  endl;
    app_log() << "  Total weight: " << W.EnsembleProperty.Weight  <<  endl;
  }
Beispiel #28
0
void GFXDrawUtil::drawRectFill( const Point2F &upperLeft, const Point2F &lowerRight, const ColorI &color )
{
   //
   // Convert Box   a----------x
   //               |          |
   //               x----------b
   // Into Quad
   //               v0---------v1
   //               | a       x |
   //               |           |
   //               | x       b |
   //               v2---------v3
   //

   // NorthWest and NorthEast facing offset vectors
   Point2F nw(-0.5,-0.5); /*  \  */
   Point2F ne(0.5,-0.5); /*  /  */

   GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, 4, GFXBufferTypeVolatile);
   verts.lock();

   F32 ulOffset = 0.5f - mDevice->getFillConventionOffset();
   
   verts[0].point.set( upperLeft.x+nw.x+ulOffset, upperLeft.y+nw.y+ulOffset, 0.0f );
   verts[1].point.set( lowerRight.x+ne.x, upperLeft.y+ne.y+ulOffset, 0.0f );
   verts[2].point.set( upperLeft.x-ne.x+ulOffset, lowerRight.y-ne.y, 0.0f );
   verts[3].point.set( lowerRight.x-nw.x, lowerRight.y-nw.y, 0.0f );

   for (S32 i=0; i<4; i++)
      verts[i].color = color;

   verts.unlock();

   mDevice->setStateBlock(mRectFillSB);
   mDevice->setVertexBuffer( verts );
   mDevice->setupGenericShaders();
   mDevice->drawPrimitive( GFXTriangleStrip, 0, 2 );
}
Beispiel #29
0
void CMainWindow::centerWindow()
{
    int screen = 0;
    QWidget *w = window();
    QDesktopWidget *desktop = QApplication::desktop();
    if (w) {
        screen = desktop->screenNumber(w);
    } else if (desktop->isVirtualDesktop()) {
        screen = desktop->screenNumber(QCursor::pos());
    } else {
        screen = desktop->screenNumber(this);
    }
    QRect rect(desktop->availableGeometry(screen));
        int h = 80*rect.height()/100;
    QSize nw(135*h/100,h);
    if (nw.width()<1000) nw.setWidth(80*rect.width()/100);
    resize(nw);
    move(rect.width()/2 - frameGeometry().width()/2,
         rect.height()/2 - frameGeometry().height()/2);

    QList<int> sz;
    sz << nw.width()/4 << 3*nw.width()/4;
    ui->splitter->setSizes(sz);
}
Beispiel #30
0
void ClusterInterface::HandleTeleportResult(WorldPacket & pck)
{
	uint32 sessionid;
	uint8 result;
	uint32 mapid, instanceid;
	LocationVector vec;
	float o;

	pck >> sessionid;

	WorldSession* s = GetSession(sessionid);

	if (!s)
	{
		//tell the realm-server we have no session
		WorldPacket data(ICMSG_ERROR_HANDLER, 5);
		data << uint8(1); //1 = no session
		data << sessionid;
		sClusterInterface.SendPacket(&data);
		return;
	}

	pck >> result >> mapid >> instanceid >> vec >> o;

	//the destination is on the same server
	if (result == 1)
	{
		if (s->GetPlayer() != NULL)
			sEventMgr.AddEvent(s->GetPlayer(), &Player::EventClusterMapChange, mapid, instanceid, vec, EVENT_UNK, 1, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
	}
	else
	{
		//make this non-async, needs redone to support packing the player
		//since were saving it HAS TO BE HERE so the new server has the correct data
		WorldPacket nw(SMSG_NEW_WORLD);
		nw << mapid << vec << o;
		s->SendPacket(&nw);

		uint32 oldmapid = s->GetPlayer()->GetMapId();
		uint32 oldinstanceid = s->GetPlayer()->GetInstanceID();
		uint32 playerlowguid = s->GetPlayer()->GetLowGUID();
		s->GetPlayer()->SetMapId(mapid);
		s->GetPlayer()->SetInstanceID(instanceid);
		s->GetPlayer()->SetPosition(vec.x, vec.y, vec.z, o);
		s->GetPlayer()->SaveToDB(true);

		//need to shift back to old ones for removing from world :)
		s->GetPlayer()->SetMapId(oldmapid);
		s->GetPlayer()->SetInstanceID(oldinstanceid);

		WorldPacket data(ICMSG_SWITCH_SERVER, 100);
		data << sessionid << playerlowguid << mapid << instanceid << vec << o;
		sClusterInterface.SendPacket(&data);

		RPlayerInfo * pRPlayer = GetPlayer(playerlowguid);
		bool newRplr = false;
		if(pRPlayer == NULL)
		{
			pRPlayer = new RPlayerInfo;
			newRplr = true;
		}
		s->GetPlayer()->UpdateRPlayerInfo(pRPlayer, newRplr);
		pRPlayer->MapId = mapid;
		pRPlayer->InstanceId = instanceid;
		data.Initialize(ICMSG_PLAYER_INFO);
		pRPlayer->Pack(data);
		sClusterInterface.SendPacket(&data);

		sEventMgr.AddEvent(s->GetPlayer(), &Player::HandleClusterRemove, EVENT_UNK, 1, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
	}
}