Example #1
0
File: test.cpp Project: ak795/acm
template<class T> void print(vector<T> A, int n=-1) { if (n==-1) n=A.size(); cout<<"{"; for (int i=0; i<n; i++) { cout<<A[i]; if (i+1<n) cout<<", "; } cout<<"}"<<endl; }
float CaffeFeatExtractor<Dtype>::extractBatch_multipleFeat(vector<cv::Mat> &images, int new_batch_size, vector< Blob<Dtype>* > &features) {

    // Set the GPU/CPU mode for Caffe (here in order to be thread-safe)
    if (gpu_mode)
    {
        Caffe::set_mode(Caffe::GPU);
        Caffe::SetDevice(device_id);
    }
    else
    {
        Caffe::set_mode(Caffe::CPU);
    }

    cudaEvent_t start, stop;

    if (timing)
    {
        cudaEventCreate(&start);
        cudaEventCreate(&stop);
        cudaEventRecord(start, NULL);
    }

    // Initialize labels to zero
    vector<int> labels(images.size(), 0);

    // Get pointer to data layer to set the input
    caffe::shared_ptr<MemoryDataLayer<Dtype> > memory_data_layer = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<Dtype> >(feature_extraction_net->layers()[0]);

    // Set batch size

    if (memory_data_layer->batch_size()!=new_batch_size)
    {
        if (images.size()%new_batch_size==0)
        {
            memory_data_layer->set_batch_size(new_batch_size);
            cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
        }
        else
        {
            if (images.size()%memory_data_layer->batch_size()==0)
            {
                cout << "WARNING: image number is not multiple of requested batch size, leaving the old one..." << endl;
                cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
            } else
            {
                cout << "WARNING: image number is not multiple of batch size, setting it to 1 (performance issue)..." << endl;
                memory_data_layer->set_batch_size(1);
                cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
            }

        }

    } else
    {
        if (images.size()%memory_data_layer->batch_size()!=0)
        {
            cout << "WARNING: image number is not multiple of batch size, setting it to 1 (performance issue)..." << endl;
            memory_data_layer->set_batch_size(1);
            cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
        }
    }

    int num_batches = images.size()/new_batch_size;

    // Input preprocessing

    // The image passed to AddMatVector must be same size as the mean image
    // If not, it is resized anisotropically (BILINEAR)
    // if it is downsampled, LANCZOS4 is used for antialiasing

    for (int i=0; i<images.size(); i++)
    {
        if (images[i].rows != mean_height || images[i].cols != mean_height)
        {
            if (images[i].rows > mean_height || images[i].cols > mean_height)
            {
                cv::resize(images[i], images[i], cv::Size(mean_height, mean_width), 0, 0, CV_INTER_LANCZOS4);
            }
            else
            {
                cv::resize(images[i], images[i], cv::Size(mean_height, mean_width), 0, 0, CV_INTER_LINEAR);
            }
        }
    }

    memory_data_layer->AddMatVector(images,labels);

    size_t num_features = blob_names.size();

    // Run network and retrieve features!

    // depending on your net's architecture, the blobs will hold accuracy and/or labels, etc
    std::vector<Blob<Dtype>*> results;

    for (int b=0; b<num_batches; b++)
    {
        results = feature_extraction_net->Forward();

        for (int i = 0; i < num_features; ++i) {

            const caffe::shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net->blob_by_name(blob_names[i]);

            int batch_size = feature_blob->num();
            int channels = feature_blob->channels();
            int width = feature_blob->width();
            int height = feature_blob->height();

            features.push_back(new Blob<Dtype>(batch_size, channels, height, width));

            features.back()->CopyFrom(*feature_blob);
        }

    }

    if (timing)
    {
        // Record the stop event
        cudaEventRecord(stop, NULL);

        // Wait for the stop event to complete
        cudaEventSynchronize(stop);

        float msecTotal = 0.0f;
        cudaEventElapsedTime(&msecTotal, start, stop);

        float msecPerImage = msecTotal/(float)images.size();

        return msecPerImage;
    }
    else
    {
        return 0;
    }

}
Example #3
0
void make_tree (vector <int> a) {
	t.resize (a.size());
	n = a.size();
	for (int i = 0; i < t.size(); i++) t[i] = inf;
	for (int i = 0; i < a.size(); i++) update (i, a[i]);
}
Example #4
0
vector<int> count_crossings_candidate_list(int point_index, vector<Punto> &candidate_list, vector<Punto> &puntos)
{
    Punto p(0,0);
    int pos_point_in_tp = 0;
    int num_cand = candidate_list.size();
    int num_pts = puntos.size();
    vector<candidato> candidates(num_cand);
    vector<int> cr_list (num_cand, 0);
    vector<int> cr_list2 (num_cand, 0);
    vector<int> cr_list3 (num_cand, 0);
    vector<int> count_change_of_list (num_cand, 0);
    vector<int> count_change_cr_for_q (num_cand, 0);
    int cr2=0;
    int cr3=0;

    for(int i=0; i<num_cand; i++)
    {
        candidates[i].pt = candidate_list[i];
        candidates[i].index =i;
        cr_list2[i]=0;
        cr_list3[i]=0;
        count_change_of_list[i]=0;
        count_change_cr_for_q[i]=0;
    }

    vector<candidato> temp_pts(num_pts-1);
    //int centro=0; unused variable
    vector<candidato> united_points(2*num_pts-3+num_cand);

    for(int centro = 0; centro<num_pts; centro++)
    {
        if(centro != point_index)
        {
            p = puntos[centro];

            for(int i=0; i<centro; i++)
                temp_pts[i].pt = puntos[i];

            for(int i=centro; i<num_pts-1; i++)
                temp_pts[i].pt = puntos[i+1];


            temp_pts=sort_around_point(p,temp_pts);

            for(int i=0; i<num_pts-1; i++)
            {
                temp_pts[i].index=i;
                temp_pts[i].original = true;
                temp_pts[i].antipodal = true;
            }

            //nis for p
            vector<int> nis(num_pts-1);
            int j=0;
            for(int i=0; i<num_pts-1; i++)
            {
                Punto p0 = temp_pts[i].pt;
                Punto p1 = temp_pts[(j+1)%(num_pts-1)].pt;

                while((turn(p,p0,p1)<=0) && ((j+1)%(num_pts-1)!=i))
                {
                    j++;
                    p0=temp_pts[i].pt;
                    p1=temp_pts[(j+1)%(num_pts-1)].pt;
                }

                if((j-i)%(num_pts-1)>=0)
                    nis[i]=(j-i)%(num_pts-1);
                else
                    nis[i]=(j-i)%(num_pts-1)+num_pts-1;
            }

            ///////////aca termina nis
            for(int i=0; i<num_pts-1; i++)                                    //puse un -1
                if(temp_pts[i].pt == puntos[point_index])
                    pos_point_in_tp=i;
            //Suma 2 cr2
            for(int i=0; i<num_pts-1; i++)
                if(i!=pos_point_in_tp)
                    cr2=cr2+(nis[i]*(nis[i]-1)/2);

            /////aca comienza el join_pts_antipodal_candidatelist
            j=0;
            for(int i=0; i<pos_point_in_tp; i++)
            {
                united_points[j] = temp_pts[i];
                j=j+1;
                united_points[j] = temp_pts[i];
                united_points[j].pt.x = 2*p.x-temp_pts[i].pt.x;
                united_points[j].pt.y = 2*p.y-temp_pts[i].pt.y;
                united_points[j].antipodal = false;
                j=j+1;
            }

            united_points[j].pt = temp_pts[pos_point_in_tp].pt;
            j=j+1;

            for(int i=pos_point_in_tp+1; i<num_pts-1; i++)
            {
                united_points[j] = temp_pts[i];
                j=j+1;
                united_points[j] = temp_pts[i];
                united_points[j].pt.x = 2*p.x-temp_pts[i].pt.x;
                united_points[j].pt.y = 2*p.y-temp_pts[i].pt.y;
                united_points[j].original = true;
                united_points[j].antipodal = false;
                j=j+1;
            }

            for(int i=0; i<num_cand; i++)
            {
                united_points[j] = candidates[i];
                j=j+1;
            }

            united_points=sort_around_point(p,united_points);
            ////aca termina el join_pts_antipodal_candidatelist
            int position_p;
            for(int i=0; i<2*num_pts-3+num_cand; i++)
                if(united_points[i].pt == puntos[point_index])
                    position_p=i;

            ///// Aca comenzamos el change_of_cr_for_list
            vector<int> aux_nis(num_pts-1);
            int count_ni=0;
            int sum_ni=0;

            for(int i=0; i<num_pts-1; i++)
                aux_nis[i]=nis[i];

            for(int i=1; i<2*num_pts-3+num_cand; i++)
            {
                int pos=(position_p+i)%(2*num_pts-3+num_cand);
                if (united_points[pos].original)
                {
                    if (united_points[pos].antipodal)
                    {
                        sum_ni=sum_ni+aux_nis[united_points[pos].index];
                        aux_nis[united_points[pos].index]=aux_nis[united_points[pos].index]+1;
                        count_ni--;
                    }
                    else
                    {
                        sum_ni=sum_ni-aux_nis[united_points[pos].index]+1;
                        aux_nis[united_points[pos].index]=aux_nis[united_points[pos].index]-1;
                        count_ni++;
                    }
                }
                else
                {
                    cr_list2[united_points[pos].index]=cr_list2[united_points[pos].index]+sum_ni;
                    count_change_of_list[united_points[pos].index]=count_ni;
                }
            }
            /////// aca terminamos el change_of_cr_for_list

            /////////////////Aca comienza la suma 3 cr3/////////////////
            cr3=cr3+(nis[pos_point_in_tp]*(nis[pos_point_in_tp]-1)/2);
            ///// cr_list3
            for(int i=0; i<num_cand; i++)
                cr_list3[i]=cr_list3[i]+(count_change_of_list[i]+nis[pos_point_in_tp])*(count_change_of_list[i]+nis[pos_point_in_tp]-1)/2;
            //////////////////////////////////fin de la suma 3
        }
    }
    int total=num_pts*(num_pts-1)*(num_pts-2)*(num_pts-3)/8;
    for(int i=0; i<num_cand; i++)
    {
        cr_list2[i]=cr_list2[i]+cr2;
        cr_list[i]=cr_list2[i]+2*cr_list3[i]-total;
    }

    return cr_list;
}
Example #5
0
      } else {
        if(abs(sumteam2 + skill - sumteam1) <= maxskill)
          if(team2.size() + 1 + team1.size() == (i + 1)) {
            team2.push_back(p.second);
            sumteam2 += skill;
          }
      }
    }
    else {
      if(abs(sumteam2 + skill - sumteam1) <= maxskill)
        if(team2.size() + 1 + team1.size() == (i + 1)) {
          team2.push_back(p.second);
          sumteam2 += skill;
        }
    }
  }

  cout << team1.size() << endl;
  REP(i, team1.size()) {
    if(i) cout << " ";
    cout << team1[i];
  }
  cout << endl << team2.size() << endl;
  REP(i, team2.size()) {
    if(i) cout << " ";
    cout << team2[i];
  }
  cout << endl;
}

Example #6
0
// Goes through the contours for the plate and picks out possible char segments based on min/max height
// returns a vector of indices corresponding to valid contours
vector<bool> CharacterAnalysis::filterByParentContour( vector< vector< Point> > contours, vector<Vec4i> hierarchy, vector<bool> goodIndices)
{

    vector<bool> includedIndices(contours.size());
    for (int j = 0; j < contours.size(); j++)
        includedIndices[j] = false;

    vector<int> parentIDs;
    vector<int> votes;

    for (int i = 0; i < contours.size(); i++)
    {
        if (goodIndices[i] == false)
            continue;

        int voteIndex = -1;
        int parentID = hierarchy[i][3];
        // check if parentID is already in the lsit
        for (int j = 0; j < parentIDs.size(); j++)
        {
            if (parentIDs[j] == parentID)
            {
                voteIndex = j;
                break;
            }
        }
        if (voteIndex == -1)
        {
            parentIDs.push_back(parentID);
            votes.push_back(1);
        }
        else
        {
            votes[voteIndex] = votes[voteIndex] + 1;
        }

    }

    // Tally up the votes, pick the winner
    int totalVotes = 0;
    int winningParentId = 0;
    int highestVotes = 0;
    for (int i = 0; i < parentIDs.size(); i++)
    {
        if (votes[i] > highestVotes)
        {
            winningParentId = parentIDs[i];
            highestVotes = votes[i];
        }
        totalVotes += votes[i];
    }

    // Now filter out all the contours with a different parent ID (assuming the totalVotes > 2)
    for (int i = 0; i < contours.size(); i++)
    {
        if (goodIndices[i] == false)
            continue;

        if (totalVotes <= 2)
        {
            includedIndices[i] = true;
        }
        else if (hierarchy[i][3] == winningParentId)
        {
            includedIndices[i] = true;
        }
    }

    return includedIndices;
}
void Planet::InitPlanet( QVector x,
                         QVector y,
                         float vely,
                         const Vector &rotvel,
                         float pos,
                         float gravity,
                         float radius,
                         const string &filename,
                         const string &technique,
                         const string &unitname,
                         const vector< string > &dest,
                         const QVector &orbitcent,
                         Unit *parent,
                         int faction,
                         string fullname,
                         bool inside_out,
                         unsigned int lights_num )
{
    atmosphere = NULL;
    terrain    = NULL;
    static float bodyradius = XMLSupport::parse_float( vs_config->getVariable( "graphics", "star_body_radius", ".33" ) );
    if (lights_num)
        radius *= bodyradius;
    inside = false;
    curr_physical_state.position = prev_physical_state.position = cumulative_transformation.position = orbitcent+x;
    Init();
    //static int neutralfaction=FactionUtil::GetFaction("neutral");
    //this->faction = neutralfaction;
    killed = false;
    bool notJumppoint = dest.empty();
    for (unsigned int i = 0; i < dest.size(); ++i)
        AddDestination( dest[i] );
    //name = "Planet - ";
    //name += textname;
    name = fullname;
    this->fullname = name;
    this->radius   = radius;
    this->gravity  = gravity;
    static float densityOfRock = XMLSupport::parse_float( vs_config->getVariable( "physics", "density_of_rock", "3" ) );
    static float densityOfJumpPoint =
        XMLSupport::parse_float( vs_config->getVariable( "physics", "density_of_jump_point", "100000" ) );
    //static  float massofplanet = XMLSupport::parse_float(vs_config->getVariable("physics","mass_of_planet","10000000"));
    hull = (4./3)*M_PI*radius*radius*radius*(notJumppoint ? densityOfRock : densityOfJumpPoint);
    this->Mass   = (4./3)*M_PI*radius*radius*radius*( notJumppoint ? densityOfRock : (densityOfJumpPoint/100000) );
    SetAI( new PlanetaryOrbit( this, vely, pos, x, y, orbitcent, parent ) );     //behavior
    terraintrans = NULL;

    colTrees     = NULL;
    SetAngularVelocity( rotvel );
    // The docking port is 20% bigger than the planet
    static float planetdockportsize    = XMLSupport::parse_float( vs_config->getVariable( "physics", "planet_port_size", "1.2" ) );
    static float planetdockportminsize =
        XMLSupport::parse_float( vs_config->getVariable( "physics", "planet_port_min_size", "300" ) );
    if ( (!atmospheric) && notJumppoint ) {
        float dock = radius*planetdockportsize;
        if (dock-radius < planetdockportminsize)
            dock = radius+planetdockportminsize;
        pImage->dockingports.push_back( DockingPorts( Vector( 0, 0, 0 ), dock, 0, DockingPorts::Type::CONNECTED_OUTSIDE ) );
    }
    string tempname = unitname.empty() ? ::getCargoUnitName( filename.c_str() ) : unitname;
    setFullname( tempname );

    int    tmpfac   = faction;
    if (UniverseUtil::LookupUnitStat( tempname, FactionUtil::GetFactionName( faction ), "Cargo_Import" ).length() == 0)
        tmpfac = FactionUtil::GetPlanetFaction();
    Unit  *un = UnitFactory::createUnit( tempname.c_str(), true, tmpfac );

    static bool smartplanets = XMLSupport::parse_bool( vs_config->getVariable( "physics", "planets_can_have_subunits", "false" ) );
    if ( un->name != string( "LOAD_FAILED" ) ) {
        pImage->cargo = un->GetImageInformation().cargo;
        pImage->CargoVolume   = un->GetImageInformation().CargoVolume;
        pImage->UpgradeVolume = un->GetImageInformation().UpgradeVolume;
        VSSprite *tmp = pImage->pHudImage;
        pImage->pHudImage     = un->GetImageInformation().pHudImage;
        un->GetImageInformation().pHudImage = tmp;
        maxwarpenergy = un->WarpCapData();
        if (smartplanets) {
            SubUnits.prepend( un );
            un->SetRecursiveOwner( this );
            this->SetTurretAI();
            un->SetTurretAI();              //allows adding planetary defenses, also allows launching fighters from planets, interestingly
            un->name = "Defense_grid";
        }
        static bool neutralplanets =
            XMLSupport::parse_bool( vs_config->getVariable( "physics", "planets_always_neutral", "true" ) );
        if (neutralplanets) {
            static int neutralfaction = FactionUtil::GetNeutralFaction();
            this->faction = neutralfaction;
        } else {
            this->faction = faction;
        }
    }
    if ( un->name == string( "LOAD_FAILED" ) || (!smartplanets) )
        un->Kill();
}
// method 1 use quicksort partition
int findKthLargest(vector<int>& nums, int k) {
    return randomized_select(nums,0,nums.size()-1,k);
}
Example #9
0
void print_vector(vector<float> vector){
	size_t size = vector.size();
	for(int i = 0 ; i< size ; i++){
		cout<<vector[i] << ", ";
	}
}
vector<float> assess(const plane& P){ //Assess the atom flags with respect to plane

	vector <size_t> atomsInPlane;
	
	for (int iA=0; iA<Atoms.size(); iA++){
		int PositionToPlane = P.assessPlane(Atoms[iA]);
		if (!PositionToPlane) {
			Atoms[iA].Flags|=In_Plane; 
			atomsInPlane.push_back(iA);
		}
		else if (PositionToPlane<0) Atoms[iA].Flags|=Under_Plane;
	}

	//Assess the activity around Sb.
	int Cnt = 0;
	for (int iSb=0; iSb<Sb.size(); iSb++){
		
		const float Threshold = 1.1;
		/* Add an assessment of atom with respect to the distance of the plane */
		float SquareDistance = P.assessSquareDistanceToPlane (Atoms[Sb[iSb]]);
		
		if (SquareDistance > Threshold*Threshold ||
				(!(Atoms[Sb[iSb]].Flags & (In_Plane|Under_Plane)))) continue;

		const size_t NofPerihperals(10); //Number of peripheral Sn/Sb atoms
		
		atom Peripheral [NofPerihperals];
		for (int i=0; i<NofPerihperals; i++) Peripheral[i].displace(Atoms[Sb[iSb]]);
		
		//Position all the peripheral atoms
		Peripheral[0].displace (0,0,1); Peripheral[1].displace (0,0,-1); 
		Peripheral[2].displace (-0.5, -0.5, -0.5);Peripheral[3].displace (-0.5, -0.5, +0.5);
		Peripheral[4].displace (-0.5, +0.5, -0.5);Peripheral[5].displace (-0.5, +0.5, +0.5);
		Peripheral[6].displace (+0.5, -0.5, -0.5);Peripheral[7].displace (+0.5, -0.5, +0.5);
		Peripheral[8].displace (+0.5, +0.5, -0.5);Peripheral[9].displace (+0.5, +0.5, +0.5);
				
		Atoms[Sb[iSb]].Flags |= Active;  // Assuming the centre Sb is active;
				
		for (int i=0; i<NofPerihperals; i++) {
			int indexPeriph = search (Peripheral[i]);
			if (indexPeriph==-1) continue;  //Searching out of boundary of the supercell

			if ((Atoms[indexPeriph].Flags & (In_Plane|Under_Plane))) {
				//If this both are in/under plane
				if (!(Atoms[indexPeriph].Flags & Dop)) {
					Atoms[indexPeriph].Flags |= Active; //Activate peripheral atom
				}
				else {
					Atoms[Sb [iSb]].Flags &= (-1-Active);   //De-activate the centre atom
				}
			}
			//printf ("\n");
		}
	}	
	
	/** Assess the surface activity**/
	
	int CountActive = 0;
	for (int i=0; i<atomsInPlane.size(); i++) {
		CountActive += (Atoms[atomsInPlane[i]].Flags & Active)? 1:0; //If active, then add 1
	}
	
	vector <float> results (2);
	results[0] = Sb.size()/ double (Atoms.size());
	results[1] = CountActive / double (atomsInPlane.size());
	
#ifdef OUTPUT_ATOM_COORDINATES
	
	/*Real coordinates X, Y, Z will be involved here*/
	
	string OutputFilename ("SurfaceAtoms_");
	OutputFilename.push_back ('0'+P.H);
	OutputFilename.push_back ('0'+P.K);
	OutputFilename.push_back ('0'+P.L);
	OutputFilename = OutputFilename + ".txt";
	ofstream ExportPlane (OutputFilename.c_str());
	
	atom newX;
	atom newY;
	atom newZ (P.H/a, P.K/a, P.L/c);
	float Normalizer = newZ.Abs();
	newZ.A/=Normalizer; newZ.B/=Normalizer; newZ.C/=Normalizer;	

	float SmallestDistance=10;
	for (int iA=-1; iA<=1; iA++){
		for (int iB=-1; iB<=1; iB++){
			for (int iC=-1; iC<=1; iC++){
				if (isZero(iA*P.H+iB*P.K+iC*P.L) && (iA||iB||iC)) {
					float X = iA*a;
					float Y = iB*a;
					float Z = iC*c;
					
					float Distance = sqrt(X*X + Y*Y + Z*Z);
					if (Distance <SmallestDistance) {
						newX = atom(X, Y, Z);
						SmallestDistance = Distance;
					}
				}
			}
		}
	}
	
	for (int iA=-1; iA<=0; iA++){
		for (int iB=-1; iB<=0; iB++){
			for (int iC=-1; iC<=0; iC++){
				if (isZero((iA+0.5)*P.H+(iB+0.5)*P.K+(iC+0.5)*P.L)) {
					float X = (iA+0.5)*a;
					float Y = (iB+0.5)*a;
					float Z = (iC+0.5)*c;
					
					float Distance = sqrt(X*X + Y*Y + Z*Z);
					if (Distance <SmallestDistance) {
						newX = atom(X, Y, Z);
						SmallestDistance = Distance;
					}
				}
			}
		}
	}
	
	//newX = atom (0,1,0); //Enable manually overriding the newX setting

	Normalizer = newX.Abs();
	newX.A /= Normalizer;
	newX.B /= Normalizer;
	newX.C /= Normalizer;

	newY = atom(newZ.B * newX.C - newZ.C * newX.B,
				newZ.C * newX.A - newZ.A * newX.C,
				newZ.A * newX.B - newZ.B * newX.A);
	
	CheckAtom (newX);
	CheckAtom (newY);
	CheckAtom (newZ);
	CheckAtom (BaseAtom);
	printf ("%.5f %.5f %.5f\n", newX.Abs(), newY.Abs(), newZ.Abs());
	printf ("%.5f %.5f %.5f\n", newX.A*newY.A + newX.B * newY.B + newX.C * newY.C,
								newY.A*newZ.A + newY.B * newZ.B + newY.C * newZ.C,
								newX.A*newZ.A + newX.B * newZ.B + newX.C * newZ.C);
	vector <atom> Transf (atomsInPlane.size());
	//Transform to new XYZ
	
	/*Transform Matrix 
	 * [newX.A	newX.B	newX.C ][ X ]
	 * [newY.A	newY.B	newY.C ][ Y ]
	 * [newZ.A	newZ.B	newZ.C ][ Z ]
	 */

	for (size_t iSurfAtom =0; iSurfAtom<atomsInPlane.size(); iSurfAtom++){
		atom AtomTC = Atoms[atomsInPlane[iSurfAtom]];
		AtomTC.displace (-BaseAtom.A, -BaseAtom.B, -BaseAtom.C);
		AtomTC.A *=a;
		AtomTC.B *=a;
		AtomTC.C *=c;		//TC is the relative coord to BaseAtom in true XYZ
		
		Transf [iSurfAtom] = atom (
			newX.A * AtomTC.A + newX.B * AtomTC.B + newX.C * AtomTC.C,
			newY.A * AtomTC.A + newY.B * AtomTC.B + newY.C * AtomTC.C,
			newZ.A * AtomTC.A + newZ.B * AtomTC.B + newZ.C * AtomTC.C
		);
		ExportPlane	<<((Atoms[atomsInPlane[iSurfAtom]].Flags&Dop) ? 'B' : 'N')<<"\t"
					<<(Atoms[atomsInPlane[iSurfAtom]].A-BaseAtom.A)*a<<"\t"
					<<(Atoms[atomsInPlane[iSurfAtom]].B-BaseAtom.B)*a<<"\t"
					<<(Atoms[atomsInPlane[iSurfAtom]].C-BaseAtom.C)*c<<"\t"
					//<<AtomTC.Abs()<<"\t"
					<<Transf [iSurfAtom].A<<"\t"
					<<Transf [iSurfAtom].B<<"\t"
					<<Transf [iSurfAtom].C<<"\t"
					//<<Transf [iSurfAtom].Abs()<<"\t"
					<<endl;
		//CheckAtom (Atoms[atomsInPlane[iSurfAtom]]);
	}
	
	vector <atom> OTransf (O.size());
	for (size_t iSurfO =0; iSurfO<O.size(); iSurfO++){
		atom AtomTC = O[iSurfO];
		AtomTC.displace (-BaseAtom.A, -BaseAtom.B, -BaseAtom.C);
		AtomTC.A *=a;
		AtomTC.B *=a;
		AtomTC.C *=c;		//TC is the relative coord to BaseAtom in true XYZ
		
		OTransf [iSurfO] = atom (
			newX.A * AtomTC.A + newX.B * AtomTC.B + newX.C * AtomTC.C,
			newY.A * AtomTC.A + newY.B * AtomTC.B + newY.C * AtomTC.C,
			newZ.A * AtomTC.A + newZ.B * AtomTC.B + newZ.C * AtomTC.C
		);
		if ((OTransf [iSurfO].C * OTransf [iSurfO].C) < 0.001)
			ExportPlane	<<'O'<<"\t"
					<<(AtomTC.A-BaseAtom.A)*a<<"\t"
					<<(AtomTC.B-BaseAtom.B)*a<<"\t"
					<<(AtomTC.C-BaseAtom.C)*c<<"\t"

					<<OTransf [iSurfO].A<<"\t"
					<<OTransf [iSurfO].B<<"\t"
					<<OTransf [iSurfO].C<<"\t"
					<<endl;
	}
	
#endif
	return results;
}
// ----------------------------------------------------------------------------
void ofOpenALSoundPlayer_TimelineAdditions::runWindow(vector<float> & signal){
	for(int i = 0; i < (int)signal.size(); i++)
		signal[i] *= window[i];
}
Example #12
0
	int singleNumber(vector<int>& nums) {
		int a = nums.at(0);
		for (int i = 1; i < nums.size(); ++i)
			a ^= nums.at(i);
		return a;
	}
Example #13
0
void DrawGLScene()
{
	if (fullScreen)
		glutFullScreen();
	else
		glutReshapeWindow(screen_width, screen_height);

	glViewport( 0, 0, screen_width, screen_height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0.0, screen_width, 0.0, screen_height);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glClear(GL_COLOR_BUFFER_BIT);

	// get mutex
	boost::mutex::scoped_lock lk(mtx);
	
	if(!vpoint.empty()){
		glPointSize(10);
		Vector v;
		glBegin(GL_POINTS);
		for(unsigned int i=0;i<vpoint.size();i++){
			v = screen.intersect(vpoint[i], true);
			glVertex2i((int)(screen_width*v.x), (int)(screen_height*v.y));
		}
		glEnd();

		sprintf(s,"Cursor Position: %d, %d", (int)(screen_width*v.x), (int)(screen_height*v.y));
		glPrint( 10, screen_height - 40, (void *)font, s);	// Print timeElapsed

		Vector t = vpoint[0].tipVelocity();
		float speed = t.x*t.x + t.y*t.y + t.z*t.z;
		sprintf(s,"Cursor Speed: %.2f", speed);
		glPrint( 10, screen_height - 55, (void *)font, s);	// Print timeElapsed
	}

	glColor3ub(255, 255, 255);								// Draw In White
	sprintf(s,"Test count: %d / %d", test_c, test_count);
	glPrint( 10, screen_height - 10, (void *)font, s);	// Print timeElapsed
	sprintf(s,"Target Position: %d, %d", target_x, target_y);
	glPrint( 10, screen_height - 25, (void *)font, s);	// Print timeElapsed

	if(test_c < test_count){
		if(new_target == 1){
			target_x = (int)((float)rand()/(float)RAND_MAX * screen_width);
			target_y = (int)((float)rand()/(float)RAND_MAX * screen_height);
			target_width[test_c] = 10+(int)((float)rand()/(float)RAND_MAX*50);
			start_time = glutGet(GLUT_ELAPSED_TIME);
			start_position = vpoint;
			new_target = 0;
		}

		glutDrawCirclei( target_x, target_y, target_width[test_c]);
	}else{
		CleanupExit();
	}

	glFlush ();					// Flush The GL Rendering Pipeline
	glutSwapBuffers();	// swap buffers to display, since we're double buffered.
}
Example #14
0
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
    CAutoBN_CTX pctx;
    CScript::const_iterator pc = script.begin();
    CScript::const_iterator pend = script.end();
    CScript::const_iterator pbegincodehash = script.begin();
    opcodetype opcode;
    valtype vchPushValue;
    vector<bool> vfExec;
    vector<valtype> altstack;
    if (script.size() > 10000)
        return false;
    int nOpCount = 0;


    try
    {
        while (pc < pend)
        {
            bool fExec = !count(vfExec.begin(), vfExec.end(), false);

            //
            // Read instruction
            //
            if (!script.GetOp(pc, opcode, vchPushValue))
                return false;
            if (vchPushValue.size() > 520)
                return false;
            if (opcode > OP_16 && ++nOpCount > 201)
                return false;

            if (opcode == OP_CAT ||
                opcode == OP_SUBSTR ||
                opcode == OP_LEFT ||
                opcode == OP_RIGHT ||
                opcode == OP_INVERT ||
                opcode == OP_AND ||
                opcode == OP_OR ||
                opcode == OP_XOR ||
                opcode == OP_2MUL ||
                opcode == OP_2DIV ||
                opcode == OP_MUL ||
                opcode == OP_DIV ||
                opcode == OP_MOD ||
                opcode == OP_LSHIFT ||
                opcode == OP_RSHIFT)
                return false;

            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
                stack.push_back(vchPushValue);
            else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
            switch (opcode)
            {
                //
                // Push value
                //
                case OP_1NEGATE:
                case OP_1:
                case OP_2:
                case OP_3:
                case OP_4:
                case OP_5:
                case OP_6:
                case OP_7:
                case OP_8:
                case OP_9:
                case OP_10:
                case OP_11:
                case OP_12:
                case OP_13:
                case OP_14:
                case OP_15:
                case OP_16:
                {
                    // ( -- value)
                    CBigNum bn((int)opcode - (int)(OP_1 - 1));
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Control
                //
                case OP_NOP:
                case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
                case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
                break;

                case OP_IF:
                case OP_NOTIF:
                {
                    // <expression> if [statements] [else [statements]] endif
                    bool fValue = false;
                    if (fExec)
                    {
                        if (stack.size() < 1)
                            return false;
                        valtype& vch = stacktop(-1);
                        fValue = CastToBool(vch);
                        if (opcode == OP_NOTIF)
                            fValue = !fValue;
                        popstack(stack);
                    }
                    vfExec.push_back(fValue);
                }
                break;

                case OP_ELSE:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.back() = !vfExec.back();
                }
                break;

                case OP_ENDIF:
                {
                    if (vfExec.empty())
                        return false;
                    vfExec.pop_back();
                }
                break;

                case OP_VERIFY:
                {
                    // (true -- ) or
                    // (false -- false) and return
                    if (stack.size() < 1)
                        return false;
                    bool fValue = CastToBool(stacktop(-1));
                    if (fValue)
                        popstack(stack);
                    else
                        return false;
                }
                break;

                case OP_RETURN:
                {
                    return false;
                }
                break;


                //
                // Stack ops
                //
                case OP_TOALTSTACK:
                {
                    if (stack.size() < 1)
                        return false;
                    altstack.push_back(stacktop(-1));
                    popstack(stack);
                }
                break;

                case OP_FROMALTSTACK:
                {
                    if (altstack.size() < 1)
                        return false;
                    stack.push_back(altstacktop(-1));
                    popstack(altstack);
                }
                break;

                case OP_2DROP:
                {
                    // (x1 x2 -- )
                    if (stack.size() < 2)
                        return false;
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_2DUP:
                {
                    // (x1 x2 -- x1 x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch1 = stacktop(-2);
                    valtype vch2 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_3DUP:
                {
                    // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
                    if (stack.size() < 3)
                        return false;
                    valtype vch1 = stacktop(-3);
                    valtype vch2 = stacktop(-2);
                    valtype vch3 = stacktop(-1);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                    stack.push_back(vch3);
                }
                break;

                case OP_2OVER:
                {
                    // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    valtype vch1 = stacktop(-4);
                    valtype vch2 = stacktop(-3);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2ROT:
                {
                    // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
                    if (stack.size() < 6)
                        return false;
                    valtype vch1 = stacktop(-6);
                    valtype vch2 = stacktop(-5);
                    stack.erase(stack.end()-6, stack.end()-4);
                    stack.push_back(vch1);
                    stack.push_back(vch2);
                }
                break;

                case OP_2SWAP:
                {
                    // (x1 x2 x3 x4 -- x3 x4 x1 x2)
                    if (stack.size() < 4)
                        return false;
                    swap(stacktop(-4), stacktop(-2));
                    swap(stacktop(-3), stacktop(-1));
                }
                break;

                case OP_IFDUP:
                {
                    // (x - 0 | x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    if (CastToBool(vch))
                        stack.push_back(vch);
                }
                break;

                case OP_DEPTH:
                {
                    // -- stacksize
                    CBigNum bn(stack.size());
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_DROP:
                {
                    // (x -- )
                    if (stack.size() < 1)
                        return false;
                    popstack(stack);
                }
                break;

                case OP_DUP:
                {
                    // (x -- x x)
                    if (stack.size() < 1)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.push_back(vch);
                }
                break;

                case OP_NIP:
                {
                    // (x1 x2 -- x2)
                    if (stack.size() < 2)
                        return false;
                    stack.erase(stack.end() - 2);
                }
                break;

                case OP_OVER:
                {
                    // (x1 x2 -- x1 x2 x1)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-2);
                    stack.push_back(vch);
                }
                break;

                case OP_PICK:
                case OP_ROLL:
                {
                    // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
                    // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
                    if (stack.size() < 2)
                        return false;
                    int n = CastToBigNum(stacktop(-1)).getint();
                    popstack(stack);
                    if (n < 0 || n >= stack.size())
                        return false;
                    valtype vch = stacktop(-n-1);
                    if (opcode == OP_ROLL)
                        stack.erase(stack.end()-n-1);
                    stack.push_back(vch);
                }
                break;

                case OP_ROT:
                {
                    // (x1 x2 x3 -- x2 x3 x1)
                    //  x2 x1 x3  after first swap
                    //  x2 x3 x1  after second swap
                    if (stack.size() < 3)
                        return false;
                    swap(stacktop(-3), stacktop(-2));
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_SWAP:
                {
                    // (x1 x2 -- x2 x1)
                    if (stack.size() < 2)
                        return false;
                    swap(stacktop(-2), stacktop(-1));
                }
                break;

                case OP_TUCK:
                {
                    // (x1 x2 -- x2 x1 x2)
                    if (stack.size() < 2)
                        return false;
                    valtype vch = stacktop(-1);
                    stack.insert(stack.end()-2, vch);
                }
                break;


                //
                // Splice ops
                //
                case OP_CAT:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    vch1.insert(vch1.end(), vch2.begin(), vch2.end());
                    popstack(stack);
                    if (stacktop(-1).size() > 520)
                        return false;
                }
                break;

                case OP_SUBSTR:
                {
                    // (in begin size -- out)
                    if (stack.size() < 3)
                        return false;
                    valtype& vch = stacktop(-3);
                    int nBegin = CastToBigNum(stacktop(-2)).getint();
                    int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
                    if (nBegin < 0 || nEnd < nBegin)
                        return false;
                    if (nBegin > vch.size())
                        nBegin = vch.size();
                    if (nEnd > vch.size())
                        nEnd = vch.size();
                    vch.erase(vch.begin() + nEnd, vch.end());
                    vch.erase(vch.begin(), vch.begin() + nBegin);
                    popstack(stack);
                    popstack(stack);
                }
                break;

                case OP_LEFT:
                case OP_RIGHT:
                {
                    // (in size -- out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch = stacktop(-2);
                    int nSize = CastToBigNum(stacktop(-1)).getint();
                    if (nSize < 0)
                        return false;
                    if (nSize > vch.size())
                        nSize = vch.size();
                    if (opcode == OP_LEFT)
                        vch.erase(vch.begin() + nSize, vch.end());
                    else
                        vch.erase(vch.begin(), vch.end() - nSize);
                    popstack(stack);
                }
                break;

                case OP_SIZE:
                {
                    // (in -- in size)
                    if (stack.size() < 1)
                        return false;
                    CBigNum bn(stacktop(-1).size());
                    stack.push_back(bn.getvch());
                }
                break;


                //
                // Bitwise logic
                //
                case OP_INVERT:
                {
                    // (in - out)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    for (int i = 0; i < vch.size(); i++)
                        vch[i] = ~vch[i];
                }
                break;

                case OP_AND:
                case OP_OR:
                case OP_XOR:
                {
                    // (x1 x2 - out)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    MakeSameSize(vch1, vch2);
                    if (opcode == OP_AND)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] &= vch2[i];
                    }
                    else if (opcode == OP_OR)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] |= vch2[i];
                    }
                    else if (opcode == OP_XOR)
                    {
                        for (int i = 0; i < vch1.size(); i++)
                            vch1[i] ^= vch2[i];
                    }
                    popstack(stack);
                }
                break;

                case OP_EQUAL:
                case OP_EQUALVERIFY:
                //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
                {
                    // (x1 x2 - bool)
                    if (stack.size() < 2)
                        return false;
                    valtype& vch1 = stacktop(-2);
                    valtype& vch2 = stacktop(-1);
                    bool fEqual = (vch1 == vch2);
                    // OP_NOTEQUAL is disabled because it would be too easy to say
                    // something like n != 1 and have some wiseguy pass in 1 with extra
                    // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
                    //if (opcode == OP_NOTEQUAL)
                    //    fEqual = !fEqual;
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fEqual ? vchTrue : vchFalse);
                    if (opcode == OP_EQUALVERIFY)
                    {
                        if (fEqual)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;


                //
                // Numeric
                //
                case OP_1ADD:
                case OP_1SUB:
                case OP_2MUL:
                case OP_2DIV:
                case OP_NEGATE:
                case OP_ABS:
                case OP_NOT:
                case OP_0NOTEQUAL:
                {
                    // (in -- out)
                    if (stack.size() < 1)
                        return false;
                    CBigNum bn = CastToBigNum(stacktop(-1));
                    switch (opcode)
                    {
                    case OP_1ADD:       bn += bnOne; break;
                    case OP_1SUB:       bn -= bnOne; break;
                    case OP_2MUL:       bn <<= 1; break;
                    case OP_2DIV:       bn >>= 1; break;
                    case OP_NEGATE:     bn = -bn; break;
                    case OP_ABS:        if (bn < bnZero) bn = -bn; break;
                    case OP_NOT:        bn = (bn == bnZero); break;
                    case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
                    }
                    popstack(stack);
                    stack.push_back(bn.getvch());
                }
                break;

                case OP_ADD:
                case OP_SUB:
                case OP_MUL:
                case OP_DIV:
                case OP_MOD:
                case OP_LSHIFT:
                case OP_RSHIFT:
                case OP_BOOLAND:
                case OP_BOOLOR:
                case OP_NUMEQUAL:
                case OP_NUMEQUALVERIFY:
                case OP_NUMNOTEQUAL:
                case OP_LESSTHAN:
                case OP_GREATERTHAN:
                case OP_LESSTHANOREQUAL:
                case OP_GREATERTHANOREQUAL:
                case OP_MIN:
                case OP_MAX:
                {
                    // (x1 x2 -- out)
                    if (stack.size() < 2)
                        return false;
                    CBigNum bn1 = CastToBigNum(stacktop(-2));
                    CBigNum bn2 = CastToBigNum(stacktop(-1));
                    CBigNum bn;
                    switch (opcode)
                    {
                    case OP_ADD:
                        bn = bn1 + bn2;
                        break;

                    case OP_SUB:
                        bn = bn1 - bn2;
                        break;

                    case OP_MUL:
                        if (!BN_mul(&bn, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_DIV:
                        if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_MOD:
                        if (!BN_mod(&bn, &bn1, &bn2, pctx))
                            return false;
                        break;

                    case OP_LSHIFT:
                        if (bn2 < bnZero || bn2 > CBigNum(2048))
                            return false;
                        bn = bn1 << bn2.getulong();
                        break;

                    case OP_RSHIFT:
                        if (bn2 < bnZero || bn2 > CBigNum(2048))
                            return false;
                        bn = bn1 >> bn2.getulong();
                        break;

                    case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
                    case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
                    case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
                    case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
                    case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
                    case OP_LESSTHAN:            bn = (bn1 < bn2); break;
                    case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
                    case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
                    case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
                    case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
                    case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
                    }
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(bn.getvch());

                    if (opcode == OP_NUMEQUALVERIFY)
                    {
                        if (CastToBool(stacktop(-1)))
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_WITHIN:
                {
                    // (x min max -- out)
                    if (stack.size() < 3)
                        return false;
                    CBigNum bn1 = CastToBigNum(stacktop(-3));
                    CBigNum bn2 = CastToBigNum(stacktop(-2));
                    CBigNum bn3 = CastToBigNum(stacktop(-1));
                    bool fValue = (bn2 <= bn1 && bn1 < bn3);
                    popstack(stack);
                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fValue ? vchTrue : vchFalse);
                }
                break;


                //
                // Crypto
                //
                case OP_RIPEMD160:
                case OP_SHA1:
                case OP_SHA256:
                case OP_HASH160:
                case OP_HASH256:
                {
                    // (in -- hash)
                    if (stack.size() < 1)
                        return false;
                    valtype& vch = stacktop(-1);
                    valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
                    if (opcode == OP_RIPEMD160)
                        RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_SHA1)
                        SHA1(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_SHA256)
                        SHA256(&vch[0], vch.size(), &vchHash[0]);
                    else if (opcode == OP_HASH160)
                    {
                        uint160 hash160 = Hash160(vch);
                        memcpy(&vchHash[0], &hash160, sizeof(hash160));
                    }
                    else if (opcode == OP_HASH256)
                    {
                        uint256 hash = Hash(vch.begin(), vch.end());
                        memcpy(&vchHash[0], &hash, sizeof(hash));
                    }
                    popstack(stack);
                    stack.push_back(vchHash);
                }
                break;

                case OP_CODESEPARATOR:
                {
                    // Hash starts after the code separator
                    pbegincodehash = pc;
                }
                break;

                case OP_CHECKSIG:
                case OP_CHECKSIGVERIFY:
                {
                    // (sig pubkey -- bool)
                    if (stack.size() < 2)
                        return false;

                    valtype& vchSig    = stacktop(-2);
                    valtype& vchPubKey = stacktop(-1);

                    ////// debug print
                    //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
                    //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signature, since there's no way for a signature to sign itself
                    scriptCode.FindAndDelete(CScript(vchSig));

                    bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);

                    popstack(stack);
                    popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
                    if (opcode == OP_CHECKSIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                case OP_CHECKMULTISIG:
                case OP_CHECKMULTISIGVERIFY:
                {
                    // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)

                    int i = 1;
                    if (stack.size() < i)
                        return false;

                    int nKeysCount = CastToBigNum(stacktop(-i)).getint();
                    if (nKeysCount < 0 || nKeysCount > 20)
                        return false;
                    nOpCount += nKeysCount;
                    if (nOpCount > 201)
                        return false;
                    int ikey = ++i;
                    i += nKeysCount;
                    if (stack.size() < i)
                        return false;

                    int nSigsCount = CastToBigNum(stacktop(-i)).getint();
                    if (nSigsCount < 0 || nSigsCount > nKeysCount)
                        return false;
                    int isig = ++i;
                    i += nSigsCount;
                    if (stack.size() < i)
                        return false;

                    // Subset of script starting at the most recent codeseparator
                    CScript scriptCode(pbegincodehash, pend);

                    // Drop the signatures, since there's no way for a signature to sign itself
                    for (int k = 0; k < nSigsCount; k++)
                    {
                        valtype& vchSig = stacktop(-isig-k);
                        scriptCode.FindAndDelete(CScript(vchSig));
                    }

                    bool fSuccess = true;
                    while (fSuccess && nSigsCount > 0)
                    {
                        valtype& vchSig    = stacktop(-isig);
                        valtype& vchPubKey = stacktop(-ikey);

                        // Check signature
                        if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
                        {
                            isig++;
                            nSigsCount--;
                        }
                        ikey++;
                        nKeysCount--;

                        // If there are more signatures left than keys left,
                        // then too many signatures have failed
                        if (nSigsCount > nKeysCount)
                            fSuccess = false;
                    }

                    while (i-- > 0)
                        popstack(stack);
                    stack.push_back(fSuccess ? vchTrue : vchFalse);

                    if (opcode == OP_CHECKMULTISIGVERIFY)
                    {
                        if (fSuccess)
                            popstack(stack);
                        else
                            return false;
                    }
                }
                break;

                default:
                    return false;
            }

            // Size limits
            if (stack.size() + altstack.size() > 1000)
                return false;
        }
    }
    catch (...)
    {
        return false;
    }


    if (!vfExec.empty())
        return false;

    return true;
}
Example #15
0
static command_result autodump_main(color_ostream &out, vector <string> & parameters)
{
    // Command line options
    bool destroy = false;
    bool here = false;
    bool need_visible = false;
    bool need_hidden = false;
    bool need_forbidden = false;
    for (size_t i = 0; i < parameters.size(); i++)
    {
        string & p = parameters[i];
        if(p == "destroy")
            destroy = true;
        else if (p == "destroy-here")
            destroy = here = true;
        else if (p == "visible")
            need_visible = true;
        else if (p == "hidden")
            need_hidden = true;
        else if (p == "forbidden")
            need_forbidden = true;
        else
            return CR_WRONG_USAGE;
    }

    if (need_visible && need_hidden)
    {
        out.printerr("An item can't be both hidden and visible.\n");
        return CR_WRONG_USAGE;
    }

    //DFHack::VersionInfo *mem = Core::getInstance().vinfo;
    if (!Maps::IsValid())
    {
        out.printerr("Map is not available!\n");
        return CR_FAILURE;
    }
    size_t numItems = world->items.all.size();

    MapCache MC;
    int i = 0;
    int dumped_total = 0;

    int cx, cy, cz;
    DFCoord pos_cursor;
    if(!destroy || here)
    {
        if (!Gui::getCursorCoords(cx,cy,cz))
        {
            out.printerr("Cursor position not found. Please enabled the cursor.\n");
            return CR_FAILURE;
        }
        pos_cursor = DFCoord(cx,cy,cz);
    }
    if (!destroy)
    {
        {
            Block * b = MC.BlockAt(pos_cursor / 16);
            if(!b)
            {
                out.printerr("Cursor is in an invalid/uninitialized area. Place it over a floor.\n");
                return CR_FAILURE;
            }
            df::tiletype ttype = MC.tiletypeAt(pos_cursor);
            if(!DFHack::isFloorTerrain(ttype))
            {
                out.printerr("Cursor should be placed over a floor.\n");
                return CR_FAILURE;
            }
        }
    }
    coordmap counts;
    // proceed with the dumpification operation
    for(size_t i=0; i< numItems; i++)
    {
        df::item * itm = world->items.all[i];
        DFCoord pos_item(itm->pos.x, itm->pos.y, itm->pos.z);

        // keep track how many items are at places. all items.
        coordmap::iterator it = counts.find(pos_item);
        if(it == counts.end())
        {
            pair< coordmap::iterator, bool > inserted = counts.insert(make_pair(pos_item,1));
            it = inserted.first;
        }
        else
        {
            it->second ++;
        }
        // iterator is valid here, we use it later to decrement the pile counter if the item is moved

        // only dump the stuff marked for dumping and laying on the ground
        if (   !itm->flags.bits.dump
            || !itm->flags.bits.on_ground
            ||  itm->flags.bits.construction
            ||  itm->flags.bits.in_building
            ||  itm->flags.bits.in_chest
            ||  itm->flags.bits.in_inventory
            ||  itm->flags.bits.artifact1
        )
            continue;

        if (need_visible && itm->flags.bits.hidden)
            continue;
        if (need_hidden && !itm->flags.bits.hidden)
            continue;
        if (need_forbidden && !itm->flags.bits.forbid)
            continue;
        if (!need_forbidden && itm->flags.bits.forbid)
            continue;

        if(!destroy) // move to cursor
        {
            // Change flags to indicate the dump was completed, as if by super-dwarfs
            itm->flags.bits.dump = false;
            itm->flags.bits.forbid = true;

            // Don't move items if they're already at the cursor
            if (pos_cursor == pos_item)
                continue;

            // Do we need to fix block-local item ID vector?
            if(pos_item/16 != pos_cursor/16)
            {
                // yes...
                cerr << "Moving from block to block!" << endl;
                df::map_block * bl_src = Maps::getBlockAbs(itm->pos.x, itm->pos.y, itm->pos.z);
                df::map_block * bl_tgt = Maps::getBlockAbs(cx, cy, cz);
                if(bl_src)
                {
                    remove(bl_src->items.begin(), bl_src->items.end(),itm->id);
                }
                else
                {
                    cerr << "No source block" << endl;
                }
                if(bl_tgt)
                {
                    bl_tgt->items.push_back(itm->id);
                }
                else
                {
                    cerr << "No target block" << endl;
                }
            }

            // Move the item
            itm->pos.x = pos_cursor.x;
            itm->pos.y = pos_cursor.y;
            itm->pos.z = pos_cursor.z;
        }
        else // destroy
        {
            if (here && pos_item != pos_cursor)
                continue;

            itm->flags.bits.garbage_colect = true;

            // Cosmetic changes: make them disappear from view instantly
            itm->flags.bits.forbid = true;
            itm->flags.bits.hidden = true;
        }
        // keeping track of item pile sizes ;)
        it->second --;
        dumped_total++;
    }
    if(!destroy) // TODO: do we have to do any of this when destroying items?
    {
        // for each item pile, see if it reached zero. if so, unset item flag on the tile it's on
        coordmap::iterator it = counts.begin();
        coordmap::iterator end = counts.end();
        while(it != end)
        {
            if(it->second == 0)
            {
                df::tile_occupancy occ = MC.occupancyAt(it->first);
                occ.bits.item = false;
                MC.setOccupancyAt(it->first, occ);
            }
            it++;
        }
        // Set "item here" flag on target tile, if we moved any items to the target tile.
        if (dumped_total > 0)
        {
            // assume there is a possibility the cursor points at some weird location with missing block data
            Block * b = MC.BlockAt(pos_cursor / 16);
            if(b)
            {
                df::tile_occupancy occ = MC.occupancyAt(pos_cursor);
                occ.bits.item = 1;
                MC.setOccupancyAt(pos_cursor,occ);
            }
        }
        // write map changes back to DF.
        MC.WriteAll();
        // Is this necessary?  Is "forbid" a dirtyable attribute like "dig" is?
        Maps::WriteDirtyBit(cx/16, cy/16, cz, true);
    }
    out.print("Done. %d items %s.\n", dumped_total, destroy ? "marked for destruction" : "quickdumped");
    return CR_OK;
}
component get_distance(int trelly[][100], vector<string> templ,vector<string> input){
	int    ally;
	int    trelly1;
	int    trelly2;
	int    trelly3;
	component TD;	

//判断首单词是否相同
	if(templ.at(0) != input.at(0)){
		templ.insert(templ.begin(),"0");
		input.insert(input.begin(),"0");
	}

	int row = templ.size();
	int coloum= input.size();
	
#if   fixed_boundary
	{
	//初始化trelly第一行和第一列的数据
		for(int j=0;j<input.size();j++)
		   trelly[0][j] = j;
		
		for(int i=0;i<templ.size();i++){
		trelly[i][0] = i;
		if(trelly[i][0]>3)
			trelly[i][0] = 10000;
		}
		
	////从这里开始计算trelly的每一格的数值

		for(int j=1;j<input.size();j++){
		int    min = 100000;
		for(int i = 1;i<templ.size();i++){
			if(input.at(j)==templ.at(i))
				ally = 0;
			else 
				ally = 1;
		
	trelly1 = trelly[i-1][j-1] + ally;
			
	trelly2 = trelly[i-1][j] + 1;
			
	trelly3 = trelly[i][j-1] + 1;

	trelly[i][j] = get_least(trelly1,trelly2,trelly3);  
	if(trelly[i][j] > 3)
		trelly[i][j] = 10000;
			}
		}
	}
		
#endif

#if  beam_boundary
	{
	//初始化trelly第一行和第一列的数据
		for(int j=0;j<input.size();j++)
		   trelly[0][j] = j;
		
		for(int i=0;i<templ.size();i++){
		trelly[i][0] = i;
		if(trelly[i][0]>3)
			trelly[i][0] = 10000;
		}
		
	////从这里开始计算trelly的每一格的数值

		for(int j=1;j<input.size();j++){
		int    min = 100000;
		for(int i = 1;i<templ.size();i++){
			if(input.at(j)==templ.at(i))
				ally = 0;
			else 
				ally = 1;
		
	trelly1 = trelly[i-1][j-1] + ally;
			
	trelly2 = trelly[i-1][j] + 1;
			
	trelly3 = trelly[i][j-1] + 1;

	trelly[i][j] = get_least(trelly1,trelly2,trelly3);  
	if(trelly[i][j]<min)
		min = trelly[i][j];
		}
		if(trelly[0][j]<min)
			min = trelly[0][j];
		for(int i = 0;i<input.size();i++)
		   if(trelly[i][j]>(min+3))
			   trelly[i][j] = 10000;
			}
	}
#endif

	TD.leastdistance = trelly[templ.size()-1][input.size()-1];
	
		//构造数组每个元素的标识符
		int tag[100][100]={0};

	//对最短距离路径上的元素进行颜色tag标示
	int m = templ.size()-1;
	int n = input.size()-1;
	int deletion = 0;
	int insertion = 0;
	int substitution = 0;
	tag[m][n] = 1;
	tag[0][0] = 1;
	while(m>0||n>0){
    
	if(n>0&&trelly[m][n-1] ==trelly[m][n]-1){
	 n = n-1;
	 tag[m][n] = 1;
	 insertion++;
	}
	else if(m>0&&trelly[m-1][n] ==trelly[m][n]-1){
		m = m-1;
		tag[m][n] = 1;
		deletion++;
	}
	else{
		m = m-1;n = n-1;
		tag[m][n] = 1;
		if(trelly[m][n] != trelly[m+1][n+1])
			substitution++;
	}
	}
	TD.sunstitution = substitution;
	TD.deletion = deletion;
	TD.insertion = insertion;

		
	return TD;

	}
Example #17
0
// Returns a polygon "stripe" across the width of the character region.  The lines are voted and the polygon starts at 0 and extends to image width
vector<Point> CharacterAnalysis::getBestVotedLines(Mat img, vector<vector<Point> > contours, vector<bool> goodIndices)
{

    //if (this->debug)
    //  cout << "CharacterAnalysis::getBestVotedLines" << endl;

    vector<Point> bestStripe;

    vector<Rect> charRegions;

    for (int i = 0; i < contours.size(); i++)
    {
        if (goodIndices[i])
            charRegions.push_back(boundingRect(contours[i]));
    }


    // Find the best fit line segment that is parallel with the most char segments
    if (charRegions.size() <= 1)
    {
        // Maybe do something about this later, for now let's just ignore
    }
    else
    {
        vector<LineSegment> topLines;
        vector<LineSegment> bottomLines;
        // Iterate through each possible char and find all possible lines for the top and bottom of each char segment
        for (int i = 0; i < charRegions.size() - 1; i++)
        {
            for (int k = i+1; k < charRegions.size(); k++)
            {
                //Mat tempImg;
                //result.copyTo(tempImg);


                Rect* leftRect;
                Rect* rightRect;
                if (charRegions[i].x < charRegions[k].x)
                {
                    leftRect = &charRegions[i];
                    rightRect = &charRegions[k];
                }
                else
                {
                    leftRect = &charRegions[k];
                    rightRect = &charRegions[i];
                }

                //rectangle(tempImg, *leftRect, Scalar(0, 255, 0), 2);
                //rectangle(tempImg, *rightRect, Scalar(255, 255, 255), 2);

                int x1, y1, x2, y2;

                if (leftRect->y > rightRect->y)	// Rising line, use the top left corner of the rect
                {
                    x1 = leftRect->x;
                    x2 = rightRect->x;
                }
                else					// falling line, use the top right corner of the rect
                {
                    x1 = leftRect->x + leftRect->width;
                    x2 = rightRect->x + rightRect->width;
                }
                y1 = leftRect->y;
                y2 = rightRect->y;

                //cv::line(tempImg, Point(x1, y1), Point(x2, y2), Scalar(0, 0, 255));
                topLines.push_back(LineSegment(x1, y1, x2, y2));


                if (leftRect->y > rightRect->y)	// Rising line, use the bottom right corner of the rect
                {
                    x1 = leftRect->x + leftRect->width;
                    x2 = rightRect->x + rightRect->width;
                }
                else					// falling line, use the bottom left corner of the rect
                {
                    x1 = leftRect->x;
                    x2 = rightRect->x;
                }
                y1 = leftRect->y + leftRect->height;
                y2 = rightRect->y + leftRect->height;

                //cv::line(tempImg, Point(x1, y1), Point(x2, y2), Scalar(0, 0, 255));
                bottomLines.push_back(LineSegment(x1, y1, x2, y2));

                //drawAndWait(&tempImg);
            }
        }

        int bestScoreIndex = 0;
        int bestScore = -1;
        int bestScoreDistance = -1; // Line segment distance is used as a tie breaker

        // Now, among all possible lines, find the one that is the best fit
        for (int i = 0; i < topLines.size(); i++)
        {
            float SCORING_MIN_THRESHOLD = 0.97;
            float SCORING_MAX_THRESHOLD = 1.03;


            int curScore = 0;
            for (int charidx = 0; charidx < charRegions.size(); charidx++)
            {

                float topYPos = topLines[i].getPointAt(charRegions[charidx].x);
                float botYPos = bottomLines[i].getPointAt(charRegions[charidx].x);

                float minTop = charRegions[charidx].y * SCORING_MIN_THRESHOLD;
                float maxTop = charRegions[charidx].y * SCORING_MAX_THRESHOLD;
                float minBot = (charRegions[charidx].y + charRegions[charidx].height) * SCORING_MIN_THRESHOLD;
                float maxBot = (charRegions[charidx].y + charRegions[charidx].height) * SCORING_MAX_THRESHOLD;
                if ( (topYPos >= minTop && topYPos <= maxTop) &&
                        (botYPos >= minBot && botYPos <= maxBot))
                {
                    curScore++;
                }

                //cout << "Slope: " << topslope << " yPos: " << topYPos << endl;
                //drawAndWait(&tempImg);

            }


            // Tie goes to the one with longer line segments
            if ((curScore > bestScore) ||
                    (curScore == bestScore && topLines[i].length > bestScoreDistance))
            {
                bestScore = curScore;
                bestScoreIndex = i;
                // Just use x distance for now
                bestScoreDistance = topLines[i].length;
            }
        }


        if (this->config->debugCharAnalysis)
        {
            cout << "The winning score is: " << bestScore << endl;
            // Draw the winning line segment
            //Mat tempImg;
            //result.copyTo(tempImg);
            //cv::line(tempImg, topLines[bestScoreIndex].p1, topLines[bestScoreIndex].p2, Scalar(0, 0, 255), 2);
            //cv::line(tempImg, bottomLines[bestScoreIndex].p1, bottomLines[bestScoreIndex].p2, Scalar(0, 0, 255), 2);

            //displayImage(config, "Lines", tempImg);
        }

        //winningLines.push_back(topLines[bestScoreIndex]);
        //winningLines.push_back(bottomLines[bestScoreIndex]);

        Point topLeft 		= Point(0, topLines[bestScoreIndex].getPointAt(0) );
        Point topRight 		= Point(img.cols, topLines[bestScoreIndex].getPointAt(img.cols));
        Point bottomRight 	= Point(img.cols, bottomLines[bestScoreIndex].getPointAt(img.cols));
        Point bottomLeft 	= Point(0, bottomLines[bestScoreIndex].getPointAt(0));


        bestStripe.push_back(topLeft);
        bestStripe.push_back(topRight);
        bestStripe.push_back(bottomRight);
        bestStripe.push_back(bottomLeft);


    }


    return bestStripe;
}
Example #18
0
void motionToColor(Mat flow, Mat &color)
{
    if (color.empty())
        color.create(flow.rows, flow.cols, CV_8UC3);

    static vector<Scalar> colorwheel; //Scalar r,g,b
    if (colorwheel.empty())
        makecolorwheel(colorwheel);

    // determine motion range:
    float maxrad = -1;

    // Find max flow to normalize fx and fy
    for (int i= 0; i < flow.rows; ++i)
    {
        for (int j = 0; j < flow.cols; ++j)
        {
            Vec2f flow_at_point = flow.at<Vec2f>(i, j);
            float fx = flow_at_point[0];
            float fy = flow_at_point[1];
            if ((fabs(fx) >  UNKNOWN_FLOW_THRESH) || (fabs(fy) >  UNKNOWN_FLOW_THRESH))
                continue;
            float rad = sqrt(fx * fx + fy * fy);
            maxrad = maxrad > rad ? maxrad : rad;
        }
    }

    for (int i= 0; i < flow.rows; ++i)
    {
        for (int j = 0; j < flow.cols; ++j)
        {
            uchar *data = color.data + color.step[0] * i + color.step[1] * j;
            Vec2f flow_at_point = flow.at<Vec2f>(i, j);

            float fx = flow_at_point[0] / maxrad;
            float fy = flow_at_point[1] / maxrad;
            if ((fabs(fx) >  UNKNOWN_FLOW_THRESH) || (fabs(fy) >  UNKNOWN_FLOW_THRESH))
            {
                data[0] = data[1] = data[2] = 0;
                continue;
            }
            float rad = sqrt(fx * fx + fy * fy);

            float angle = atan2(-fy, -fx) / CV_PI;
            float fk = (angle + 1.0) / 2.0 * (colorwheel.size()-1);
            int k0 = (int)fk;
            int k1 = (k0 + 1) % colorwheel.size();
            float f = fk - k0;
            //f = 0; // uncomment to see original color wheel

            for (int b = 0; b < 3; b++)
            {
                float col0 = colorwheel[k0][b] / 255.0;
                float col1 = colorwheel[k1][b] / 255.0;
                float col = (1 - f) * col0 + f * col1;
                if (rad <= 1)
                    col = 1 - rad * (1 - col); // increase saturation with radius
                else
                    col *= .75; // out of range
                data[2 - b] = (int)(255.0 * col);
            }
        }
    }
}
Example #19
0
vector<bool> CharacterAnalysis::filterBetweenLines(Mat img, vector<vector<Point> > contours, vector<Vec4i> hierarchy, vector<Point> outerPolygon, vector<bool> goodIndices)
{
    static float MIN_AREA_PERCENT_WITHIN_LINES = 0.88;

    vector<bool> includedIndices(contours.size());
    for (int j = 0; j < contours.size(); j++)
        includedIndices[j] = false;


    if (outerPolygon.size() == 0)
        return includedIndices;

    vector<Point> validPoints;

    // Figure out the line height
    LineSegment topLine(outerPolygon[0].x, outerPolygon[0].y, outerPolygon[1].x, outerPolygon[1].y);
    LineSegment bottomLine(outerPolygon[3].x, outerPolygon[3].y, outerPolygon[2].x, outerPolygon[2].y);

    float x = ((float) img.cols) / 2;
    Point midpoint = Point(x, bottomLine.getPointAt(x));
    Point acrossFromMidpoint = topLine.closestPointOnSegmentTo(midpoint);
    float lineHeight = distanceBetweenPoints(midpoint, acrossFromMidpoint);

    // Create a white mask for the area inside the polygon
    Mat outerMask = Mat::zeros(img.size(), CV_8U);
    Mat innerArea = Mat::zeros(img.size(), CV_8U);
    fillConvexPoly(outerMask, outerPolygon.data(), outerPolygon.size(), Scalar(255,255,255));


    for (int i = 0; i < contours.size(); i++)
    {
        if (goodIndices[i] == false)
            continue;

        // get rid of the outline by drawing a 1 pixel width black line
        drawContours(innerArea, contours,
                     i, // draw this contour
                     cv::Scalar(255,255,255), // in
                     CV_FILLED,
                     8,
                     hierarchy,
                     0
                    );


        bitwise_and(innerArea, outerMask, innerArea);


        vector<vector<Point> > tempContours;
        findContours(innerArea, tempContours,
                     CV_RETR_EXTERNAL, // retrieve the external contours
                     CV_CHAIN_APPROX_SIMPLE ); // all pixels of each contours );

        double totalArea = contourArea(contours[i]);
        double areaBetweenLines = 0;

        for (int tempContourIdx = 0; tempContourIdx < tempContours.size(); tempContourIdx++)
        {
            areaBetweenLines += contourArea(tempContours[tempContourIdx]);

        }


        if (areaBetweenLines / totalArea >= MIN_AREA_PERCENT_WITHIN_LINES)
        {
            includedIndices[i] = true;
        }

        innerArea.setTo(Scalar(0,0,0));
    }

    return includedIndices;
}
Example #20
0
bool ReadImg_names(vector<string>& ins)
{
    /*ins.push_back("n1.jpg");
    ins.push_back("n2.jpg");
    ins.push_back("n3.jpg");
    ins.push_back("n4.jpg");
    ins.push_back("n5.jpg");*/

    // 上下
    /*ins.push_back("m1.jpg");
    ins.push_back("m2.jpg");
    */
    // 下上
    //ins.push_back("m2.jpg");
    //ins.push_back("m1.jpg");

    /*ins.push_back("o1.jpg");
    ins.push_back("o2.jpg");
    ins.push_back("o3.jpg");*/

    // 左右
    //ins.push_back("n1.jpg");
    //ins.push_back("n2.jpg");

    // 左右实际照片
    //ins.push_back("p1.jpg");
    //ins.push_back("p2.jpg");

    //斜下
    /*ins.push_back("z1.jpg");
    ins.push_back("z2.jpg");*/

    // 混乱水平顺序
    /*ins.push_back("n3.jpg");
    ins.push_back("n2.jpg");
    ins.push_back("n1.jpg");
    ins.push_back("n4.jpg");
    ins.push_back("n5.jpg");*/

    //平面图 终极杂序
    /*ins.push_back("q1.jpg");
    ins.push_back("q2.jpg");
    ins.push_back("q3.jpg");
    ins.push_back("q4.jpg");
    ins.push_back("q5.jpg");
    ins.push_back("q6.jpg");*/

    // 手机照片
    //ins.push_back("j0.jpg");
    //ins.push_back("j1.jpg");
    //ins.push_back("j2.jpg");
    //ins.push_back("j3.jpg");
    //ins.push_back("j4.jpg");

    //小图
    ins.push_back("s1.jpg");
    ins.push_back("s2.jpg");
    ins.push_back("s3.jpg");

    if(ins.size() > 0) return true;
    else return false;
}
Example #21
0
vector<candidato> sort_around_point(Punto p, const vector<candidato>& points)
{
    /*
     * Sorts a set of points by angle around a point p.
     * If join == false, returns a vector with the points at the right of p
     * and a vector with the points at the left of p. Otherwise it returns
     * just one vector.
     */

    Punto p1(p.x, p.y + 1);
    vector<candidato> r, l;
    r.reserve(points.size());
    l.reserve(points.size());

    for (auto &q : points)
    {
        if (turn(p, p1, q.pt) == RIGHT)
            r.push_back(q);
        else if (turn(p, p1, q.pt) == LEFT)
            l.push_back(q);
        else if (p.y >= q.pt.y)
            l.push_back(q);
        else
            r.push_back(q);
    }

    sort(l.begin(), l.end(), [&p](candidato r, candidato q)->bool
    {
        if(turn(p, r.pt, q.pt) < 0)
            return true;
        return false;
    }
    );

    sort(r.begin(), r.end(), [&p](candidato r, candidato q)->bool
    {
        if(turn(p, r.pt, q.pt) < 0)
            return true;
        return false;
    }
        );

    r.insert(r.end(), l.begin(), l.end());

    bool concave = false;
    unsigned int i = 0;

    for (i = 0; i < r.size(); i++)
        if (turn(r[i].pt, p, r[(i + 1) % r.size()].pt) < 0)
        {
            concave = true;
            break;
        }

    if (concave)
    {
        int start = (i + 1) % r.size();
        vector<candidato> tmp(r);

        for (i = 0; i < tmp.size(); i++)
            r[i] = tmp[(start + i) % r.size()];
    }
    return r;
}
Example #22
0
bool blending_all(const vector<cv::Mat>& img_afs, const vector<shape>& img_shapes, const cv::Size2i& img_size, cv::Mat& result)
{
    // 首先 所有 img_afs 的大小必定是一样的,用 img_size 确定
    for(int i = 0; i < img_afs.size(); i++)
    {
        if(img_afs[i].cols != img_size.width || img_afs[i].rows != img_size.height)
            return false;
    }

    // 新建一张 img_size 的黑色图
    IplImage* img1 = cvCreateImage(img_size, IPL_DEPTH_8U, 3);
    for(int i = 0; i < img1->height; i++)
    {
        uchar *ptrImage = (uchar*)(img1->imageData + i * img1->widthStep);
        for (int j = 0; j < img1->width; j++)
        {
            ptrImage[3 * j + 0]=0;
            ptrImage[3 * j + 1]=0;
            ptrImage[3 * j + 2]=0;
        }
    }
    cv::Mat res = img1;

    vector<vector< vector<int>>> indexTable(res.cols, vector< vector<int>>(res.rows, vector<int>()));
    for(int r = 0; r < res.rows; r++)
    {
        for(int c = 0; c < res.cols; c++)
        {
            for(int idx = 0; idx < img_afs.size(); idx++)
            {
                shape t_shp = img_shapes[idx];
                if(t_shp.isInShape(c, r))
                {
                    indexTable[c][r].push_back(idx);
                }
            }
        }
    }

    /*std::ofstream Dout("indexTable.txt",ios::out);
    for(int i = 0; i < indexTable.size(); i++)
    {
    	for(int j = 0; j < indexTable[i].size(); j++)
    	{
    		Dout<<indexTable[i][j].size()<<" ";
    	}
    	Dout<<endl;
    }*/


    for(int r = 0; r < res.rows; r++)
    {
        for(int c = 0; c < res.cols; c++)
        {
            vector<int> t_index = indexTable[c][r];
            int num_inxt = t_index.size();
            cv::Point2i t_point(c, r);
            if(num_inxt == 0)
            {
                // 没有图片像素,直接设为黑色
                res.at<Vec3b>(t_point) = Vec3b(0, 0, 0);
            }
            else
            {
                /*if(num_inxt == 1)
                	{
                		if(t_index[0] == 0)
                		{
                			res.at<Vec3b>(t_point) = Vec3b(255, 0, 0);
                			//res.at<Vec3b>(t_point) = img_afs[0].at<Vec3b>(t_point);
                		}
                		if(t_index[0] == 1)
                		{
                			res.at<Vec3b>(t_point) = Vec3b(0, 255, 0);
                		}
                		if(t_index[0] == 2)
                		{
                			res.at<Vec3b>(t_point) = Vec3b(0, 0, 255); // Vec3b(0, 0, 255) 为红色
                		}
                	}
                	if(num_inxt == 2)
                	{
                		res.at<Vec3b>(t_point) = Vec3b(255, 255, 255);
                	}*/
                int Blue = 0;
                int Green = 0;
                int Red = 0;
                for(int ni = 0; ni < num_inxt; ni++)
                {
                    Blue += img_afs[t_index[ni]].at<Vec3b>(t_point)[0];
                    Green += img_afs[t_index[ni]].at<Vec3b>(t_point)[1];
                    Red += img_afs[t_index[ni]].at<Vec3b>(t_point)[2];
                    //res.at<Vec3b>(t_point) += ((double)(1/num_inxt)) * img_afs[t_index[ni]].at<Vec3b>(t_point);
                }
                res.at<Vec3b>(t_point) = Vec3b(Blue/num_inxt, Green/num_inxt, Red/num_inxt);
            }
        }
    }

    imwrite("Blend_all.jpg",res);

    result = res;

    return true;
}
 int findPeakElement(const vector<int> &num) {
 	if (num.size() == 1) return 0;
 	return binarySearch(num, 0, num.size()-1);
 }
Example #24
0
	int check(string word, vector<string> dictionary) {
		for (int i = 0; i < dictionary.size(); i++)
			if (word == dictionary[i])
				return i;
		return -1;
	}
void MatchFeatures(const Mat& img_1, const Mat& img_1_orig, 
				   const Mat& img_2, const Mat& img_2_orig,
				   const vector<KeyPoint>& imgpts1,
				   const vector<KeyPoint>& imgpts2,
				   const Mat& descriptors_1, 
				   const Mat& descriptors_2,
				   vector<KeyPoint>& fullpts1,
				   vector<KeyPoint>& fullpts2,
				   int strategy,
				   vector<DMatch>* matches) {
	//strategy
	bool use_features_for_matching =		(strategy & STRATEGY_USE_FEATURE_MATCH) > 0;
	bool use_optical_flow_for_matching =	(strategy & STRATEGY_USE_OPTICAL_FLOW) > 0;
	bool use_dense_optflow =				(strategy & STRATEGY_USE_DENSE_OF) > 0;
	bool use_horiz_disparity =				(strategy & STRATEGY_USE_HORIZ_DISPARITY) > 0;
	
	
	std::vector< DMatch > good_matches_,very_good_matches_;
	std::vector<KeyPoint> keypoints_1, keypoints_2;
	
	Mat_<Point2f> flow_from_features(img_1.size());
#ifdef __SFM__DEBUG__
	Mat outputflow; img_1_orig.copyTo(outputflow);
#endif		
	
	bool update_imgpts1 = (imgpts1.size()<=0);
	bool update_imgpts2 = (imgpts2.size()<=0);
	
	cout << "----------------------------------------------------------------------"<<endl;
	if (update_imgpts1) {
		cout << "imgpts1 empty, get new" << endl;
	} else {
		cout << "imgpts1 has " << imgpts1.size() << " points (descriptors " << descriptors_1.rows << ")" << endl;
	}
	if (update_imgpts2) {
		cout << "imgpts2 empty, get new" << endl;
	} else {
		cout << "imgpts2 has " << imgpts2.size() << " points (descriptors " << descriptors_2.rows << ")" << endl;
	}
	
	if(use_features_for_matching) 
	{	
		//-- Step 1: Detect the keypoints using SURF Detector
		int minHessian = 10;
		
		//		GridAdaptedFeatureDetector detector(new SurfFeatureDetector(minHessian), 1000,1,1);
		SurfFeatureDetector detector( minHessian );
		
		if(update_imgpts1) {
			detector.detect( img_1, keypoints_1 );
		} else {
			keypoints_1 = imgpts1;
		}

		if(update_imgpts2) {
			detector.detect( img_2, keypoints_2 );
		} else {
			keypoints_2 = imgpts2;
		}

		
		//-- Step 2: Calculate descriptors (feature vectors)
		//		SurfDescriptorExtractor extractor(8,4,true);
		SiftDescriptorExtractor extractor(48,16,true);
		//	OpponentColorDescriptorExtractor extractor(new SurfDescriptorExtractor);
		
		if(descriptors_1.empty()) {
//			Mat desc;
//			extractor.compute( img_1, keypoints_1, desc );
//			desc.copyTo(descriptors_1);
			CV_Error(0,"descriptors_1 is empty");
		}
		if(descriptors_2.empty()) {
//			Mat desc;
//			extractor.compute( img_2, keypoints_2, desc );
//			desc.copyTo(descriptors_2);
			CV_Error(0,"descriptors_2 is empty");
		}
		
		//-- Step 3: Matching descriptor vectors using FLANN matcher
		//FlannBasedMatcher matcher;
		BFMatcher matcher(NORM_L2,true); //use an alternative to the ratio test
		std::vector< DMatch > matches_;
		if (matches == NULL) {
			matches = &matches_;
		}
		if (matches->size() == 0) {
#ifdef __SFM__DEBUG__
			cout << "matching desc1="<<descriptors_1.rows<<", desc2="<<descriptors_2.rows<<endl;
#endif
			matcher.match( descriptors_1, descriptors_2, *matches );
		}
		
#ifdef __SFM__DEBUG__
		cout << "matches->size() " << matches->size() << endl;
#endif
		
		double max_dist = 0; double min_dist = 1000.0;
		//-- Quick calculation of max and min distances between keypoints
		for(unsigned int i = 0; i < matches->size(); i++ )
		{ 
			double dist = (*matches)[i].distance;
			if( dist < min_dist ) min_dist = dist;
			if( dist > max_dist ) max_dist = dist;
		}
		
#ifdef __SFM__DEBUG__
		printf("-- Max dist : %f \n", max_dist );
		printf("-- Min dist : %f \n", min_dist );
#endif
		
		vector<KeyPoint> imgpts1_good,imgpts2_good;

		if (min_dist <= 0) {
			min_dist = 10.0;
		}
		
		double cutoff = 4.0*min_dist;
		std::set<int> existing_trainIdx;
		for(unsigned int i = 0; i < matches->size(); i++ )
		{ 
			if ((*matches)[i].trainIdx <= 0) {
				(*matches)[i].trainIdx = (*matches)[i].imgIdx;
			}
			
			if( existing_trainIdx.find((*matches)[i].trainIdx) == existing_trainIdx.end() && 
				(*matches)[i].trainIdx >= 0 && (*matches)[i].trainIdx < (int)(keypoints_2.size()) &&
				(*matches)[i].distance > 0.0 && (*matches)[i].distance < cutoff ) 
			{
				good_matches_.push_back( (*matches)[i]);
				imgpts1_good.push_back(keypoints_1[(*matches)[i].queryIdx]);
				imgpts2_good.push_back(keypoints_2[(*matches)[i].trainIdx]);
				existing_trainIdx.insert((*matches)[i].trainIdx);
			}
		}
		
		
#ifdef __SFM__DEBUG__
		cout << "keypoints_1.size() " << keypoints_1.size() << " imgpts1_good.size() " << imgpts1_good.size() << endl;
		cout << "keypoints_2.size() " << keypoints_2.size() << " imgpts2_good.size() " << imgpts2_good.size() << endl;

		{
			//-- Draw only "good" matches
			Mat img_matches;
			drawMatches( img_1, keypoints_1, img_2, keypoints_2,
						good_matches_, img_matches, Scalar::all(-1), Scalar::all(-1),
						vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );		
			//-- Show detected matches
			imshow( "Feature Matches", img_matches );
			waitKey(100);
			destroyWindow("Feature Matches");
		}
#endif
		
		//Let the feature matching guide the general flow...
		
		vector<uchar> status;
		vector<KeyPoint> imgpts2_very_good,imgpts1_very_good;
		
		
		//Select features that make epipolar sense
		{
			vector<Point2f> pts1,pts2;
			KeyPointsToPoints(imgpts1_good, pts1);
			KeyPointsToPoints(imgpts2_good, pts2);
#ifdef __SFM__DEBUG__
			cout << "pts1 " << pts1.size() << " (orig pts " << imgpts1_good.size() << ")" << endl;
			cout << "pts2 " << pts2.size() << " (orig pts " << imgpts2_good.size() << ")" << endl;
#endif
			Mat F = findFundamentalMat(pts1, pts2, FM_RANSAC, 0.1, 0.99, status);
		}
		cout << "Fundamental mat is keeping " << countNonZero(status) << " / " << status.size() << endl;	
		
		double status_nz = countNonZero(status); 
		double status_sz = status.size();
		double kept_ratio = status_nz / status_sz;
		if (kept_ratio > 0.2) {
			
			for (unsigned int i=0; i<imgpts1_good.size(); i++) {
				if (status[i]) 
				{
					imgpts1_very_good.push_back(imgpts1_good[i]);
					imgpts2_very_good.push_back(imgpts2_good[i]);
				}
			}
			
			if(use_optical_flow_for_matching) {
				//Estimate the overall 2D homography
		//		Mat_<double> H;
		//		{
		//			vector<Point2f> pts1,pts2;
		//			KeyPointsToPoints(imgpts1_very_good, pts1);
		//			KeyPointsToPoints(imgpts2_very_good, pts2);
		//			cout << "pts1 " << pts1.size() << endl;
		//			cout << "pts2 " << pts2.size() << endl;
		//			H = findHomography(pts1, pts2, CV_RANSAC, 0.001);
		//			cout << "homography from features " << endl << H << endl;
		//		}
				Mat_<double> T;
				{
					vector<Point2f> pts1,pts2;
					KeyPointsToPoints(imgpts1_very_good, pts1);
					KeyPointsToPoints(imgpts2_very_good, pts2);
#ifdef __SFM__DEBUG__
					cout << "pts1 " << pts1.size() << endl;
					cout << "pts2 " << pts2.size() << endl;
#endif
					T = estimateRigidTransform(pts1,pts2, false);
#ifdef __SFM__DEBUG__
					cout << "rigid transform from features " << endl << T << endl;
#endif
				}
				
				//Create the approximate flow using the estimated overall motion
				for (int x=0; x<img_1.cols; x++) {
					for (int y=0; y<img_1.rows; y++) {
		//				Mat_<double> moved = H * (Mat_<double>(3,1) << x , y , 1);
						Mat_<double> moved = T * (Mat_<double>(3,1) << x , y , 1);
						Point2f movedpt(moved(0),moved(1));
						flow_from_features(y,x) = Point2f(movedpt.x-x,movedpt.y-y);
#ifdef __SFM__DEBUG__
		//				circle(outputflow, Point(x,y), 1, Scalar(0,255*norm(flow_from_features(y,x))/250), 1);
						if (x%20 == 0 && y%20 == 0) {
		//					cout << "Point " << Point(x,y) << " moved to " << movedpt << endl;
							line(outputflow, Point(x,y), movedpt, Scalar(0,255*norm(flow_from_features(y,x))/50), 1);
						}
#endif
					}
				}
#ifdef __SFM__DEBUG__
				imshow("flow", outputflow);
				waitKey(100);
				destroyWindow("flow");
#endif		
			}
		} 
	} 
	if(use_optical_flow_for_matching) 
	{
#ifdef __SFM__DEBUG__
		img_1_orig.copyTo(outputflow);
#endif		
		double t = getTickCount();
		cout << "Optical Flow...";
		if(use_dense_optflow) {
			cout << "Dense...";
			Mat_<Point2f> _flow,flow;
			if (use_features_for_matching) {
				flow_from_features.copyTo(flow);
			} else {
				//coarse
				calcOpticalFlowFarneback(img_1,img_2,flow,0.5,5,150,60,7,1.5,OPTFLOW_FARNEBACK_GAUSSIAN);
			}

			//refine
			calcOpticalFlowFarneback(img_1,img_2,flow,0.5,2,40,40,5,0.5,OPTFLOW_USE_INITIAL_FLOW);
			calcOpticalFlowFarneback(img_1,img_2,flow,0.5,0,25,40,3,0.25,OPTFLOW_USE_INITIAL_FLOW);
			
			//imgpts1.clear(); imgpts2.clear(); 
			good_matches_.clear(); keypoints_1.clear(); keypoints_2.clear();
			
			for (int x=0;x<flow.cols; x+=1) {
				for (int y=0; y<flow.rows; y+=1) {
					if (norm(flow(y,x)) < 20 || norm(flow(y,x)) > 100) {
						continue; //discard points that havn't moved
					}
					Point2f p(x,y),p1(x+flow(y,x).x,y+flow(y,x).y);
					
					//line(outputflow, p, p1, Scalar(0,255*norm(flow(y,x))/50), 1);
#ifdef __SFM__DEBUG__
					circle(outputflow, p, 1, Scalar(0,255*norm(flow(y,x))/50), 1);
#endif
					if (x%10 == 0 && y%10 == 0) {
//						imgpts1.push_back(KeyPoint(p,1));
//						imgpts2.push_back(KeyPoint(p1,1));
						good_matches_.push_back(DMatch(imgpts1.size()-1,imgpts1.size()-1,1.0));
						keypoints_1.push_back(KeyPoint(p,1));
						keypoints_2.push_back(KeyPoint(p1,1));
					}
					fullpts1.push_back(KeyPoint(p,1));
					fullpts2.push_back(KeyPoint(p1,1));
				}
			}		
		} else {
			vector<Point2f> corners,nextPts; vector<uchar> status; vector<float> err;
			goodFeaturesToTrack(img_1, corners, 2000, 0.001, 10);
			cornerSubPix(img_1, corners, Size(15,15), Size(-1,-1), TermCriteria( CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.001 ));
			calcOpticalFlowPyrLK(img_1, img_2, corners, nextPts, status, err, Size(45,45));
			for (unsigned int i=0; i<corners.size(); i++) {
				if(status[i] == 1) {
#ifdef __SFM__DEBUG__
					line(outputflow, corners[i], nextPts[i], Scalar(0,255), 1);
#endif
//					imgpts1.push_back(KeyPoint(corners[i],1));
//					imgpts2.push_back(KeyPoint(nextPts[i],1));
					good_matches_.push_back(DMatch(imgpts1.size()-1,imgpts1.size()-1,1.0));
					keypoints_1.push_back(KeyPoint(corners[i],1));
					keypoints_2.push_back(KeyPoint(nextPts[i],1));
				}
			}
		}
		t = ((double)getTickCount() - t)/getTickFrequency();
		cout << "Done. (" << t <<"s)"<< endl;
#ifdef __SFM__DEBUG__
		imshow("flow", outputflow);
		waitKey(100);
		destroyWindow("flow");
#endif
	} 
	else if(use_horiz_disparity) 
	{		
		double downscale = 0.6;
		Mat small_im1; resize(img_1_orig,small_im1,Size(),downscale,downscale);
		Mat small_im2; resize(img_2_orig,small_im2,Size(),downscale,downscale);
		int numberOfDisparities = ((small_im1.cols/8) + 15) & -16;
		
		StereoSGBM sgbm;
		sgbm.preFilterCap = 63;
		sgbm.SADWindowSize = 3;
		
		int cn = img_1_orig.channels();
		
		sgbm.P1 = 8*cn*sgbm.SADWindowSize*sgbm.SADWindowSize;
		sgbm.P2 = 32*cn*sgbm.SADWindowSize*sgbm.SADWindowSize;
		sgbm.minDisparity = 0;
		sgbm.numberOfDisparities = numberOfDisparities;
		sgbm.uniquenessRatio = 10;
		sgbm.speckleWindowSize = 100;
		sgbm.speckleRange = 32;
		sgbm.disp12MaxDiff = 1;
		sgbm.fullDP = false;
		
		Mat_<short> disp;
		sgbm(small_im1, small_im2, disp);
		Mat disp8; disp.convertTo(disp8, CV_8U, 255/(numberOfDisparities*16.));
#ifdef __SFM__DEBUG__
		imshow("disparity",disp8);
		waitKey(0);
		destroyWindow("disparity");
#endif		
		Mat outputflow; img_1_orig.copyTo(outputflow);
		Mat_<short> disp_orig_scale; resize(disp,disp_orig_scale,img_1.size());
		
		for (int x=0;x<disp_orig_scale.cols; x+=1) {
			for (int y=0; y<disp_orig_scale.rows; y+=1) {
				float _d = ((float)disp_orig_scale(y,x))/(16.0 * downscale);
				if (fabsf(_d) > 150.0f || fabsf(_d) < 5.0f) {
					continue; //discard strange points 
				}
				Point2f p(x,y),p1(x-_d,y);
#ifdef __SFM__DEBUG__
				circle(outputflow, p, 1, Scalar(0,255*_d/50.0), 1);
#endif
				if (x%10 == 0 && y%10 == 0) {
//					imgpts1.push_back(KeyPoint(p,1));
//					imgpts2.push_back(KeyPoint(p1,1));
					good_matches_.push_back(DMatch(imgpts1.size()-1,imgpts1.size()-1,1.0));
					keypoints_1.push_back(KeyPoint(p,1));
					keypoints_2.push_back(KeyPoint(p1,1));
				}
				fullpts1.push_back(KeyPoint(p,1));
				fullpts2.push_back(KeyPoint(p1,1));
			}
		}		
#ifdef __SFM__DEBUG__		
		imshow("outputflow", outputflow);
		waitKey(0);
		destroyWindow("outputflow");
#endif
	}
	
	//Draw matches
//	if(0) 
#ifdef __SFM__DEBUG__
	{
		//-- Draw only "good" matches
		Mat img_matches;
		drawMatches( img_1, keypoints_1, img_2, keypoints_2,
					good_matches_, img_matches, Scalar::all(-1), Scalar::all(-1),
					vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );		
		//-- Show detected matches
		imshow( "Good Matches", img_matches );
		waitKey(100);
		destroyWindow("Good Matches");
	}
#endif
}
bool car_allowed_to_move(vector<vector<float>> Car, int carnumber)  //Evaluate if car is allowed to move in order to avert collision!!
{
bool allowed_to_move;
int startnumber;
int exitnumber;
float global_t;
int cx;
int cy;
int px;
int py;
int opposite;

int minimum_distance_to_keep_left_turning = 29;

startnumber=	int(Car.at(carnumber).at(1));
exitnumber=		int(Car.at(carnumber).at(2));
global_t=		Car.at(carnumber).at(3);
cx=				int(Car.at(carnumber).at(4));
cy=				int(Car.at(carnumber).at(5));
px=				int(Car.at(carnumber).at(6));
py=				int(Car.at(carnumber).at(7));
//(Car.at(carnumber).at(8)); //If car is at end
if (distance_to_origin_decreasing(Car, carnumber) == false)// if distance NOT decreasing
{
	return allowed_to_move = true;
}

	if((startnumber==1 || startnumber==3) && light_phase==true)
	{
		if (distance_to_origin(Car,carnumber) < 25)
		{
			return allowed_to_move = false;
		}
	}
	if ((startnumber == 0 || startnumber == 2) && light_phase==false)
	{
		if (distance_to_origin(Car, carnumber) < 25)
		{
			return allowed_to_move = false;
		}
	}


if(startnumber==0 || startnumber==1)
{
	opposite=(startnumber+2);
}
if(startnumber==2 || startnumber==3)
{
	opposite=(startnumber-2);
}

if(exitnumber==opposite)
{
	return allowed_to_move = true;
}

if (startnumber == 1 || startnumber == 2 || startnumber == 3)
{
	if (exitnumber == (startnumber - 1))
	{
		return allowed_to_move = true;
	}
}
if (startnumber == 0 && exitnumber == 3)
{
	//car_turn_right=true;
	return allowed_to_move = true;
}

bool car_turn_left=false;
if(startnumber==0 || startnumber==1 || startnumber==2)
{
	if(exitnumber==(startnumber+1))
	{
		car_turn_left=true;
	}
}
if(startnumber==3 && exitnumber==0)
{
	car_turn_left=true;
}


for (int carnumber_index = 0; carnumber_index < Car.size(); carnumber_index++)
{
	if (Car.at(carnumber_index).at(8) == 0) // Only take into account other car, if it is NOT at end position!
	{
		if ((carnumber_index != carnumber) && (Car.at(carnumber_index).at(1) == opposite) && (car_turn_left == true) &&
			(distance_to_origin(Car, carnumber_index) < minimum_distance_to_keep_left_turning)
			&& (distance_to_origin_decreasing(Car, carnumber_index)))//If startnumber of other car is opposite
		{
			return allowed_to_move = false;
		}
	}
}
return allowed_to_move = true;
}
float CaffeFeatExtractor<Dtype>::extractBatch_singleFeat_1D(vector<cv::Mat> &images, int new_batch_size, vector< vector<Dtype> > &features)
{

    // Set the GPU/CPU mode for Caffe (here in order to be thread-safe)
    if (gpu_mode)
    {
        Caffe::set_mode(Caffe::GPU);
        Caffe::SetDevice(device_id);
    }
    else
    {
        Caffe::set_mode(Caffe::CPU);
    }

    cudaEvent_t start, stop;

    if (timing)
    {
        cudaEventCreate(&start);
        cudaEventCreate(&stop);
        cudaEventRecord(start, NULL);
    }

    // Initialize labels to zero
    vector<int> labels(images.size(), 0);

    // Get pointer to data layer to set the input
    caffe::shared_ptr<MemoryDataLayer<Dtype> > memory_data_layer = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<Dtype> >(feature_extraction_net->layers()[0]);

    // Set batch size

    if (memory_data_layer->batch_size()!=new_batch_size)
    {
        if (images.size()%new_batch_size==0)
        {
            memory_data_layer->set_batch_size(new_batch_size);
            cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
        }
        else
        {
            if (images.size()%memory_data_layer->batch_size()==0)
            {
                cout << "WARNING: image number is not multiple of requested batch size,leaving the old one." << endl;
                cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
            } else
            {
                cout << "WARNING: image number is not multiple of batch size, setting it to 1 (performance issue)." << endl;
                memory_data_layer->set_batch_size(1);
                cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
            }

        }

    } else
    {
        if (images.size()%memory_data_layer->batch_size()!=0)
        {
            cout << "WARNING: image number is not multiple of batch size, setting it to 1 (performance issue)." << endl;
            memory_data_layer->set_batch_size(1);
            cout << "BATCH SIZE = " << memory_data_layer->batch_size() << endl;
        }
    }

    int num_batches = images.size()/new_batch_size;

    // Input preprocessing

    // The image passed to AddMatVector must be same size as the mean image
    // If not, it is resized:
    // if it is downsampled, an anti-aliasing Gaussian Filter is applied

    for (int i=0; i<images.size(); i++)
    {
        if (images[i].rows != mean_height || images[i].cols != mean_height)
        {
            if (images[i].rows > mean_height || images[i].cols > mean_height)
            {
                cv::resize(images[i], images[i], cv::Size(mean_height, mean_width), 0, 0, CV_INTER_LANCZOS4);
            }
            else
            {
                cv::resize(images[i], images[i], cv::Size(mean_height, mean_width), 0, 0, CV_INTER_LINEAR);
            }
        }
    }

    memory_data_layer->AddMatVector(images,labels);

    size_t num_features = blob_names.size();
    if (num_features!=1)
    {
        cout<< "Error! The list of features to be extracted has not size one!" << endl;
        return -1;
    }

    // Run network and retrieve features!

    std::vector<Blob<Dtype>*> results;

    for (int b=0; b<num_batches; ++b)
    {
        results = feature_extraction_net->Forward();

        const caffe::shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net->blob_by_name(blob_names[0]);

        int batch_size = feature_blob->num();

        int feat_dim = feature_blob->count() / batch_size; // should be equal to: channels*width*height
        if (feat_dim!=feature_blob->channels())
        {
            cout<< "Attention! The feature is not 1D: unrolling according to Caffe's order (i.e. channel, width, height)" << endl;
        }

        for (int i=0; i<batch_size; ++i)
        {
            features.push_back(vector <Dtype>(feature_blob->mutable_cpu_data() + feature_blob->offset(i), feature_blob->mutable_cpu_data() + feature_blob->offset(i) + feat_dim));
        }

    }

    if (timing)
    {
        // Record the stop event
        cudaEventRecord(stop, NULL);

        // Wait for the stop event to complete
        cudaEventSynchronize(stop);

        float msecTotal = 0.0f;
        cudaEventElapsedTime(&msecTotal, start, stop);

        float msecPerImage = msecTotal/(float)images.size();

        return msecPerImage;
    }
    else
    {
        return 0;
    }
}
Example #28
0
ll mcm(const vector<int>& moves) {
    ll res = 1;
    for (int i = 0; i < (signed)moves.size(); ++i) res = mcm2(res, moves[i]);
    return res; 
}
Example #29
0
    vector<vector<int> > threeSum(vector<int> &num) {
    	typedef vector<int>::size_type itype;
    	vector<vector<int> > result;

    	sort(num.begin(), num.end());
    	itype len = num.size();
    	if (len < 3)
    		return result;

    	for (int i = 0;i < len;i++) {
    		cout<<num[i]<<" ";
    	}
    	cout<<endl;

    	//find the position of the biggest negative number and positive number
    	int posPos = len - 1;
    	if (num[posPos] < 0)
    		return result;

    	int posNeg = -1;
    	for (itype i = 0;i < len;i++) {
    		if (num[i] >= 0)
    			break;
    		posNeg++;
    	}

    	//no negative number
    	/*if (posNeg == -1) {
    		if (num[0] == 0 && num[1] == 0 && num[2] == 0) {
    			hPushBack(result, 0, 0, 0);
    			//result.push_back(vector<int>{0, 0, 0});
    		}

    		return result;
    	}*/
    	if (len - posNeg > 3) {
    		if (num[posNeg + 1] == 0 && num[posNeg + 2] == 0 && num[posNeg + 3] == 0) {
    			hPushBack(result, 0, 0, 0);
    		}
    	}

    	//one negative with 2 positives
    	int curNeg = 0;
    	int tempPosPos = posPos;
    	for (int i = 0;i <= posNeg;i++) {
    		if (num[i] == curNeg)
    			continue;

    		curNeg = num[i];

    		int first = -1;
    		int second = -1;
    		for (int j = tempPosPos;j > posNeg + 1;j--) {
    			//skip equal numbers
    			if (num[j] == first)
    				continue;
    			first = num[j];

    			//The biggest positive is too big
    			if (first + curNeg > 0) {
    				tempPosPos--;
    				continue;
    			}
    			int sum = 0;
    			second = -1;
    			for (int k = j - 1;k > posNeg;k--) {
    				if (num[k] == second)
    					continue;
    				second = num[k];
    				sum = curNeg + first + second;
    				if (sum == 0) {
    					//result.push_back(vector<int>{curNeg, second, first});
    					hPushBack(result, curNeg, second, first);
    					break;
    				}
    				if (sum < 0)
    					break;
    			}
    		}
    	}

    	//2 negatives with 1 positive
    	int curPos = -1;
    	int startPos = 0;
    	for (int i = posPos;i > posNeg;i--) {
    		if (num[i] == curPos)
    			continue;

    		curPos = num[i];

    		int first = 1;
    		int second = 1;
    		for (int j = startPos;j < posNeg;j++) {
    			//skip equal numbers
    			if (num[j] == first)
    				continue;
    			first = num[j];

    			//The smallest negative is too small
    			if (first + curPos < 0) {
    				startPos++;
    				continue;
    			}
    			int sum = 0;
    			second = 1;
    			for (int k = j + 1;k <= posNeg;k++) {
    				if (num[k] == second)
    					continue;
    				second = num[k];
    				sum = curPos + first + second;
    				if (sum == 0) {
    					//result.push_back(vector<int>{curNeg, second, first});
    					hPushBack(result, first, second, curPos);
    					break;
    				}
    				if (sum > 0)
    					break;
    			}
    		}
    	}

    	for (itype i = 0;i < result.size();i++) {
    		for (itype j = 0;j < result[i].size();j++)
    			cout<<result[i][j]<<" ";
    		cout<<endl;
    	}
    	return result;
    }
Example #30
0
 void printFeatures() {
     for (size_t i = 0; i < features.size(); i++) {
         cout << features.at(i) << ",";
     }
     cout << endl;
 }