<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by ScyllaDB
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "utils/serialization.hh"
#include "gms/heart_beat_state.hh"
#include "gms/application_state.hh"
#include "gms/versioned_value.hh"
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <experimental/optional>
#include <chrono>

namespace gms {

/**
 * This abstraction represents both the HeartBeatState and the ApplicationState in an EndpointState
 * instance. Any state for a given endpoint can be retrieved from this instance.
 */
class endpoint_state {
public:
    using clk = seastar::lowres_system_clock;
private:
    heart_beat_state _heart_beat_state;
    std::map<application_state, versioned_value> _application_state;
    /* fields below do not get serialized */
    clk::time_point _update_timestamp;
    bool _is_alive;
public:
    bool operator==(const endpoint_state& other) const {
        return _heart_beat_state  == other._heart_beat_state &&
               _application_state == other._application_state &&
               _update_timestamp  == other._update_timestamp &&
               _is_alive          == other._is_alive;
    }

    endpoint_state()
        : _heart_beat_state(0)
        , _update_timestamp(clk::now())
        , _is_alive(true) {
    }

    endpoint_state(heart_beat_state initial_hb_state)
        : _heart_beat_state(initial_hb_state)
        , _update_timestamp(clk::now())
        , _is_alive(true) {
    }

    endpoint_state(heart_beat_state&& initial_hb_state,
            const std::map<application_state, versioned_value>& application_state)
        : _heart_beat_state(std::move(initial_hb_state))
          ,_application_state(application_state)
        , _update_timestamp(clk::now())
        , _is_alive(true) {
    }

    heart_beat_state& get_heart_beat_state() {
        return _heart_beat_state;
    }

    const heart_beat_state& get_heart_beat_state() const {
        return _heart_beat_state;
    }

    void set_heart_beat_state_and_update_timestamp(heart_beat_state hbs) {
        update_timestamp();
        _heart_beat_state = hbs;
    }

    std::experimental::optional<versioned_value> get_application_state(application_state key) const;
    const versioned_value* get_application_state_ptr(application_state key) const;

    /**
     * TODO replace this with operations that don't expose private state
     */
    // @Deprecated
    std::map<application_state, versioned_value>& get_application_state_map() {
        return _application_state;
    }

    const std::map<application_state, versioned_value>& get_application_state_map() const {
        return _application_state;
    }

    void add_application_state(application_state key, versioned_value value) {
        if (_application_state.count(key)) {
            _application_state.at(key) = value;
        } else {
            _application_state.emplace(key, value);
        }
    }

    /* getters and setters */
    /**
     * @return System.nanoTime() when state was updated last time.
     */
    clk::time_point get_update_timestamp() const {
        return _update_timestamp;
    }

    void update_timestamp() {
        _update_timestamp = clk::now();
    }

    bool is_alive() const {
        return _is_alive;
    }

    void mark_alive() {
        _is_alive = true;
    }

    void mark_dead() {
        _is_alive = false;
    }

    bool is_shutdown() const {
        auto app_state = get_application_state(application_state::STATUS);
        if (!app_state) {
            return false;
        }
        auto value = app_state->value;
        std::vector<sstring> pieces;
        boost::split(pieces, value, boost::is_any_of(","));
        if (pieces.empty()) {
            return false;
        }
        return pieces[0] == sstring(versioned_value::SHUTDOWN);
    }

    friend std::ostream& operator<<(std::ostream& os, const endpoint_state& x);
};

} // gms
<commit_msg>gms/endpoint_state: Avoid copies in is_shutdown()<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by ScyllaDB
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "utils/serialization.hh"
#include "gms/heart_beat_state.hh"
#include "gms/application_state.hh"
#include "gms/versioned_value.hh"
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <experimental/optional>
#include <chrono>

namespace gms {

/**
 * This abstraction represents both the HeartBeatState and the ApplicationState in an EndpointState
 * instance. Any state for a given endpoint can be retrieved from this instance.
 */
class endpoint_state {
public:
    using clk = seastar::lowres_system_clock;
private:
    heart_beat_state _heart_beat_state;
    std::map<application_state, versioned_value> _application_state;
    /* fields below do not get serialized */
    clk::time_point _update_timestamp;
    bool _is_alive;
public:
    bool operator==(const endpoint_state& other) const {
        return _heart_beat_state  == other._heart_beat_state &&
               _application_state == other._application_state &&
               _update_timestamp  == other._update_timestamp &&
               _is_alive          == other._is_alive;
    }

    endpoint_state()
        : _heart_beat_state(0)
        , _update_timestamp(clk::now())
        , _is_alive(true) {
    }

    endpoint_state(heart_beat_state initial_hb_state)
        : _heart_beat_state(initial_hb_state)
        , _update_timestamp(clk::now())
        , _is_alive(true) {
    }

    endpoint_state(heart_beat_state&& initial_hb_state,
            const std::map<application_state, versioned_value>& application_state)
        : _heart_beat_state(std::move(initial_hb_state))
          ,_application_state(application_state)
        , _update_timestamp(clk::now())
        , _is_alive(true) {
    }

    heart_beat_state& get_heart_beat_state() {
        return _heart_beat_state;
    }

    const heart_beat_state& get_heart_beat_state() const {
        return _heart_beat_state;
    }

    void set_heart_beat_state_and_update_timestamp(heart_beat_state hbs) {
        update_timestamp();
        _heart_beat_state = hbs;
    }

    std::experimental::optional<versioned_value> get_application_state(application_state key) const;
    const versioned_value* get_application_state_ptr(application_state key) const;

    /**
     * TODO replace this with operations that don't expose private state
     */
    // @Deprecated
    std::map<application_state, versioned_value>& get_application_state_map() {
        return _application_state;
    }

    const std::map<application_state, versioned_value>& get_application_state_map() const {
        return _application_state;
    }

    void add_application_state(application_state key, versioned_value value) {
        if (_application_state.count(key)) {
            _application_state.at(key) = value;
        } else {
            _application_state.emplace(key, value);
        }
    }

    /* getters and setters */
    /**
     * @return System.nanoTime() when state was updated last time.
     */
    clk::time_point get_update_timestamp() const {
        return _update_timestamp;
    }

    void update_timestamp() {
        _update_timestamp = clk::now();
    }

    bool is_alive() const {
        return _is_alive;
    }

    void mark_alive() {
        _is_alive = true;
    }

    void mark_dead() {
        _is_alive = false;
    }

    bool is_shutdown() const {
        auto* app_state = get_application_state_ptr(application_state::STATUS);
        if (!app_state) {
            return false;
        }
        auto value = app_state->value;
        std::vector<sstring> pieces;
        boost::split(pieces, value, boost::is_any_of(","));
        if (pieces.empty()) {
            return false;
        }
        return pieces[0] == sstring(versioned_value::SHUTDOWN);
    }

    friend std::ostream& operator<<(std::ostream& os, const endpoint_state& x);
};

} // gms
<|endoftext|>


<commit_before>#include <std.h>
#include <vector.h>
#include <cv2.h>

typedef vector<Point> cnt;

class IMGProcessor {
	private:
	    //All contours from findPoly along with the heirarchy
	    struct Cnts {
	        vector<cnt> contours;
	        vector<Vec4i> heirarchy;
	    }

	    //A Focus Point
	    class Fp {
			public:
		        vector<cnt> contours;
		        Point center;
		        int depth, shape;

		        public Fp(vector<cnt> contours) throws Exception {
		            this.contours = contours;
		            this.center = centroid(contours);
		            this.depth = findInnerBorder();
		            this.shape = contours.length;
		        }

			private:
		        //Takes the contours and returns the index of
		        int findInnerBorder() throws Exception {

				}
	    }

	    // -------------- Feature Detection ----------------
	    //Filters the img, finds the contours, and returns the Cnts.
	    Cnts findPolys (Mat img,int polyTol) {
	        //Find contours and heirarchy
	        vector<cnt> contours, polys; vector<Vec4i> heirarchy;
	        findContours(img,contours,heirarchy,RETR_TREE,CHAIN_APPROX_SIMPLE);

	        //Return approximate polygons
	        for(int i=0;i<sizeOf(contours);i++){
	            approxPolyDP(contours[i],polys[i],polyTol,true);
	        }

	        //Return Cnts
	        return {polys, heirarchy};
	    }
	    Cnts findPolys(Mat img){return findPolys(img,5);}

	    //Find all the focus points within an image.
	    vector<Fp> findFocusPoints (Cnts polys) {
	        //Definitions
	        vector<FP> out; FP tempFp; vector<vector<cnt>> cntV; vector<int> done; vector<cnt> contours; int k;

	        for(int i=0;i<sizeOf(polys.contours);i++){
	            k=i; poly.empty();
	            if(!done.contains(i)){        //Check that through navigation you haven't been here before
	                done.push_back(i);

	                //Navigate the heirarchy
	                while(heirarchy[k][2]!=-1){
	                    k=heirarchy[k][2];
	                    done.push_back(k);
	                    contours.push_back(polys.contours[k]);
	                }
	                if(heirarchy[k][2]!=-1){contours.push_back(polys.contours[k]);} //Add the last element

	                //Check if there are enough polys to count as a potential focus point, append them to fp
	                if(sizeOf(poly)>=5){cntV.push_back(contours);}
	            }
	        }

	        //Filter the focus points for their innermost border
	        for(int x=0;x<sizeOf(cntV);x++){
	            try {
	                tempFp = new Fp(cntV[x]);
	                out.push_back(tempFp);
	            } catch (Exception e) {}
	        }
			delete tempFp

	        //Return the focus points
	        return out;
	    }

		//Classifies squares and selects the four most likely to be corners
	    vector<Fp> getCorners(vector<Fp> focusPoints, int angleTol){
			list<Fp> fours = remove_if(fp.begin(),fp.end(),[](Fp z){return len(z)!=4;});
			double angles (Point x) {
				vector<double> out;
				for (Fp y:fours) for (Fp z:fours) if (x != y && y != z && x != z) out.push_back(angle(x,y,z));
				return out;
			}

			//Classify corners as having 2 right angles
			vector<Fp> out;
			for (f : fours)
				if len(filter(lambda z: np.absolute(z-90.0)<ATOL, angles(c)))>=2 and c not in out:
					out.append(c)

			//Return their centroids
			if len(out)!=4: raise Exception("Corners not Detected!")
			else: print out
			return out
		}

	    vector<Fp> sortCorners(vector<Fp> corners){}

	    // ------------ Image Manipulation --------------
	    Mat importFilter(Mat img,int tol1,int tol2,int wSize){
	        //Declarations
	        Mat gray,edges;

	        //Convert to gray if not already
	        try{cvtColor(img,gray,COLOR_RGB2GRAY);}
	        catch(Exception e){
	            gray = img.copy();
	        }

	        //Return Canny Edge Detection
	        Canny(gray,edges,tol1,tol2,wSize);
	        return edges
	    }
	    Mat importFilter(Mat img){return importFilter(img,100,200,3);}

	    Mat outputFilter(Mat img,int wSize,int C){

		}
	    Mat outputFilter(Mat img){return outputFilter(img,11,2);}

	    Mat cropImage(Mat img){

		}

	    Mat fixPerspective(Mat img,int[][] border,int ref,double ratio){

		}
	    Mat fixPerspective(Mat img,int[][] border,int ref){return fixPerspective(img,border,ref,8.5/11.0);}

	    // -------------- Geometric ------------------
	    Point centroid(cnt contour){

		}
	    Point centroid(vector<cnt> contours){

		}
	    Point centroid(Cnts contours){

		}

	    double dist(Point a, Point b){

		}

	    bool allSameLength(cnt poly, int distTol){

		}
	    bool allSameLength(cnt poly){return allSameLength(poly,5);}

	public:
	    // -------------- Main Methods ----------------------
	    Mat process(Mat img,int angleTol,int distTol,int polyTol,int blockSize,int C,double aspectRatio,int etol1,int etol2,int eSize){

		}
	    Mat process(Mat img){return call(img,10,5,5,11,2,8.5/11.0,100,200,3);}

	    void IMGProcessor() {}
}
<commit_msg>Got everything written...<commit_after>#include <std.h>
#include <vector.h>
#include <cv2.h>

typedef vector<Point> cnt;

class IMGProcessor {
	private:
		//All contours from findPoly along with the heirarchy
		struct Cnts {
			vector<cnt> contours;
			vector<Vec4i> heirarchy;
		}

		//A Focus Point
		class Fp {
			public:
				vector<cnt> contours;
				Point center;
				int depth, shape;

				Fp (vector<cnt> contours) throws Exception {
					this.contours = contours;
					this.center = centroid(contours);
					this.depth = findInnerBorder(contours);
					this.shape = contours.length;
				}

			private:
				//Checks shape of each contour from last to -5 and finds the first 'square.' Returns 0 if none exists.
				int findInnerBorder(vector<cnt> cnts) throws Exception {
					cnt contour;
					for (int x = sizeOf(cnts); x > 0; x++) {
						contour = cnts[x]
						if (isContourConvex(contour) && sizeOf(contour)==4 && allSameLength(contour)) {return x+1;}
						else {throw Exception e;}
					}
				}
				int findInnerBorder(Cnts cnts) throws Exception {return findInnerBorder(cnts.contours);}
		}

		// -------------- Feature Detection ----------------
		//Filters the img, finds the contours, and returns the Cnts.
		Cnts findPolys (Mat img) {
			//Find contours and heirarchy
			vector<cnt> contours, polys; vector<Vec4i> heirarchy;
			findContours(img, contours, heirarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);

			//Return approximate polygons
			for(int i=0; i<sizeOf(contours); i++) {
				approxPolyDP(contours[i],polys[i],polyTol,true);
			}

			//Return Cnts
			return {polys, heirarchy};
		}

		//Find all the focus points within an image.
		vector<Fp> findFocusPoints (Cnts polys) {
			//Definitions
			vector<FP> out; FP tempFp; vector<vector<cnt>> cntV;
			vector<int> done; vector<cnt> contours; int k;

			for(int i=0;i<sizeOf(polys.contours);i++){
				k=i; poly.clear();
				if(!done.contains(i)){        //Check that through navigation you haven't been here before
					done.push_back(i);

					//Navigate the heirarchy
					while(heirarchy[k][2]!=-1){
						k=heirarchy[k][2];
						done.push_back(k);
						contours.push_back(polys.contours[k]);
					}
					if(heirarchy[k][2]!=-1){contours.push_back(polys.contours[k]);} //Add the last element

					//Check if there are enough polys to count as a potential focus point, append them to fp
					if(sizeOf(poly)>=5){cntV.push_back(contours);}
				}
			}

			//Filter the focus points for their innermost border
			for(int x=0;x<sizeOf(cntV);x++){
				try {
					tempFp = new Fp(cntV[x]);
					out.push_back(tempFp);
	 			} catch (Exception e) {}
			}
			delete tempFp

			//Return the focus points
			return out;
		}

		//Classifies squares and selects the four most likely to be corners
		vector<Fp> getCorners(vector<Fp> focusPoints){
			list<Fp> fpList = list<Fp>(focusPoints);
			list<Fp> fours = fpList.remove_if([](Fp z){return z.shape == 4;});
			double angles (Point x) {
				vector<double> out;
				for (Fp y : fours) for (Fp z : fours) if (x != y && y != z && x != z) {out.push_back(angle(x,y,z));}
				return out;
			}

			//Classify corners as having 2 right angles
			list<Fp> out;
			for (f : fours)
				if (sizeOf(angles(f.contours).remove_if([](double z){return math.abs(z-90.0)<angleTol;}))>=2 && !out.contains(f))
					out.append(f);

			//Return their centroids
			if (sizeOf(out)!=4) {throw Exception e;}
			return vector<Fp>(out);
		}

		//Sort edges by distance.
	    vector<Fp> sortCorners(vector<Fp> corners){
			Point cent = centroid(corners); list<double> polar; int n; vector<Fp> out;
			for (Fp z : corners) {polar.push_back(angle(z.center,cent));} //Calculate all the angles from the centroid, maintaining index
			//Sort "corners" by the order of sorted "polar"
			vector<Point> sorted = polar.sort();
			for (int i = 0; i<sizeOf(polar); i++) {
				n = polar.index(sorted[i]);
				out.push_back(corners[n]); //Return sorted corners
			}

			return out;
		}

	    // ------------ Image Manipulation --------------
	    Mat importFilter(Mat img){
	        //Declarations
	        Mat gray,edges;

	        //Convert to gray if not already
	        try{cvtColor(img,gray,COLOR_RGB2GRAY);}
	        catch(Exception e){
	            gray = img.copy();
	        }

	        //Return Canny Edge Detection
	        Canny(gray,edges,etol1,etol2,eSize);
	        return edges
	    }

	    Mat outputFilter(Mat img){
			Mat gray, out;
			cvtColor(img, gray, COLOR_RGB2GRAY);
			adaptiveThreshold(gray, out, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, wSize, C);
			return out;
		}

	    Mat cropImage(Mat img, int R){
			int sizeX = img.cols; int sizeY = img.rows;
			return img[R:sizeY-R][R:sizeX-R];
		}

	    Mat fixPerspective(Mat img, vector<cnt> border, Fp ref) throws Exception {
			//Check initial factors
			if (sizeOf(border)!=4) {throw Exception e;}

			//Declare variables
			cnt t1, tr, br, b1;
			Mat M, out;

			//Rotate the array until the reference is first
			while (centroid(border[0]) != ref.center)
				border = rotateList(border,1);

			//Copied from http://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
			tl = border[0]; tr = border[1]; br = border[2]; bl = border[3];

			// compute the width of the new image, which will be the
			// maximum distance between bottom-right and bottom-left
			// x-coordiates or the top-right and top-left x-coordinates
			auto widthA = math.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2));
			auto widthB = math.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2));
			auto maxWidth = max(int(widthA), int(widthB));

			// compute the height of the new image, which will be the
		 	// maximum distance between the top-right and bottom-right
			// y-coordinates or the top-left and bottom-left y-coordinates
			auto heightA = math.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2));
			auto heightB = math.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2));
			auto maxHeight = max(int(heightA), int(heightB));

			// now that we have the dimensions of the new image, construct
			// the set of destination points to obtain a "birds eye view",
			// (i.e. top-down view) of the image, again specifying points
			// in the top-left, top-right, bottom-right, and bottom-left
			// order
			auto dst = Rect(Point(0, 0),
							Point(maxWidth - 1, 0),
							Point(maxWidth - 1, maxHeight - 1),
							Point(0, maxHeight - 1));

			//Return Perspective Transform
			M = getPerspectiveTransform(border, dst);
			warpPerspective(img, out, M, (maxWidth, maxHeight));
			return out;
		}

	    // -------------- Geometric ------------------
	    bool allSameLength(cnt poly){
			vector<vector<Point>> pairs; vector<double> lengths, error; vector<bool> test; int i;

			//Get a list of all lines in poly
			pairs.push_back({poly[poly.size()-1],poly[0]}) 											//Add the first pair to the list
			for (i = 1; i < sizeOf(poly); i++) {pairs.push_back({poly[i-1],poly[i]});} 				//Add the rest
			for (i = 0; i < sizeOf(poly); i++) {lengths.push_back(dist(pairs[i][0],pairs[i][1]));} 	//Get a list of the length of all pairs in poly
			double = mean(lengths);
			for (i = 0; i < sizeOf(poly); i++) {error.push_back(abs(lengths[i]-mean));} 			//Get the error from the mean of each length
			for (i = 0; i < sizeOf(poly); i++) {test.push_back(error[i] < distTol);}				//Check if the error is within tolerance
			return find(test.begin(), test.end(), false)!=v.end();									//Test and return to see if there is a false within the test vector
		}

		cnt rotateCnt(cnt contour, int n) {
			cnt AB = cnt().reserve(contour.size());
			AB.insert( AB.end(), contour[n:].begin(), contour[n:].end() );
			AB.insert( AB.end(), contour[:n].begin(), contour[:n].end() );
		    return AB;
		}
		cnt rotateCnt(cnt contour) {return rotateCnt(contour,1);}

		Point centroid(cnt contour) {
			Point sum = Point(0,0);
			for (Point p : contour)
				sum += p;
			return sum / sizeOf(contour);
		}
	    Point centroid(vector<cnt> contours) {
			Point sum = Point(0,0);
			for (cnt c : contours)
				sum += centroid(c);
			return sum / sizeOf(contours);
		}
	    Point centroid(Cnts contours) {return centroid(contours.contours);}

	    double dist(Point a, Point b){
			return sqrt((a[0]-b[0])**2+(a[1]-b[1])**2);
		}

		double angle(Point origin, Point a){
			Point v = a - origin;
			return atan2(v[0],v[1]) * 180 / PI;
		}

		double angle(Point origin, Point c2, Point c3) {
			Point *a1 = origin; Point *a2 = c2; Point *a3 = origin; Point *a4 = c3;
			return acos(dot((*a2-*a1),(*a4-*a3))/(norm(*a2-*a1)*norm(*a4-*a3)))) * 180 / PI;
		}

		Fp getRef(vector<Fp> fps) {
			Fp maxFp; int max = 0;
			for (fp : fps) {
				if (fp.depth > max) {
					maxFp = fp;
					max = fp.depth;
				}
			}
			return maxFp;
		}

		// -------------- Main Methods ----------------------
	    Mat process(Mat img){
			//Intial Processing
			Cnts polys = findPolys(img,polyTol)
			vector<Fp> fps = findFocusPoints(polys)

			try {
				vector<Fp> corners = getCorners(fps,angleTol);
				vector<Fp> sort = sortCorners(corners);
				Fp ref = getRef(corners);
				Mat warp = fixPerspective(img,sort,ref,aspectRatio);
				Mat crop = cropImage(warp,R*warp.cols);
				Mat out = outputFilter(crop,wSize,C);
			}
			catch(...) {out = img;}

			return out;
		}

		const Mat img;
		const int angleTol, distTol, polyTol, wSize, C, etol1, etol2, eSize, R;
		const double aspectRatio;

	public:
	    Mat IMGProcessor(Mat img, int angleTol, int distTol, int polyTol, int wSize, int C, double aspectRatio, int etol1, int etol2, int eSize, int R) throws Exception {
			//Global variables
			this.img = img; this.angleTol = angleTol; this.distTol = distTol; this.polyTol = polyTol; this.wSize = wSize; this.C = C;
			this.aspectRatio = aspectRatio; this.etol1 = etol1; this.etol2 = etol2; this.eSize = eSize; this.R = R;

			return process(img);
		}

		Mat IMGProcessor(Mat img) throws Exception {return IMGProcessor(img,10,5,5,11,2,8.5/11.0,100,200,3,.04);}
}
<|endoftext|>


<commit_before>//
//  params.cpp
//  ndnrtc
//
//  Copyright 2013 Regents of the University of California
//  For licensing details see the LICENSE file.
//
//  Author:  Peter Gusev
//

#include <string.h>
#include "params.h"

using namespace ndnrtc;
using namespace ndnlog;

int _ParamsStruct::validateVideoParams(const struct _ParamsStruct &params,
                                       struct _ParamsStruct &validatedResult)
{
    // check critical values
    if (params.loggingLevel != NdnLoggerDetailLevelNone &&
        (params.logFile == NULL ||
         strcmp(params.logFile,"") == 0))
        return RESULT_ERR;

    if (params.host == NULL ||
        strcmp(params.host, "") == 0)
        return RESULT_ERR;

    if (params.producerId == NULL ||
        strcmp(params.producerId, "") == 0)
        return RESULT_ERR;

    if (params.streamName == NULL ||
        strcmp(params.streamName, "") == 0)
        return RESULT_ERR;

    if (params.streamThread == NULL ||
        strcmp(params.streamThread, "") == 0)
        return RESULT_ERR;

    if (params.ndnHub == NULL ||
        strcmp(params.ndnHub, "") == 0)
        return RESULT_ERR;

    int res = RESULT_OK;
    ParamsStruct validated = DefaultParams;

    // check other values
    validated.loggingLevel = params.loggingLevel;
    validated.logFile = params.logFile;

    validated.captureDeviceId = params.captureDeviceId;
    validated.captureWidth = ParamsStruct::validate(params.captureWidth,
                                                    MinWidth, MaxWidth, res,
                                                    DefaultParams.captureWidth);
    validated.captureHeight = ParamsStruct::validate(params.captureHeight,
                                                     MinHeight, MaxHeight, res,
                                                     DefaultParams.captureHeight);
    validated.captureFramerate = ParamsStruct::validate(params.captureFramerate,
                                                        MinFrameRate, MaxFrameRate, res,
                                                        DefaultParams.captureFramerate);

    validated.renderWidth = ParamsStruct::validate(params.renderWidth,
                                                   MinWidth, MaxWidth, res,
                                                   DefaultParams.renderWidth);
    validated.renderHeight = ParamsStruct::validate(params.renderHeight,
                                                    MinHeight, MaxHeight, res,
                                                    DefaultParams.renderHeight);

    validated.codecFrameRate = ParamsStruct::validate(params.codecFrameRate,
                                                      MinFrameRate, MaxFrameRate, res,
                                                      DefaultParams.codecFrameRate);
    validated.startBitrate = ParamsStruct::validate(params.startBitrate,
                                                    MinStartBitrate, MaxStartBitrate, res,
                                                    DefaultParams.startBitrate);
    validated.maxBitrate = ParamsStruct::validate(params.maxBitrate,
                                                  MinStartBitrate, MaxBitrate, res,
                                                  DefaultParams.maxBitrate);
    validated.encodeWidth = ParamsStruct::validate(params.encodeWidth,
                                                   MinWidth, MaxWidth, res,
                                                   DefaultParams.encodeWidth);
    validated.encodeHeight = ParamsStruct::validate(params.encodeHeight,
                                                    MinHeight, MaxHeight, res,
                                                    DefaultParams.encodeHeight);
    validated.dropFramesOn = params.dropFramesOn;

    validated.host = params.host;
    validated.portNum = ParamsStruct::validateLE(params.portNum, MaxPortNum, res,
                                                 DefaultParams.portNum);

    validated.producerId = params.producerId;
    validated.streamName = params.streamName;
    validated.streamThread = params.streamThread;
    validated.ndnHub = params.ndnHub;

    validated.segmentSize = ParamsStruct::validate(params.segmentSize,
                                                   MinSegmentSize, MaxSegmentSize, res,
                                                   DefaultParams.segmentSize);
    validated.freshness = params.freshness;
    validated.producerRate = ParamsStruct::validate(params.producerRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParams.producerRate);
    validated.playbackRate = ParamsStruct::validate(params.playbackRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParams.playbackRate);
    validated.interestTimeout = params.interestTimeout;
    validated.bufferSize = ParamsStruct::validate(params.bufferSize,
                                                  MinBufferSize, MaxBufferSize, res,
                                                  DefaultParams.bufferSize);
    validated.jitterSize = ParamsStruct::validate(params.jitterSize,
                                                  MinJitterSize, INT_MAX, res,
                                                  DefaultParams.jitterSize);
    validated.slotSize = ParamsStruct::validate(params.slotSize,
                                                MinSlotSize, MaxSlotSize, res,
                                                DefaultParams.slotSize);
    if (validated.slotSize < validated.segmentSize)
    {
        validated.slotSize = validated.segmentSize;
        res = RESULT_WARN;
    }

    validatedResult = validated;

    return res;
}

int _ParamsStruct::validateAudioParams(const struct _ParamsStruct &params,
                                       struct _ParamsStruct &validatedResult)
{
    // check critical values
    if (params.host == NULL ||
        strcmp(params.host, "") == 0)
        return RESULT_ERR;

    if (params.producerId == NULL ||
        strcmp(params.producerId, "") == 0)
        return RESULT_ERR;

    if (params.streamName == NULL ||
        strcmp(params.streamName, "") == 0)
        return RESULT_ERR;

    if (params.streamThread == NULL ||
        strcmp(params.streamThread, "") == 0)
        return RESULT_ERR;

    if (params.ndnHub == NULL ||
        strcmp(params.ndnHub, "") == 0)
        return RESULT_ERR;

    // check other values
    int res = RESULT_OK;
    ParamsStruct validated = DefaultParamsAudio;

    validated.host = params.host;
    validated.portNum = ParamsStruct::validateLE(params.portNum, MaxPortNum,
                                                 res, DefaultParamsAudio.portNum);

    validated.producerId = params.producerId;
    validated.streamName = params.streamName;
    validated.streamThread = params.streamThread;
    validated.ndnHub = params.ndnHub;

    validated.segmentSize = ParamsStruct::validate(params.segmentSize,
                                                   MinSegmentSize, MaxSegmentSize, res,
                                                   DefaultParamsAudio.segmentSize);
    validated.freshness = params.freshness;
    validated.producerRate = ParamsStruct::validate(params.producerRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParamsAudio.producerRate);
    validated.playbackRate = ParamsStruct::validate(params.playbackRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParamsAudio.playbackRate);
    validated.interestTimeout = params.interestTimeout;
    validated.bufferSize = ParamsStruct::validate(params.bufferSize,
                                                  MinBufferSize, MaxBufferSize, res,
                                                  DefaultParamsAudio.bufferSize);
    validated.jitterSize = ParamsStruct::validate(params.jitterSize,
                                                  MinJitterSize, INT_MAX, res,
                                                  DefaultParams.jitterSize);

    validated.slotSize = ParamsStruct::validate(params.slotSize, MinSlotSize,
                                                MaxSlotSize, res,
                                                DefaultParamsAudio.slotSize);

    if (validated.slotSize < validated.segmentSize)
    {
        validated.slotSize = validated.segmentSize;
        res = RESULT_WARN;
    }

    validatedResult = validated;

    return res;
}
<commit_msg>[untracked] parameters load fixes<commit_after>//
//  params.cpp
//  ndnrtc
//
//  Copyright 2013 Regents of the University of California
//  For licensing details see the LICENSE file.
//
//  Author:  Peter Gusev
//

#include <string.h>
#include "params.h"

using namespace ndnrtc;
using namespace ndnlog;

int _ParamsStruct::validateVideoParams(const struct _ParamsStruct &params,
                                       struct _ParamsStruct &validatedResult)
{
    // check critical values
    if (params.loggingLevel != NdnLoggerDetailLevelNone &&
        (params.logFile == NULL ||
         strcmp(params.logFile,"") == 0))
        return RESULT_ERR;

    if (params.host == NULL ||
        strcmp(params.host, "") == 0)
        return RESULT_ERR;

    if (params.producerId == NULL ||
        strcmp(params.producerId, "") == 0)
        return RESULT_ERR;

    if (params.streamName == NULL ||
        strcmp(params.streamName, "") == 0)
        return RESULT_ERR;

    if (params.streamThread == NULL ||
        strcmp(params.streamThread, "") == 0)
        return RESULT_ERR;

    if (params.ndnHub == NULL ||
        strcmp(params.ndnHub, "") == 0)
        return RESULT_ERR;

    int res = RESULT_OK;
    ParamsStruct validated = DefaultParams;

    // check other values
    validated.loggingLevel = params.loggingLevel;
    validated.logFile = params.logFile;
    validated.useTlv = params.useTlv;
    validated.useRtx = params.useRtx;

    validated.captureDeviceId = params.captureDeviceId;
    validated.captureWidth = ParamsStruct::validate(params.captureWidth,
                                                    MinWidth, MaxWidth, res,
                                                    DefaultParams.captureWidth);
    validated.captureHeight = ParamsStruct::validate(params.captureHeight,
                                                     MinHeight, MaxHeight, res,
                                                     DefaultParams.captureHeight);
    validated.captureFramerate = ParamsStruct::validate(params.captureFramerate,
                                                        MinFrameRate, MaxFrameRate, res,
                                                        DefaultParams.captureFramerate);

    validated.renderWidth = ParamsStruct::validate(params.renderWidth,
                                                   MinWidth, MaxWidth, res,
                                                   DefaultParams.renderWidth);
    validated.renderHeight = ParamsStruct::validate(params.renderHeight,
                                                    MinHeight, MaxHeight, res,
                                                    DefaultParams.renderHeight);

    validated.codecFrameRate = ParamsStruct::validate(params.codecFrameRate,
                                                      MinFrameRate, MaxFrameRate, res,
                                                      DefaultParams.codecFrameRate);
    validated.startBitrate = ParamsStruct::validate(params.startBitrate,
                                                    MinStartBitrate, MaxStartBitrate, res,
                                                    DefaultParams.startBitrate);
    validated.maxBitrate = ParamsStruct::validate(params.maxBitrate,
                                                  MinStartBitrate, MaxBitrate, res,
                                                  DefaultParams.maxBitrate);
    validated.encodeWidth = ParamsStruct::validate(params.encodeWidth,
                                                   MinWidth, MaxWidth, res,
                                                   DefaultParams.encodeWidth);
    validated.encodeHeight = ParamsStruct::validate(params.encodeHeight,
                                                    MinHeight, MaxHeight, res,
                                                    DefaultParams.encodeHeight);
    validated.dropFramesOn = params.dropFramesOn;

    validated.host = params.host;
    validated.portNum = ParamsStruct::validateLE(params.portNum, MaxPortNum, res,
                                                 DefaultParams.portNum);

    validated.producerId = params.producerId;
    validated.streamName = params.streamName;
    validated.streamThread = params.streamThread;
    validated.ndnHub = params.ndnHub;

    validated.segmentSize = ParamsStruct::validate(params.segmentSize,
                                                   MinSegmentSize, MaxSegmentSize, res,
                                                   DefaultParams.segmentSize);
    validated.freshness = params.freshness;
    validated.producerRate = ParamsStruct::validate(params.producerRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParams.producerRate);
    validated.playbackRate = ParamsStruct::validate(params.playbackRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParams.playbackRate);
    validated.interestTimeout = params.interestTimeout;
    validated.bufferSize = ParamsStruct::validate(params.bufferSize,
                                                  MinBufferSize, MaxBufferSize, res,
                                                  DefaultParams.bufferSize);
    validated.jitterSize = ParamsStruct::validate(params.jitterSize,
                                                  MinJitterSize, INT_MAX, res,
                                                  DefaultParams.jitterSize);
    validated.slotSize = ParamsStruct::validate(params.slotSize,
                                                MinSlotSize, MaxSlotSize, res,
                                                DefaultParams.slotSize);
    if (validated.slotSize < validated.segmentSize)
    {
        validated.slotSize = validated.segmentSize;
        res = RESULT_WARN;
    }

    validatedResult = validated;

    return res;
}

int _ParamsStruct::validateAudioParams(const struct _ParamsStruct &params,
                                       struct _ParamsStruct &validatedResult)
{
    // check critical values
    if (params.host == NULL ||
        strcmp(params.host, "") == 0)
        return RESULT_ERR;

    if (params.producerId == NULL ||
        strcmp(params.producerId, "") == 0)
        return RESULT_ERR;

    if (params.streamName == NULL ||
        strcmp(params.streamName, "") == 0)
        return RESULT_ERR;

    if (params.streamThread == NULL ||
        strcmp(params.streamThread, "") == 0)
        return RESULT_ERR;

    if (params.ndnHub == NULL ||
        strcmp(params.ndnHub, "") == 0)
        return RESULT_ERR;

    // check other values
    int res = RESULT_OK;
    ParamsStruct validated = DefaultParamsAudio;

    validated.loggingLevel = params.loggingLevel;
    validated.logFile = params.logFile;
    validated.useTlv = params.useTlv;
    validated.useRtx = params.useRtx;

    validated.host = params.host;
    validated.portNum = ParamsStruct::validateLE(params.portNum, MaxPortNum,
                                                 res, DefaultParamsAudio.portNum);

    validated.producerId = params.producerId;
    validated.streamName = params.streamName;
    validated.streamThread = params.streamThread;
    validated.ndnHub = params.ndnHub;

    validated.segmentSize = ParamsStruct::validate(params.segmentSize,
                                                   MinSegmentSize, MaxSegmentSize, res,
                                                   DefaultParamsAudio.segmentSize);
    validated.freshness = params.freshness;
    validated.producerRate = ParamsStruct::validate(params.producerRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParamsAudio.producerRate);
    validated.playbackRate = ParamsStruct::validate(params.playbackRate,
                                                    MinFrameRate, MaxFrameRate, res,
                                                    DefaultParamsAudio.playbackRate);
    validated.interestTimeout = params.interestTimeout;
    validated.bufferSize = ParamsStruct::validate(params.bufferSize,
                                                  MinBufferSize, MaxBufferSize, res,
                                                  DefaultParamsAudio.bufferSize);
    validated.jitterSize = ParamsStruct::validate(params.jitterSize,
                                                  MinJitterSize, INT_MAX, res,
                                                  DefaultParams.jitterSize);

    validated.slotSize = ParamsStruct::validate(params.slotSize, MinSlotSize,
                                                MaxSlotSize, res,
                                                DefaultParamsAudio.slotSize);

    if (validated.slotSize < validated.segmentSize)
    {
        validated.slotSize = validated.segmentSize;
        res = RESULT_WARN;
    }

    validatedResult = validated;

    return res;
}
<|endoftext|>


<commit_before>// csafmt_headline.cpp                                                -*-C++-*-

#include <clang/Basic/Diagnostic.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <csabase_analyser.h>
#include <csabase_binder.h>
#include <csabase_diagnostic_builder.h>
#include <csabase_filenames.h>
#include <csabase_ppobserver.h>
#include <csabase_registercheck.h>
#include <csabase_util.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/MemoryBuffer.h>
#include <stddef.h>
#include <utils/event.hpp>
#include <utils/function.hpp>
#include <string>
#include <utility>

namespace csabase { class Visitor; }

using namespace csabase;
using namespace clang;

// ----------------------------------------------------------------------------

static std::string const check_name("headline");

// ----------------------------------------------------------------------------

static void open_file(Analyser& analyser,
                      SourceLocation where,
                      const std::string&,
                      const std::string& name)
{
    FileName fn(name);
    std::string filename = fn.name();
    if (analyser.is_component_header(filename) ||
        name == analyser.toplevel()) {
        const SourceManager &m = analyser.manager();
        llvm::StringRef buf = m.getBuffer(m.getFileID(where))->getBuffer();
        buf = buf.substr(0, buf.find('\n')).rtrim();
        std::string expectcpp("// " + filename);
        expectcpp.resize(70, ' ');
        expectcpp += "-*-C++-*-";
        std::string expectc("/* " + filename);
        expectc.resize(69, ' ');
        expectc += "-*-C-*- */";

        if (   !buf.equals(expectcpp)
            && !buf.equals(expectc)
            && buf.find("GENERATED") == buf.npos) {
            std::pair<size_t, size_t> mcpp = mid_mismatch(buf, expectcpp);
            std::pair<size_t, size_t> mc = mid_mismatch(buf, expectc);
            std::pair<size_t, size_t> m;
            std::string expect;

            if (mcpp.first >= mc.first || mcpp.second >= mc.second) {
                m = mcpp;
                expect = expectcpp;
            } else {
                m = mc;
                expect = expectc;
            }
            analyser.report(where.getLocWithOffset(m.first),
                            check_name, "HL01",
                            "File headline incorrect", true);
            analyser.report(where.getLocWithOffset(m.first),
                            check_name, "HL01",
                            "Correct format is\n%0",
                            true, DiagnosticsEngine::Note)
                << expect;
            analyser.rewriter().ReplaceText(
                where.getLocWithOffset(m.first),
                buf.size() - m.first - m.second,
                llvm::StringRef(expect)
                    .drop_front(m.first)
                    .drop_back(m.second));
        }
    }
}

// ----------------------------------------------------------------------------

static void subscribe(Analyser& analyser, Visitor&, PPObserver& observer)
{
    observer.onOpenFile += bind<Analyser&>(analyser, open_file);
}

// ----------------------------------------------------------------------------

static RegisterCheck register_observer(check_name, &subscribe);

// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Insert headline when necessary.<commit_after>// csafmt_headline.cpp                                                -*-C++-*-

#include <clang/Basic/Diagnostic.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <csabase_analyser.h>
#include <csabase_binder.h>
#include <csabase_diagnostic_builder.h>
#include <csabase_filenames.h>
#include <csabase_ppobserver.h>
#include <csabase_registercheck.h>
#include <csabase_util.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/MemoryBuffer.h>
#include <stddef.h>
#include <utils/event.hpp>
#include <utils/function.hpp>
#include <string>
#include <utility>

namespace csabase { class Visitor; }

using namespace csabase;
using namespace clang;

// ----------------------------------------------------------------------------

static std::string const check_name("headline");

// ----------------------------------------------------------------------------

static void open_file(Analyser& analyser,
                      SourceLocation where,
                      const std::string&,
                      const std::string& name)
{
    FileName fn(name);
    std::string filename = fn.name();
    if (analyser.is_component_header(filename) ||
        name == analyser.toplevel()) {
        const SourceManager &m = analyser.manager();
        llvm::StringRef buf = m.getBuffer(m.getFileID(where))->getBuffer();
        buf = buf.substr(0, buf.find('\n')).rtrim();
        std::string expectcpp("// " + filename);
        expectcpp.resize(70, ' ');
        expectcpp += "-*-C++-*-";
        std::string expectc("/* " + filename);
        expectc.resize(69, ' ');
        expectc += "-*-C-*- */";

        if (   !buf.equals(expectcpp)
            && !buf.equals(expectc)
            && buf.find("GENERATED") == buf.npos) {
            std::pair<size_t, size_t> mcpp = mid_mismatch(buf, expectcpp);
            std::pair<size_t, size_t> mc = mid_mismatch(buf, expectc);
            std::pair<size_t, size_t> m;
            std::string expect;

            if (mcpp.first >= mc.first || mcpp.second >= mc.second) {
                m = mcpp;
                expect = expectcpp;
            } else {
                m = mc;
                expect = expectc;
            }
            analyser.report(where.getLocWithOffset(m.first),
                            check_name, "HL01",
                            "File headline incorrect", true);
            analyser.report(where.getLocWithOffset(m.first),
                            check_name, "HL01",
                            "Correct format is\n%0",
                            true, DiagnosticsEngine::Note)
                << expect;
            if (m.first == 0) {
                analyser.rewriter().InsertText(
                    where.getLocWithOffset(m.first),
                    expect + "\n");
            } else {
                analyser.rewriter().ReplaceText(
                    where.getLocWithOffset(m.first),
                    buf.size() - m.first - m.second,
                    llvm::StringRef(expect)
                        .drop_front(m.first)
                        .drop_back(m.second));
            }
        }
    }
}

// ----------------------------------------------------------------------------

static void subscribe(Analyser& analyser, Visitor&, PPObserver& observer)
{
    observer.onOpenFile += bind<Analyser&>(analyser, open_file);
}

// ----------------------------------------------------------------------------

static RegisterCheck register_observer(check_name, &subscribe);

// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>


<commit_before>#ifndef CLOCK_UNORDERED_MAP
#define CLOCK_UNORDERED_MAP
#include<functional>	//equal_to, hash
#include<memory>	//allocator
#include<mutex>
#include<shared_mutex>
#include<tuple>
#include<unordered_map>
#include<utility>	//forward, move

namespace nThread
{
	template<class Key,class T,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Alloc=std::allocator<std::pair<const Key,T>>>
	class CLock_unordered_map
	{
	public:
		using key_type=Key;
		using mapped_type=T;
	private:
		std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc> map_;
		mutable std::shared_mutex mut_;
		inline bool find_(const key_type &key) const
		{
			return map_.find(key)!=map_.end();
		}
		template<class Key_typeFwdRef>
		mapped_type& subscript_(Key_typeFwdRef &&key)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			return map_[std::forward<decltype(key)>(key)];
		}
		template<class Key_typeFwdRef,class ... Args>
		bool try_emplace_(Key_typeFwdRef &&key,Args &&...args)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			if(find_(key))
				return false;
			map_.emplace(std::piecewise_construct,std::forward_as_tuple(std::forward<decltype(key)>(key)),std::forward_as_tuple(std::forward<decltype(args)>(args)...));
			return true;
		}
		template<class Key_typeFwdRef,class Gen>
		bool emplace_if_not_exist_(Key_typeFwdRef &&key,Gen &&gen)
		{
			if(find_(key))
				return false;
			map_.emplace(std::piecewise_construct,std::forward_as_tuple(std::forward<decltype(key)>(key)),std::forward_as_tuple(std::forward<decltype(gen)>(gen)()));
			return true;
		}
		template<class Key_typeFwdRef,class Gen>
		bool try_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			return emplace_if_not_exist_(std::forward<decltype(key)>(key),std::forward<decltype(gen)>(gen));
		}
		template<class Key_typeFwdRef,class Gen>
		int try_lock_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen)
		{
			std::unique_lock<std::shared_mutex> lock{mut_,std::defer_lock};
			if(lock.try_lock())
				return emplace_if_not_exist_(std::forward<decltype(key)>(key),std::forward<decltype(gen)>(gen));
			return -1;
		}
	public:
		CLock_unordered_map()=default;
		CLock_unordered_map(const CLock_unordered_map &)=delete;
		mapped_type& at(const key_type &key)
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.at(key);
		}
		const mapped_type& at(const key_type &key) const
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.at(key);
		}
		bool find(const key_type &key) const
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return find_(key);
		}
		template<class ... Args>
		bool emplace(Args &&...args)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			return map_.emplace(std::forward<decltype(args)>(args)...).second;
		}
		mapped_type& read(const key_type &key)
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.find(key)->second;
		}
		const mapped_type& read(const key_type &key) const
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.find(key)->second;
		}
		template<class ... Args>
		inline bool try_emplace(const key_type &key,Args &&...args)
		{
			return try_emplace_(key,std::forward<decltype(args)>(args)...);
		}
		template<class ... Args>
		inline bool try_emplace(key_type &&key,Args &&...args)
		{
			return try_emplace_(std::move(key),std::forward<decltype(args)>(args)...);
		}
		template<class Gen>
		inline bool try_emplace_gen(const key_type &key,Gen &&gen)
		{
			return try_emplace_gen_(key,std::forward<decltype(gen)>(gen));
		}
		template<class Gen>
		inline bool try_emplace_gen(key_type &&key,Gen &&gen)
		{
			return try_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen));
		}
		template<class Gen>
		inline int try_lock_emplace_gen(const key_type &key,Gen &&gen)
		{
			return try_lock_emplace_gen_(key,std::forward<decltype(gen)>(gen));
		}
		template<class Gen>
		inline int try_lock_emplace_gen(key_type &&key,Gen &&gen)
		{
			return try_lock_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen));
		}
		CLock_unordered_map& operator=(const CLock_unordered_map &)=delete;
		inline mapped_type& operator[](const key_type &key)
		{
			return subscript_(key);
		}
		inline mapped_type& operator[](key_type &&key)
		{
			return subscript_(std::move(key));
		}
	};
}

#endif
<commit_msg>add unordered_map<commit_after>#ifndef CLOCK_UNORDERED_MAP
#define CLOCK_UNORDERED_MAP
#include<functional>	//equal_to, hash
#include<memory>	//allocator
#include<mutex>
#include<shared_mutex>
#include<tuple>
#include<unordered_map>
#include<utility>	//forward, move

namespace nThread
{
	template<class Key,class T,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Alloc=std::allocator<std::pair<const Key,T>>>
	class CLock_unordered_map
	{
	public:
		using key_type=Key;
		using mapped_type=T;
	private:
		std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc> map_;
		mutable std::shared_mutex mut_;
		inline bool find_(const key_type &key) const
		{
			return map_.find(key)!=map_.end();
		}
		template<class Key_typeFwdRef>
		mapped_type& subscript_(Key_typeFwdRef &&key)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			return map_[std::forward<decltype(key)>(key)];
		}
		template<class Key_typeFwdRef,class ... Args>
		bool try_emplace_(Key_typeFwdRef &&key,Args &&...args)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			if(find_(key))
				return false;
			map_.emplace(std::piecewise_construct,std::forward_as_tuple(std::forward<decltype(key)>(key)),std::forward_as_tuple(std::forward<decltype(args)>(args)...));
			return true;
		}
		template<class Key_typeFwdRef,class Gen>
		bool emplace_if_not_exist_(Key_typeFwdRef &&key,Gen &&gen)
		{
			if(find_(key))
				return false;
			map_.emplace(std::piecewise_construct,std::forward_as_tuple(std::forward<decltype(key)>(key)),std::forward_as_tuple(std::forward<decltype(gen)>(gen)()));
			return true;
		}
		template<class Key_typeFwdRef,class Gen>
		bool try_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			return emplace_if_not_exist_(std::forward<decltype(key)>(key),std::forward<decltype(gen)>(gen));
		}
		template<class Key_typeFwdRef,class Gen>
		int try_lock_emplace_gen_(Key_typeFwdRef &&key,Gen &&gen)
		{
			std::unique_lock<std::shared_mutex> lock{mut_,std::defer_lock};
			if(lock.try_lock())
				return emplace_if_not_exist_(std::forward<decltype(key)>(key),std::forward<decltype(gen)>(gen));
			return -1;
		}
	public:
		CLock_unordered_map()=default;
		CLock_unordered_map(const CLock_unordered_map &)=delete;
		mapped_type& at(const key_type &key)
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.at(key);
		}
		const mapped_type& at(const key_type &key) const
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.at(key);
		}
		bool find(const key_type &key) const
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return find_(key);
		}
		template<class ... Args>
		bool emplace(Args &&...args)
		{
			std::lock_guard<std::shared_mutex> lock{mut_};
			return map_.emplace(std::forward<decltype(args)>(args)...).second;
		}
		mapped_type& read(const key_type &key)
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.find(key)->second;
		}
		const mapped_type& read(const key_type &key) const
		{
			std::shared_lock<std::shared_mutex> lock{mut_};
			return map_.find(key)->second;
		}
		template<class ... Args>
		inline bool try_emplace(const key_type &key,Args &&...args)
		{
			return try_emplace_(key,std::forward<decltype(args)>(args)...);
		}
		template<class ... Args>
		inline bool try_emplace(key_type &&key,Args &&...args)
		{
			return try_emplace_(std::move(key),std::forward<decltype(args)>(args)...);
		}
		template<class Gen>
		inline bool try_emplace_gen(const key_type &key,Gen &&gen)
		{
			return try_emplace_gen_(key,std::forward<decltype(gen)>(gen));
		}
		template<class Gen>
		inline bool try_emplace_gen(key_type &&key,Gen &&gen)
		{
			return try_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen));
		}
		template<class Gen>
		inline int try_lock_emplace_gen(const key_type &key,Gen &&gen)
		{
			return try_lock_emplace_gen_(key,std::forward<decltype(gen)>(gen));
		}
		template<class Gen>
		inline int try_lock_emplace_gen(key_type &&key,Gen &&gen)
		{
			return try_lock_emplace_gen_(std::move(key),std::forward<decltype(gen)>(gen));
		}
		inline std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc>& unordered_map() noexcept
		{
			return map_;
		}
		inline const std::unordered_map<key_type,mapped_type,Hash,KeyEqual,Alloc>& unordered_map() const noexcept
		{
			return map_;
		}
		CLock_unordered_map& operator=(const CLock_unordered_map &)=delete;
		inline mapped_type& operator[](const key_type &key)
		{
			return subscript_(key);
		}
		inline mapped_type& operator[](key_type &&key)
		{
			return subscript_(std::move(key));
		}
	};
}

#endif
<|endoftext|>


<commit_before>#ifndef __RANK_FILTER__
#define __RANK_FILTER__

#include <list>
#include <set>
#include <cmath>
#include <cassert>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>

#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>

template<unsigned int N,
        class T1, class S1,
        class T2, class S2>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = N - 1,
        typename std::enable_if<(N == 1)>::type *enabled = 0)
{
    // Will ignore boundaries initially.
    // Then will try adding reflection.

    // Rank must be in the range 0 to 1
    assert((0 <= rank) && (rank <= 1));

    const int rank_pos = round(rank * (2 * half_length));

    // The position of the
    typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
    std::multiset<T1> sorted_window;
    std::list< typename std::multiset<T1>::iterator > window_iters;

    // Get the initial sorted window.
    // Include the reflection.
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }

    typename std::multiset<T1>::iterator rank_point = sorted_window.begin();

    for (int i = 0; i < rank_pos; i++)
    {
        rank_point++;
    }

    while ( window_begin < src.size() )
    {
        dest[window_begin] = *rank_point;

        typename std::multiset<T1>::iterator prev_iter(window_iters.front());
        T1 prev_value = *prev_iter;
        window_iters.pop_front();

        window_begin++;

        T1 next_value;
        if ( window_begin < (src.size() - half_length) )
        {
            next_value = src[window_begin + half_length];
        }
        else
        {
            next_value = src[2 * src.size() - (window_begin + half_length + 2)];
        }

        if ( ( *rank_point < *prev_iter ) && ( *rank_point <= next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));
        }
        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point > next_value ) )
        {
            if ( rank_point == prev_iter )
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point--;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));
            }
        }
        else if ( ( *rank_point < *prev_iter ) && ( *rank_point > next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));

            rank_point--;
        }
        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point <= next_value ) )
        {
            if (rank_point == prev_iter)
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point++;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));

                rank_point++;
            }
        }
    }
}

template<unsigned int N,
        class T1, class S1,
        class T2, class S2>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = N - 1,
        typename std::enable_if<(N > 1)>::type *enabled = 0)
{
    typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;

    for (unsigned int i = 0; i < N; i++)
    {
        transposed_axes[i] = i;
    }

    std::swap(transposed_axes[N - 1], transposed_axes[axis]);

    vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));

    vigra::MultiArrayView<N, T1, S1> dest_transposed_view(dest.transpose(transposed_axes));

    typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
    pos = 0;

    bool done = false;

    while (!done)
    {
        lineRankOrderFilter(src_transposed.bindInner(pos), dest_transposed_view.bindInner(pos), half_length, rank);

        bool carry = true;
        for (unsigned int i = 0; ( carry && (i < N) ); i++)
        {
            if ( (++pos[N - (i + 1)]) < src.shape()[N - (i + 1)])
            {
                carry = false;
            }
            else
            {
                pos[N - (i + 1)] = 0;
                carry = true;
            }
        }

        done = !carry;
    }
}

#endif //__RANK_FILTER__
<commit_msg>rank_filter.hxx: Added the function lineRankOrderFilter to call the right version of lineRankOrderFilterND.<commit_after>#ifndef __RANK_FILTER__
#define __RANK_FILTER__

#include <list>
#include <set>
#include <cmath>
#include <cassert>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>

#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>

template<unsigned int N,
        class T1, class S1,
        class T2, class S2>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = N - 1,
        typename std::enable_if<(N == 1)>::type *enabled = 0)
{
    // Will ignore boundaries initially.
    // Then will try adding reflection.

    // Rank must be in the range 0 to 1
    assert((0 <= rank) && (rank <= 1));

    const int rank_pos = round(rank * (2 * half_length));

    // The position of the
    typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
    std::multiset<T1> sorted_window;
    std::list< typename std::multiset<T1>::iterator > window_iters;

    // Get the initial sorted window.
    // Include the reflection.
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }

    typename std::multiset<T1>::iterator rank_point = sorted_window.begin();

    for (int i = 0; i < rank_pos; i++)
    {
        rank_point++;
    }

    while ( window_begin < src.size() )
    {
        dest[window_begin] = *rank_point;

        typename std::multiset<T1>::iterator prev_iter(window_iters.front());
        T1 prev_value = *prev_iter;
        window_iters.pop_front();

        window_begin++;

        T1 next_value;
        if ( window_begin < (src.size() - half_length) )
        {
            next_value = src[window_begin + half_length];
        }
        else
        {
            next_value = src[2 * src.size() - (window_begin + half_length + 2)];
        }

        if ( ( *rank_point < *prev_iter ) && ( *rank_point <= next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));
        }
        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point > next_value ) )
        {
            if ( rank_point == prev_iter )
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point--;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));
            }
        }
        else if ( ( *rank_point < *prev_iter ) && ( *rank_point > next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));

            rank_point--;
        }
        else if ( ( *rank_point >= *prev_iter ) && ( *rank_point <= next_value ) )
        {
            if (rank_point == prev_iter)
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point++;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));

                rank_point++;
            }
        }
    }
}

template<unsigned int N,
        class T1, class S1,
        class T2, class S2>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = N - 1,
        typename std::enable_if<(N > 1)>::type *enabled = 0)
{
    typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;

    for (unsigned int i = 0; i < N; i++)
    {
        transposed_axes[i] = i;
    }

    std::swap(transposed_axes[N - 1], transposed_axes[axis]);

    vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));

    vigra::MultiArrayView<N, T1, S1> dest_transposed_view(dest.transpose(transposed_axes));

    typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
    pos = 0;

    bool done = false;

    while (!done)
    {
        lineRankOrderFilter(src_transposed.bindInner(pos), dest_transposed_view.bindInner(pos), half_length, rank);

        bool carry = true;
        for (unsigned int i = 0; ( carry && (i < N) ); i++)
        {
            if ( (++pos[N - (i + 1)]) < src.shape()[N - (i + 1)])
            {
                carry = false;
            }
            else
            {
                pos[N - (i + 1)] = 0;
                carry = true;
            }
        }

        done = !carry;
    }
}

template<unsigned int N,
        class T1, class S1,
        class T2, class S2>
inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = N - 1)
{
    lineRankOrderFilterND(src, dest, half_length, rank, axis);
}

#endif //__RANK_FILTER__
<|endoftext|>


<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "Cursor.h"
#include "Application.h"
#include "CursorResource.h"
#include "graphics/ImageDataSTB.h"

namespace ouzel
{
    Cursor::Cursor()
    {
        resource = sharedApplication->createCursorResource();
    }

    Cursor::~Cursor()
    {
        if (sharedApplication && resource) sharedApplication->deleteCursorResource(resource);
    }

    bool Cursor::init(SystemCursor systemCursor)
    {
        if (!resource->init(systemCursor))
        {
            return false;
        }

        sharedApplication->uploadCursorResource(resource);

        return true;
    }

    bool Cursor::init(const std::string& filename, const Vector2& hotSpot)
    {
        graphics::ImageDataSTB image;
        if (!image.initFromFile(filename))
        {
            return false;
        }

        return init(image.getData(),
                    image.getSize(),
                    hotSpot);
    }

    bool Cursor::init(const std::vector<uint8_t>& data,
                      const Size2& size,
                      const Vector2& hotSpot)
    {
        if (!resource->init(data, size, hotSpot))
        {
            return false;
        }

        sharedApplication->uploadCursorResource(resource);

        return true;
    }
}
<commit_msg>Implement missing Cursor constructors<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "Cursor.h"
#include "Application.h"
#include "CursorResource.h"
#include "graphics/ImageDataSTB.h"

namespace ouzel
{
    Cursor::Cursor()
    {
        resource = sharedApplication->createCursorResource();
    }

    Cursor::Cursor(SystemCursor systemCursor):
        Cursor()
    {
        init(systemCursor);
    }

    Cursor::Cursor(const std::string& filename, const Vector2& hotSpot):
        Cursor()
    {
        init(filename, hotSpot);
    }

    Cursor::~Cursor()
    {
        if (sharedApplication && resource) sharedApplication->deleteCursorResource(resource);
    }

    bool Cursor::init(SystemCursor systemCursor)
    {
        if (!resource->init(systemCursor))
        {
            return false;
        }

        sharedApplication->uploadCursorResource(resource);

        return true;
    }

    bool Cursor::init(const std::string& filename, const Vector2& hotSpot)
    {
        graphics::ImageDataSTB image;
        if (!image.initFromFile(filename))
        {
            return false;
        }

        return init(image.getData(),
                    image.getSize(),
                    hotSpot);
    }

    bool Cursor::init(const std::vector<uint8_t>& data,
                      const Size2& size,
                      const Vector2& hotSpot)
    {
        if (!resource->init(data, size, hotSpot))
        {
            return false;
        }

        sharedApplication->uploadCursorResource(resource);

        return true;
    }
}
<|endoftext|>


<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_CXXAUX_HH__
#define __RAPICORN_CXXAUX_HH__

#include <rcore/rapicornconfig.h>       // _GNU_SOURCE
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>			// NULL
#include <sys/types.h>			// uint, ssize
#include <stdint.h>			// uint64_t
#include <limits.h>                     // {INT|CHAR|...}_{MIN|MAX}
#include <float.h>                      // {FLT|DBL}_{MIN|MAX|EPSILON}

// == Standard Macros ==
#ifndef FALSE
#  define FALSE					false
#endif
#ifndef TRUE
#  define TRUE					true
#endif
#define RAPICORN_ABS(a)                       	((a) > -(a) ? (a) : -(a))
#define RAPICORN_MIN(a,b)                         ((a) <= (b) ? (a) : (b))
#define RAPICORN_MAX(a,b)                         ((a) >= (b) ? (a) : (b))
#define RAPICORN_CLAMP(v,mi,ma)                   ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v)))
#define RAPICORN_ARRAY_SIZE(array)		(sizeof (array) / sizeof ((array)[0]))
#undef ABS
#define ABS                                     RAPICORN_ABS
#undef MIN
#define MIN                                     RAPICORN_MIN
#undef MAX
#define MAX                                     RAPICORN_MAX
#undef CLAMP
#define CLAMP                                   RAPICORN_CLAMP
#undef ARRAY_SIZE
#define ARRAY_SIZE				RAPICORN_ARRAY_SIZE
#undef EXTERN_C
#ifdef	__cplusplus
#define EXTERN_C                                extern "C"
#else
#define EXTERN_C                                extern
#endif
#undef STRFUNC
#define STRFUNC				        RAPICORN_SIMPLE_FUNCTION
#if     !defined (INT64_MAX) || !defined (INT64_MIN) || !defined (UINT64_MAX)
#ifdef  LLONG_MAX       // some gcc versions ship limits.h that fail to define LLONG_MAX for C99
#  define INT64_MAX     LLONG_MAX       // +9223372036854775807LL
#  define INT64_MIN     LLONG_MIN       // -9223372036854775808LL
#  define UINT64_MAX    ULLONG_MAX      // +18446744073709551615LLU
#else   // !LLONG_MAX but gcc always has __LONG_LONG_MAX__
#  define INT64_MAX     __LONG_LONG_MAX__
#  define INT64_MIN     (-INT64_MAX - 1LL)
#  define UINT64_MAX    (INT64_MAX * 2ULL + 1ULL)
#endif
#endif
#ifndef SIZE_T_MAX
#define SIZE_T_MAX              (~size_t (0))
#define SSIZE_T_MAX             (ssize_t (SIZE_T_MAX / 2))
#endif

// == Likelyness Hinting ==
#define	RAPICORN__BOOL(expr)		__extension__ ({ bool _rapicorn__bool; if (expr) _rapicorn__bool = 1; else _rapicorn__bool = 0; _rapicorn__bool; })
#define	RAPICORN_ISLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 1)
#define	RAPICORN_UNLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 0)
#define	RAPICORN_LIKELY			RAPICORN_ISLIKELY

// == Convenience Macros ==
#ifdef  RAPICORN_CONVENIENCE
#define	ISLIKELY		RAPICORN_ISLIKELY       ///< Compiler hint that @a expression is likely to be true.
#define	UNLIKELY		RAPICORN_UNLIKELY       ///< Compiler hint that @a expression is unlikely to be true.
#define	LIKELY			RAPICORN_LIKELY         ///< Compiler hint that @a expression is likely to be true.
#define	STRINGIFY               RAPICORN_CPP_STRINGIFY  ///< Produces a const char C string from the macro @a argument.
#endif
/**
 * @def RAPICORN_CONVENIENCE
 * Configuration macro to enable convenience macros.
 * Defining this before inclusion of rapicorn.hh or rapicorn-core.hh enables several convenience
 * macros that are defined in the global namespace without the usual "RAPICORN_" prefix,
 * see e.g. critical_unless(), UNLIKELY().
 */
#ifdef  RAPICORN_DOXYGEN
#  define RAPICORN_CONVENIENCE
#endif // RAPICORN_DOXYGEN

// == Preprocessor Convenience ==
#define RAPICORN_CPP_PASTE2_(a,b)               a ## b  // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_PASTE2(a,b)                RAPICORN_CPP_PASTE2_ (a,b)
#define RAPICORN_CPP_STRINGIFY_(s)              #s      // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_STRINGIFY(s)               RAPICORN_CPP_STRINGIFY_ (s)
#define RAPICORN_STATIC_ASSERT(expr)            static_assert (expr, #expr)

// == GCC Attributes ==
#if     __GNUC__ >= 4
#define RAPICORN_PURE                           __attribute__ ((__pure__))
#define RAPICORN_MALLOC                         __attribute__ ((__malloc__))
#define RAPICORN_PRINTF(format_idx, arg_idx)    __attribute__ ((__format__ (__printf__, format_idx, arg_idx)))
#define RAPICORN_SCANF(format_idx, arg_idx)     __attribute__ ((__format__ (__scanf__, format_idx, arg_idx)))
#define RAPICORN_FORMAT(arg_idx)                __attribute__ ((__format_arg__ (arg_idx)))
#define RAPICORN_SENTINEL                       __attribute__ ((__sentinel__))
#define RAPICORN_NORETURN                       __attribute__ ((__noreturn__))
#define RAPICORN_CONST                          __attribute__ ((__const__))
#define RAPICORN_UNUSED                         __attribute__ ((__unused__))
#define RAPICORN_NO_INSTRUMENT                  __attribute__ ((__no_instrument_function__))
#define RAPICORN_DEPRECATED                     __attribute__ ((__deprecated__))
#define RAPICORN_ALWAYS_INLINE			__attribute__ ((always_inline))
#define RAPICORN_NEVER_INLINE			__attribute__ ((noinline))
#define RAPICORN_CONSTRUCTOR			__attribute__ ((constructor,used))      // gcc-3.3 also needs "used" to emit code
#define RAPICORN_MAY_ALIAS                      __attribute__ ((may_alias))
#define	RAPICORN_SIMPLE_FUNCTION	       (::Rapicorn::string_from_pretty_function_name (__PRETTY_FUNCTION__).c_str())
#else   // !__GNUC__
#define RAPICORN_PURE
#define RAPICORN_MALLOC
#define RAPICORN_PRINTF(format_idx, arg_idx)
#define RAPICORN_SCANF(format_idx, arg_idx)
#define RAPICORN_FORMAT(arg_idx)
#define RAPICORN_SENTINEL
#define RAPICORN_NORETURN
#define RAPICORN_CONST
#define RAPICORN_UNUSED
#define RAPICORN_NO_INSTRUMENT
#define RAPICORN_DEPRECATED
#define RAPICORN_ALWAYS_INLINE
#define RAPICORN_NEVER_INLINE
#define RAPICORN_CONSTRUCTOR
#define RAPICORN_MAY_ALIAS
#define	RAPICORN_SIMPLE_FUNCTION	       (__func__)
#error  Failed to detect a recent GCC version (>= 4)
#endif  // !__GNUC__

// == Ensure 'uint' in global namespace ==
#if 	RAPICORN_SIZEOF_SYS_TYPESH_UINT == 0
typedef unsigned int		uint;           // for systems that don't define uint in sys/types.h
#else
RAPICORN_STATIC_ASSERT (RAPICORN_SIZEOF_SYS_TYPESH_UINT == 4);
#endif
RAPICORN_STATIC_ASSERT (sizeof (uint) == 4);

// == Rapicorn Namespace ==
namespace Rapicorn {

// == Provide Canonical Integer Types ==
typedef uint8_t                 uint8;          ///< An 8-bit unsigned integer.
typedef uint16_t                uint16;         ///< A 16-bit unsigned integer.
typedef uint32_t                uint32;         ///< A 32-bit unsigned integer.
typedef unsigned long long int  uint64;         ///< A 64-bit unsigned integer, use "%llu" in format strings.
// typedef uint64_t             uint64;         // int64_t / uint64_t are longs on AMD64 which breaks printf
typedef int8_t                  int8;           ///< An 8-bit signed integer.
typedef int16_t                 int16;          ///< A 16-bit signed integer.
typedef int32_t                 int32;          ///< A 32-bit signed integer.
typedef signed long long int    int64;          ///< A 64-bit unsigned integer, use "%lld" in format strings.
typedef uint32_t                unichar;        ///< A 32-bit unsigned integer used for Unicode characters.
RAPICORN_STATIC_ASSERT (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8);
RAPICORN_STATIC_ASSERT (sizeof (int8)  == 1 && sizeof (int16)  == 2 && sizeof (int32)  == 4 && sizeof (int64)  == 8);
RAPICORN_STATIC_ASSERT (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4);

// == File Path Handling ==
#ifdef	RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '\\'
#define RAPICORN_DIR_SEPARATOR_S	  "\\"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ';'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ";"
#else   // !RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '/'
#define RAPICORN_DIR_SEPARATOR_S	  "/"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ':'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ":"
#endif  // !RAPICORN_OS_WIN32
#define	RAPICORN_IS_DIR_SEPARATOR(c)        (RAPICORN_DIR_SEPARATOR == (c))
#define RAPICORN_IS_SEARCHPATH_SEPARATOR(c) (RAPICORN_SEARCHPATH_SEPARATOR == (c))

// == C++ Macros ==
#define RAPICORN_CLASS_NON_COPYABLE(ClassName)                                  private: \
  /*copy-ctor*/ ClassName  (const ClassName&) __attribute__ ((error ("NON_COPYABLE"))); \
  ClassName&    operator=  (const ClassName&) __attribute__ ((error ("NON_COPYABLE")))

// == C++ Helper Classes ==
/// Simple helper class to call one-line lambda initializers as static constructor.
struct Init {
  explicit Init (void (*f) ()) { f(); }
};

// == X86 Architecture ==
#if defined __i386__ || defined __x86_64__
#define RAPICORN_HAVE_X86_RDTSC  1
#define RAPICORN_X86_RDTSC()     ({ Rapicorn::uint32 __l_, __h_, __s_; \
                                    __asm__ __volatile__ ("rdtsc" : "=a" (__l_), "=d" (__h_));  \
                                    __s_ = __l_ + (Rapicorn::uint64 (__h_) << 32); __s_; })
#else
#define RAPICORN_HAVE_X86_RDTSC  0
#define RAPICORN_X86_RDTSC()    (0)
#endif

} // Rapicorn

#endif // __RAPICORN_CXXAUX_HH__
<commit_msg>RCORE: use C++11 'delete' keyword for methods of non-copyable classes<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_CXXAUX_HH__
#define __RAPICORN_CXXAUX_HH__

#include <rcore/rapicornconfig.h>       // _GNU_SOURCE
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>			// NULL
#include <sys/types.h>			// uint, ssize
#include <stdint.h>			// uint64_t
#include <limits.h>                     // {INT|CHAR|...}_{MIN|MAX}
#include <float.h>                      // {FLT|DBL}_{MIN|MAX|EPSILON}

// == Standard Macros ==
#ifndef FALSE
#  define FALSE					false
#endif
#ifndef TRUE
#  define TRUE					true
#endif
#define RAPICORN_ABS(a)                       	((a) > -(a) ? (a) : -(a))
#define RAPICORN_MIN(a,b)                         ((a) <= (b) ? (a) : (b))
#define RAPICORN_MAX(a,b)                         ((a) >= (b) ? (a) : (b))
#define RAPICORN_CLAMP(v,mi,ma)                   ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v)))
#define RAPICORN_ARRAY_SIZE(array)		(sizeof (array) / sizeof ((array)[0]))
#undef ABS
#define ABS                                     RAPICORN_ABS
#undef MIN
#define MIN                                     RAPICORN_MIN
#undef MAX
#define MAX                                     RAPICORN_MAX
#undef CLAMP
#define CLAMP                                   RAPICORN_CLAMP
#undef ARRAY_SIZE
#define ARRAY_SIZE				RAPICORN_ARRAY_SIZE
#undef EXTERN_C
#ifdef	__cplusplus
#define EXTERN_C                                extern "C"
#else
#define EXTERN_C                                extern
#endif
#undef STRFUNC
#define STRFUNC				        RAPICORN_SIMPLE_FUNCTION
#if     !defined (INT64_MAX) || !defined (INT64_MIN) || !defined (UINT64_MAX)
#ifdef  LLONG_MAX       // some gcc versions ship limits.h that fail to define LLONG_MAX for C99
#  define INT64_MAX     LLONG_MAX       // +9223372036854775807LL
#  define INT64_MIN     LLONG_MIN       // -9223372036854775808LL
#  define UINT64_MAX    ULLONG_MAX      // +18446744073709551615LLU
#else   // !LLONG_MAX but gcc always has __LONG_LONG_MAX__
#  define INT64_MAX     __LONG_LONG_MAX__
#  define INT64_MIN     (-INT64_MAX - 1LL)
#  define UINT64_MAX    (INT64_MAX * 2ULL + 1ULL)
#endif
#endif
#ifndef SIZE_T_MAX
#define SIZE_T_MAX              (~size_t (0))
#define SSIZE_T_MAX             (ssize_t (SIZE_T_MAX / 2))
#endif

// == Likelyness Hinting ==
#define	RAPICORN__BOOL(expr)		__extension__ ({ bool _rapicorn__bool; if (expr) _rapicorn__bool = 1; else _rapicorn__bool = 0; _rapicorn__bool; })
#define	RAPICORN_ISLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 1)
#define	RAPICORN_UNLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 0)
#define	RAPICORN_LIKELY			RAPICORN_ISLIKELY

// == Convenience Macros ==
#ifdef  RAPICORN_CONVENIENCE
#define	ISLIKELY		RAPICORN_ISLIKELY       ///< Compiler hint that @a expression is likely to be true.
#define	UNLIKELY		RAPICORN_UNLIKELY       ///< Compiler hint that @a expression is unlikely to be true.
#define	LIKELY			RAPICORN_LIKELY         ///< Compiler hint that @a expression is likely to be true.
#define	STRINGIFY               RAPICORN_CPP_STRINGIFY  ///< Produces a const char C string from the macro @a argument.
#endif
/**
 * @def RAPICORN_CONVENIENCE
 * Configuration macro to enable convenience macros.
 * Defining this before inclusion of rapicorn.hh or rapicorn-core.hh enables several convenience
 * macros that are defined in the global namespace without the usual "RAPICORN_" prefix,
 * see e.g. critical_unless(), UNLIKELY().
 */
#ifdef  RAPICORN_DOXYGEN
#  define RAPICORN_CONVENIENCE
#endif // RAPICORN_DOXYGEN

// == Preprocessor Convenience ==
#define RAPICORN_CPP_PASTE2_(a,b)               a ## b  // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_PASTE2(a,b)                RAPICORN_CPP_PASTE2_ (a,b)
#define RAPICORN_CPP_STRINGIFY_(s)              #s      // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_STRINGIFY(s)               RAPICORN_CPP_STRINGIFY_ (s)
#define RAPICORN_STATIC_ASSERT(expr)            static_assert (expr, #expr)

// == GCC Attributes ==
#if     __GNUC__ >= 4
#define RAPICORN_PURE                           __attribute__ ((__pure__))
#define RAPICORN_MALLOC                         __attribute__ ((__malloc__))
#define RAPICORN_PRINTF(format_idx, arg_idx)    __attribute__ ((__format__ (__printf__, format_idx, arg_idx)))
#define RAPICORN_SCANF(format_idx, arg_idx)     __attribute__ ((__format__ (__scanf__, format_idx, arg_idx)))
#define RAPICORN_FORMAT(arg_idx)                __attribute__ ((__format_arg__ (arg_idx)))
#define RAPICORN_SENTINEL                       __attribute__ ((__sentinel__))
#define RAPICORN_NORETURN                       __attribute__ ((__noreturn__))
#define RAPICORN_CONST                          __attribute__ ((__const__))
#define RAPICORN_UNUSED                         __attribute__ ((__unused__))
#define RAPICORN_NO_INSTRUMENT                  __attribute__ ((__no_instrument_function__))
#define RAPICORN_DEPRECATED                     __attribute__ ((__deprecated__))
#define RAPICORN_ALWAYS_INLINE			__attribute__ ((always_inline))
#define RAPICORN_NEVER_INLINE			__attribute__ ((noinline))
#define RAPICORN_CONSTRUCTOR			__attribute__ ((constructor,used))      // gcc-3.3 also needs "used" to emit code
#define RAPICORN_MAY_ALIAS                      __attribute__ ((may_alias))
#define	RAPICORN_SIMPLE_FUNCTION	       (::Rapicorn::string_from_pretty_function_name (__PRETTY_FUNCTION__).c_str())
#else   // !__GNUC__
#define RAPICORN_PURE
#define RAPICORN_MALLOC
#define RAPICORN_PRINTF(format_idx, arg_idx)
#define RAPICORN_SCANF(format_idx, arg_idx)
#define RAPICORN_FORMAT(arg_idx)
#define RAPICORN_SENTINEL
#define RAPICORN_NORETURN
#define RAPICORN_CONST
#define RAPICORN_UNUSED
#define RAPICORN_NO_INSTRUMENT
#define RAPICORN_DEPRECATED
#define RAPICORN_ALWAYS_INLINE
#define RAPICORN_NEVER_INLINE
#define RAPICORN_CONSTRUCTOR
#define RAPICORN_MAY_ALIAS
#define	RAPICORN_SIMPLE_FUNCTION	       (__func__)
#error  Failed to detect a recent GCC version (>= 4)
#endif  // !__GNUC__

// == Ensure 'uint' in global namespace ==
#if 	RAPICORN_SIZEOF_SYS_TYPESH_UINT == 0
typedef unsigned int		uint;           // for systems that don't define uint in sys/types.h
#else
RAPICORN_STATIC_ASSERT (RAPICORN_SIZEOF_SYS_TYPESH_UINT == 4);
#endif
RAPICORN_STATIC_ASSERT (sizeof (uint) == 4);

// == Rapicorn Namespace ==
namespace Rapicorn {

// == Provide Canonical Integer Types ==
typedef uint8_t                 uint8;          ///< An 8-bit unsigned integer.
typedef uint16_t                uint16;         ///< A 16-bit unsigned integer.
typedef uint32_t                uint32;         ///< A 32-bit unsigned integer.
typedef unsigned long long int  uint64;         ///< A 64-bit unsigned integer, use "%llu" in format strings.
// typedef uint64_t             uint64;         // int64_t / uint64_t are longs on AMD64 which breaks printf
typedef int8_t                  int8;           ///< An 8-bit signed integer.
typedef int16_t                 int16;          ///< A 16-bit signed integer.
typedef int32_t                 int32;          ///< A 32-bit signed integer.
typedef signed long long int    int64;          ///< A 64-bit unsigned integer, use "%lld" in format strings.
typedef uint32_t                unichar;        ///< A 32-bit unsigned integer used for Unicode characters.
RAPICORN_STATIC_ASSERT (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8);
RAPICORN_STATIC_ASSERT (sizeof (int8)  == 1 && sizeof (int16)  == 2 && sizeof (int32)  == 4 && sizeof (int64)  == 8);
RAPICORN_STATIC_ASSERT (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4);

// == File Path Handling ==
#ifdef	RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '\\'
#define RAPICORN_DIR_SEPARATOR_S	  "\\"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ';'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ";"
#else   // !RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '/'
#define RAPICORN_DIR_SEPARATOR_S	  "/"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ':'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ":"
#endif  // !RAPICORN_OS_WIN32
#define	RAPICORN_IS_DIR_SEPARATOR(c)        (RAPICORN_DIR_SEPARATOR == (c))
#define RAPICORN_IS_SEARCHPATH_SEPARATOR(c) (RAPICORN_SEARCHPATH_SEPARATOR == (c))

// == C++ Macros ==
#define RAPICORN_CLASS_NON_COPYABLE(ClassName)                                  private: \
  /*copy-ctor*/ ClassName  (const ClassName&) __attribute__ ((error ("NON_COPYABLE"))) = delete; \
  ClassName&    operator=  (const ClassName&) __attribute__ ((error ("NON_COPYABLE"))) = delete

// == C++ Helper Classes ==
/// Simple helper class to call one-line lambda initializers as static constructor.
struct Init {
  explicit Init (void (*f) ()) { f(); }
};

// == X86 Architecture ==
#if defined __i386__ || defined __x86_64__
#define RAPICORN_HAVE_X86_RDTSC  1
#define RAPICORN_X86_RDTSC()     ({ Rapicorn::uint32 __l_, __h_, __s_; \
                                    __asm__ __volatile__ ("rdtsc" : "=a" (__l_), "=d" (__h_));  \
                                    __s_ = __l_ + (Rapicorn::uint64 (__h_) << 32); __s_; })
#else
#define RAPICORN_HAVE_X86_RDTSC  0
#define RAPICORN_X86_RDTSC()    (0)
#endif

} // Rapicorn

#endif // __RAPICORN_CXXAUX_HH__
<|endoftext|>