Refactored segment_foreground to be easier to reason about

--- src/plugins/orbbec_hand/Segmentation.cpp
+++ src/plugins/orbbec_hand/Segmentation.cpp
@@ -7,491 +7,539 @@

 #define MAX_DEPTH 10000

-namespace sensekit { namespace plugins { namespace hand {
-
-    namespace segmentation {
-
-        struct PointTTL
-        {
-            cv::Point m_point;
-            float m_ttl;
-            bool m_pathInRange;
-
-            PointTTL(cv::Point point, float ttl, bool pathInRange)
-            {
-                m_point = point;
-                m_ttl = ttl;
-                m_pathInRange = pathInRange;
-            }
-        };
-
-        static void segment_foreground(TrackingData& data)
-        {
-            const float maxSegmentationDist = data.maxSegmentationDist;
-            const SegmentationVelocityPolicy velocitySignalPolicy = data.velocityPolicy;
-            const float seedDepth = data.matrices.depth.at<float>(data.seedPosition);
-            cv::Mat& depthMatrix = data.matrices.depth;
-            cv::Mat& velocitySignalMatrix = data.matrices.velocitySignal;
-            cv::Mat& areaSqrtMatrix = data.matrices.areaSqrt;
-            cv::Mat& segmentationMatrix = data.matrices.layerSegmentation;
-            cv::Mat& searchedMatrix = data.matrices.foregroundSearched;
+namespace sensekit { namespace plugins { namespace hand { namespace segmentation {
+
+    struct PointTTL
+    {
+        cv::Point point;
+        float ttl;
+
+        PointTTL(cv::Point point, float ttl) :
+            point(point),
+            ttl(ttl)
+        { }
+    };
+
+    static cv::Point INVALID_POINT(-1, -1);
+
+    static void enqueue_neighbors(cv::Mat& matVisited,
+                                 std::queue<PointTTL>& pointQueue,
+                                 PointTTL pt)
+    {
+        const cv::Point& p = pt.point;
+        float& ttlRef = pt.ttl;
+
+        int width = matVisited.cols;
+        int height = matVisited.rows;
+
+        cv::Point right(p.x + 1, p.y);
+        cv::Point left(p.x - 1, p.y);
+        cv::Point down(p.x, p.y + 1);
+        cv::Point up(p.x, p.y - 1);
+
+        if (right.x < width && 0 == matVisited.at<char>(right))
+        {
+            matVisited.at<char>(right) = 1;
+            pointQueue.push(PointTTL(right, ttlRef));
+        }
+        if (left.x >= 0 && 0 == matVisited.at<char>(left))
+        {
+            matVisited.at<char>(left) = 1;
+            pointQueue.push(PointTTL(left, ttlRef));
+        }
+        if (down.y < height && 0 == matVisited.at<char>(down))
+        {
+            matVisited.at<char>(down) = 1;
+            pointQueue.push(PointTTL(down, ttlRef));
+        }
+        if (up.y >= 0 && 0 == matVisited.at<char>(up))
+        {
+            matVisited.at<char>(up) = 1;
+            pointQueue.push(PointTTL(up, ttlRef));
+        }
+    }
+
+    static cv::Point find_nearest_in_range_pixel(TrackingData& data,
+                                                cv::Mat& matVisited)
+    {
+        assert(matVisited.size() == data.matrices.depth.size());
+
+        const float maxDepth = data.referenceDepth + data.bandwidthDepth;
+        const float maxSegmentationDist = data.maxSegmentationDist;
+        cv::Mat& depthMatrix = data.matrices.depth;
+        cv::Mat& searchedMatrix = data.matrices.foregroundSearched;
+        bool isCandidatePoint = data.pointType == TrackedPointType::CandidatePoint;
+        cv::Mat& areaSqrtMatrix = data.matrices.areaSqrt;
+
+        std::queue<PointTTL> pointQueue;
+
+        pointQueue.push(PointTTL(data.seedPosition, maxSegmentationDist));
+
+        matVisited.at<char>(data.seedPosition) = 1;
+
+        while (!pointQueue.empty())
+        {
+            PointTTL pt = pointQueue.front();
+            pointQueue.pop();
+            const cv::Point& p = pt.point;
+            float& ttlRef = pt.ttl;
+
+            if (ttlRef <= 0)
+            {
+                continue;
+            }
+
+            searchedMatrix.at<char>(p) = PixelType::Searched;
+
+            float depth = depthMatrix.at<float>(p);
+            bool pointInRange = depth != 0 && depth < maxDepth;
+
+            if (pointInRange)
+            {
+                return p;
+            }
+
+            if (isCandidatePoint)
+            {
+                //active points get infinite recovery distance when the seed is out of range
+                ttlRef -= areaSqrtMatrix.at<float>(p);
+            }
+
+            enqueue_neighbors(matVisited, pointQueue, pt);
+        }
+
+        return INVALID_POINT;
+    }
+
+    static void segment_foreground(TrackingData& data)
+    {
+        const float& maxSegmentationDist = data.maxSegmentationDist;
+        const SegmentationVelocityPolicy& velocitySignalPolicy = data.velocityPolicy;
+        const float seedDepth = data.matrices.depth.at<float>(data.seedPosition);
+        cv::Mat& depthMatrix = data.matrices.depth;
+        cv::Mat& velocitySignalMatrix = data.matrices.velocitySignal;
+        cv::Mat& areaSqrtMatrix = data.matrices.areaSqrt;
+        cv::Mat& segmentationMatrix = data.matrices.layerSegmentation;
+        cv::Mat& searchedMatrix = data.matrices.foregroundSearched;
+
+        std::queue<PointTTL> pointQueue;
+
+        //does the seed point start in range?
+        //If not, it will search outward until it finds in range pixels
+        const float maxDepth = data.referenceDepth + data.bandwidthDepth;

-            bool isCandidatePoint = data.pointType == TrackedPointType::CandidatePoint;
-            std::queue<PointTTL> pointQueue;
-
-            //does the seed point start in range?
-            //If not, it will search outward until it finds in range pixels
-            const float maxDepth = data.referenceDepth + data.bandwidthDepth;
-            bool seedInRange = seedDepth != 0 && seedDepth < maxDepth;
-            bool anyInRange = seedInRange;
-
-            pointQueue.push(PointTTL(data.seedPosition, maxSegmentationDist, seedInRange));
-
-            cv::Mat matVisited = cv::Mat::zeros(depthMatrix.size(), CV_8UC1);
-
-            int width = depthMatrix.cols;
-            int height = depthMatrix.rows;
-
-            matVisited.at<char>(data.seedPosition) = 1;
-
-            while (!pointQueue.empty())
-            {
-                PointTTL pt = pointQueue.front();
-                pointQueue.pop();
-                cv::Point p = pt.m_point;
-                float ttl = pt.m_ttl;
-                bool pathInRange = pt.m_pathInRange;
-
-                //Some other path has come ashore first, so cut off this path's exploration
-                bool rejectedOutOfRangePath = !pathInRange && anyInRange;
-
-                if (velocitySignalPolicy == VELOCITY_POLICY_RESET_TTL &&
-                    velocitySignalMatrix.at<char>(p) == PixelType::Foreground)
-                {
-                    ttl = maxSegmentationDist;
-                }
-                if (ttl > 0 && !rejectedOutOfRangePath)
-                {
-                    searchedMatrix.at<char>(p) = PixelType::Searched;
-
-                    float depth = depthMatrix.at<float>(p);
-                    bool pointInRange = depth != 0 && depth < maxDepth;
-
-                    //Keep exploring this pixel's neighbors if: TTL > 0 and
-                    // either this point is in range, or
-                    // the path has not been in range yet
-                    if (!pathInRange || pointInRange)
+        cv::Mat matVisited = cv::Mat::zeros(depthMatrix.size(), CV_8UC1);
+
+        cv::Point seedPosition = data.seedPosition;
+
+        bool seedInRange = seedDepth != 0 && seedDepth < maxDepth;
+        if (!seedInRange)
+        {
+            seedPosition = find_nearest_in_range_pixel(data, matVisited);
+            if (seedPosition == INVALID_POINT)
+            {
+                //No in range pixels found, no foreground to set
+                return;
+            }
+        }
+
+        pointQueue.push(PointTTL(seedPosition, maxSegmentationDist));
+
+        matVisited.at<char>(data.seedPosition) = 1;
+
+        while (!pointQueue.empty())
+        {
+            PointTTL pt = pointQueue.front();
+            pointQueue.pop();
+            const cv::Point& p = pt.point;
+            float& ttlRef = pt.ttl;
+
+            if (velocitySignalPolicy == VELOCITY_POLICY_RESET_TTL &&
+                velocitySignalMatrix.at<char>(p) == PixelType::Foreground)
+            {
+                ttlRef = maxSegmentationDist;
+            }
+
+            float depth = depthMatrix.at<float>(p);
+            bool pointOutOfRange = depth == 0 || depth > maxDepth;
+
+            if (ttlRef <= 0 || pointOutOfRange)
+            {
+                continue;
+            }
+
+            searchedMatrix.at<char>(p) = PixelType::Searched;
+            segmentationMatrix.at<char>(p) = PixelType::Foreground;
+
+            ttlRef -= areaSqrtMatrix.at<float>(p);
+
+            enqueue_neighbors(matVisited, pointQueue, pt);
+        }
+    }
+
+    void calculate_layer_score(TrackingData& data)
+    {
+        cv::Mat& depthMatrix = data.matrices.depth;
+        cv::Mat& basicScoreMatrix = data.matrices.basicScore;
+        cv::Mat& edgeDistanceMatrix = data.matrices.layerEdgeDistance;
+        const float edgeDistanceFactor = data.edgeDistanceFactor;
+        const float targetEdgeDist = data.targetEdgeDistance;
+        cv::Mat& layerScoreMatrix = data.matrices.layerScore;
+        const float pointInertiaFactor = data.pointInertiaFactor;
+        const float pointInertiaRadius = data.pointInertiaRadius;
+
+        ScalingCoordinateMapper mapper = get_scaling_mapper(data.matrices);
+
+        cv::Point3f seedWorldPosition = mapper.convert_depth_to_world(data.seedPosition.x,
+                                                                        data.seedPosition.y,
+                                                                        data.referenceDepth);
+        bool activePoint = data.pointType == TrackedPointType::ActivePoint;
+
+        int width = depthMatrix.cols;
+        int height = depthMatrix.rows;
+
+        for (int y = 0; y < height; y++)
+        {
+            float* depthRow = depthMatrix.ptr<float>(y);
+            float* basicScoreRow = basicScoreMatrix.ptr<float>(y);
+            float* edgeDistanceRow = edgeDistanceMatrix.ptr<float>(y);
+            float* layerScoreRow = layerScoreMatrix.ptr<float>(y);
+
+            for (int x = 0; x < width; x++)
+            {
+                float depth = *depthRow;
+                if (depth != 0)
+                {
+                    cv::Point3f worldPosition = mapper.convert_depth_to_world(x, y, depth);
+
+                    float score = *basicScoreRow;
+
+                    if (activePoint && pointInertiaRadius > 0)
                     {
-                        //If candidate point, always decrement TTL.
-                        //Otherwise, active points get a larger range, more likely to recover.
-                        //If active tracking and any points are in range, start decrementing TTL.
-                        if (isCandidatePoint || anyInRange)
-                        {
-                            ttl -= areaSqrtMatrix.at<float>(p);
-                        }
-
-                        if (pointInRange)
-                        {
-                            //Once a path has "come ashore" -- found an in-range pixel -- it won't leave the range again
-                            pathInRange = true;
-                            anyInRange = true;
-                            segmentationMatrix.at<char>(p) = PixelType::Foreground;
-                        }
-
-                        cv::Point right(p.x + 1, p.y);
-                        cv::Point left(p.x - 1, p.y);
-                        cv::Point down(p.x, p.y + 1);
-                        cv::Point up(p.x, p.y - 1);
-
-                        if (right.x < width && 0 == matVisited.at<char>(right))
-                        {
-                            matVisited.at<char>(right) = 1;
-                            pointQueue.push(PointTTL(right, ttl, pathInRange));
-                        }
-                        if (left.x >= 0 && 0 == matVisited.at<char>(left))
-                        {
-                            matVisited.at<char>(left) = 1;
-                            pointQueue.push(PointTTL(left, ttl, pathInRange));
-                        }
-                        if (down.y < height && 0 == matVisited.at<char>(down))
-                        {
-                            matVisited.at<char>(down) = 1;
-                            pointQueue.push(PointTTL(down, ttl, pathInRange));
-                        }
-                        if (up.y >= 0 && 0 == matVisited.at<char>(up))
-                        {
-                            matVisited.at<char>(up) = 1;
-                            pointQueue.push(PointTTL(up, ttl, pathInRange));
-                        }
+                        float distFromSeedNorm = std::max(0.0, std::min(1.0,
+                                                    cv::norm(worldPosition - seedWorldPosition) / pointInertiaRadius));
+                        score += (1.0f - distFromSeedNorm) * pointInertiaFactor;
                     }
-                }
-            }
-        }
-
-        void calculate_layer_score(TrackingData& data)
-        {
-            cv::Mat& depthMatrix = data.matrices.depth;
-            cv::Mat& basicScoreMatrix = data.matrices.basicScore;
-            cv::Mat& edgeDistanceMatrix = data.matrices.layerEdgeDistance;
-            const float edgeDistanceFactor = data.edgeDistanceFactor;
-            const float targetEdgeDist = data.targetEdgeDistance;
-            cv::Mat& layerScoreMatrix = data.matrices.layerScore;
-            const float pointInertiaFactor = data.pointInertiaFactor;
-            const float pointInertiaRadius = data.pointInertiaRadius;
-
-            ScalingCoordinateMapper mapper = get_scaling_mapper(data.matrices);
-
-            cv::Point3f seedWorldPosition = mapper.convert_depth_to_world(data.seedPosition.x,
-                                                                          data.seedPosition.y,
-                                                                          data.referenceDepth);
-            bool activePoint = data.pointType == TrackedPointType::ActivePoint;
-
-            int width = depthMatrix.cols;
-            int height = depthMatrix.rows;
-
-            for (int y = 0; y < height; y++)
-            {
-                float* depthRow = depthMatrix.ptr<float>(y);
-                float* basicScoreRow = basicScoreMatrix.ptr<float>(y);
-                float* edgeDistanceRow = edgeDistanceMatrix.ptr<float>(y);
-                float* layerScoreRow = layerScoreMatrix.ptr<float>(y);
-
-                for (int x = 0; x < width; x++)
-                {
-                    float depth = *depthRow;
-                    if (depth != 0)
+
+                    float edgeDistance = *edgeDistanceRow;
+                    float edgeScore = (targetEdgeDist - abs(targetEdgeDist - edgeDistance)) * edgeDistanceFactor;
+                    if (edgeScore > 0)
                     {
-                        cv::Point3f worldPosition = mapper.convert_depth_to_world(x, y, depth);
-
-                        float score = *basicScoreRow;
-
-                        if (activePoint && pointInertiaRadius > 0)
-                        {
-                            float distFromSeedNorm = std::max(0.0, std::min(1.0,
-                                                        cv::norm(worldPosition - seedWorldPosition) / pointInertiaRadius));
-                            score += (1.0f - distFromSeedNorm) * pointInertiaFactor;
-                        }
-
-                        float edgeDistance = *edgeDistanceRow;
-                        float edgeScore = (targetEdgeDist - abs(targetEdgeDist - edgeDistance)) * edgeDistanceFactor;
-                        if (edgeScore > 0)
-                        {
-                            score += edgeScore;
-                        }
-                        else
-                        {
-                            score = 0;
-                        }
-
-
-                        *layerScoreRow = score;
+                        score += edgeScore;
                     }
                     else
                     {
-                        *layerScoreRow = 0;
+                        score = 0;
                     }
-                    ++depthRow;
-                    ++basicScoreRow;
-                    ++edgeDistanceRow;
-                    ++layerScoreRow;
-                }
-            }
-        }
-
-        static cv::Point track_point_from_seed(TrackingData& data)
-        {
-            cv::Size size = data.matrices.depth.size();
-            data.matrices.layerSegmentation = cv::Mat::zeros(size, CV_8UC1);
-            data.matrices.layerEdgeDistance = cv::Mat::zeros(size, CV_32FC1);
-            data.matrices.layerScore = cv::Mat::zeros(size, CV_32FC1);
-            //data.matrices.matLayerSegmentation.setTo(cv::Scalar(0));
-
-            segment_foreground(data);
+
+
+                    *layerScoreRow = score;
+                }
+                else
+                {
+                    *layerScoreRow = 0;
+                }
+                ++depthRow;
+                ++basicScoreRow;
+                ++edgeDistanceRow;
+                ++layerScoreRow;
+            }
+        }
+    }
+
+    static cv::Point track_point_from_seed(TrackingData& data)
+    {
+        cv::Size size = data.matrices.depth.size();
+        data.matrices.layerSegmentation = cv::Mat::zeros(size, CV_8UC1);
+        data.matrices.layerEdgeDistance = cv::Mat::zeros(size, CV_32FC1);
+        data.matrices.layerScore = cv::Mat::zeros(size, CV_32FC1);
+        //data.matrices.matLayerSegmentation.setTo(cv::Scalar(0));
+
+        segment_foreground(data);

-            calculate_edge_distance(data.matrices.layerSegmentation,
-                                    data.matrices.areaSqrt,
-                                    data.matrices.layerEdgeDistance);
-
-            calculate_layer_score(data);
-
-            double min, max;
-            cv::Point minLoc, maxLoc;
-
-            cv::minMaxLoc(data.matrices.layerScore, &min, &max, &minLoc, &maxLoc, data.matrices.layerSegmentation);
-
-            if (data.matrices.debugLayersEnabled)
-            {
-                ++data.matrices.layerCount;
-
-                cv::bitwise_or(cv::Mat(size, CV_8UC1, cv::Scalar(data.matrices.layerCount)),
-                    data.matrices.debugSegmentation,
-                    data.matrices.debugSegmentation,
-                    data.matrices.layerSegmentation);
-                if (data.pointType == TrackedPointType::ActivePoint)
-                {
-                    cv::Mat scoreMask;
+        calculate_edge_distance(data.matrices.layerSegmentation,
+                                data.matrices.areaSqrt,
+                                data.matrices.layerEdgeDistance);
+
+        calculate_layer_score(data);
+
+        double min, max;
+        cv::Point minLoc, maxLoc;
+
+        cv::minMaxLoc(data.matrices.layerScore, &min, &max, &minLoc, &maxLoc, data.matrices.layerSegmentation);
+
+        if (data.matrices.debugLayersEnabled)
+        {
+            ++data.matrices.layerCount;
+
+            cv::bitwise_or(cv::Mat(size, CV_8UC1, cv::Scalar(data.matrices.layerCount)),
+                data.matrices.debugSegmentation,
+                data.matrices.debugSegmentation,
+                data.matrices.layerSegmentation);
+            if (data.pointType == TrackedPointType::ActivePoint)
+            {
+                cv::Mat scoreMask;

-                    cv::inRange(data.matrices.layerScore, 1, INT_MAX, scoreMask);
-                    cv::normalize(data.matrices.layerScore, data.matrices.debugScore, 0, 1, cv::NORM_MINMAX, -1, scoreMask);
-                }
-            }
-
-            return maxLoc;
-        }
-
-        cv::Point converge_track_point_from_seed(TrackingData& data)
-        {
-            cv::Point point = data.seedPosition;
-            cv::Point lastPoint = data.seedPosition;
-            int iterations = 0;
-
-            do
-            {
-                lastPoint = point;
-                point = track_point_from_seed(data);
-                ++iterations;
-            } while (point != lastPoint && iterations < data.iterationMax && point.x != -1 && point.y != -1);
-
-            return point;
-        }
-
-        bool find_next_velocity_seed_pixel(cv::Mat& velocitySignalMatrix,
-                                          cv::Mat& searchedMatrix,
-                                          cv::Point& foregroundPosition,
-                                          cv::Point& nextSearchStart)
-        {
-            assert(foregroundMatrix.cols == searchedMatrix.cols);
-            assert(foregroundMatrix.rows == searchedMatrix.rows);
-            int width = velocitySignalMatrix.cols;
-            int height = velocitySignalMatrix.rows;
-
-            const int startX = MAX(0, MIN(width - 1, nextSearchStart.x));
-            const int startY = MAX(0, MIN(height - 1, nextSearchStart.y));
-
-            for (int y = startY; y < height; y++)
-            {
-                for (int x = startX; x < width; x++)
-                {
-                    uint8_t velocitySignal = *velocitySignalMatrix.ptr<uint8_t>(y, x);
-                    uint8_t searched = *searchedMatrix.ptr<uint8_t>(y, x);
-                    if (velocitySignal == PixelType::Foreground && searched != PixelType::Searched)
+                cv::inRange(data.matrices.layerScore, 1, INT_MAX, scoreMask);
+                cv::normalize(data.matrices.layerScore, data.matrices.debugScore, 0, 1, cv::NORM_MINMAX, -1, scoreMask);
+            }
+        }
+
+        return maxLoc;
+    }
+
+    cv::Point converge_track_point_from_seed(TrackingData& data)
+    {
+        cv::Point point = data.seedPosition;
+        cv::Point lastPoint = data.seedPosition;
+        int iterations = 0;
+
+        do
+        {
+            lastPoint = point;
+            point = track_point_from_seed(data);
+            ++iterations;
+        } while (point != lastPoint && iterations < data.iterationMax && point.x != -1 && point.y != -1);
+
+        return point;
+    }
+
+    bool find_next_velocity_seed_pixel(cv::Mat& velocitySignalMatrix,
+                                        cv::Mat& searchedMatrix,
+                                        cv::Point& foregroundPosition,
+                                        cv::Point& nextSearchStart)
+    {
+        assert(foregroundMatrix.cols == searchedMatrix.cols);
+        assert(foregroundMatrix.rows == searchedMatrix.rows);
+        int width = velocitySignalMatrix.cols;
+        int height = velocitySignalMatrix.rows;
+
+        const int startX = MAX(0, MIN(width - 1, nextSearchStart.x));
+        const int startY = MAX(0, MIN(height - 1, nextSearchStart.y));
+
+        for (int y = startY; y < height; y++)
+        {
+            for (int x = startX; x < width; x++)
+            {
+                uint8_t velocitySignal = *velocitySignalMatrix.ptr<uint8_t>(y, x);
+                uint8_t searched = *searchedMatrix.ptr<uint8_t>(y, x);
+                if (velocitySignal == PixelType::Foreground && searched != PixelType::Searched)
+                {
+                    foregroundPosition.x = x;
+                    foregroundPosition.y = y;
+
+                    nextSearchStart.x = x + 1;
+                    if (nextSearchStart.x < width)
                     {
-                        foregroundPosition.x = x;
-                        foregroundPosition.y = y;
-
-                        nextSearchStart.x = x + 1;
-                        if (nextSearchStart.x < width)
-                        {
-                            nextSearchStart.y = y;
-                        }
-                        else
-                        {
-                            nextSearchStart.x = 0;
-                            nextSearchStart.y = y + 1;
-                            if (nextSearchStart.y >= height)
-                            {
-                                return false;
-                            }
-                        }
-                        return true;
-                    }
-                }
-            }
-            foregroundPosition.x = -1;
-            foregroundPosition.y = -1;
-            nextSearchStart.x = width;
-            nextSearchStart.y = height;
-            return false;
-        }
-
-        void calculate_basic_score(cv::Mat& depthMatrix,
-                                   cv::Mat& scoreMatrix,
-                                   const float heightFactor,
-                                   const float depthFactor,
-                                   const ScalingCoordinateMapper& mapper)
-        {
-            scoreMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
-
-            int width = depthMatrix.cols;
-            int height = depthMatrix.rows;
-
-            for (int y = 0; y < height; y++)
-            {
-                float* depthRow = depthMatrix.ptr<float>(y);
-                float* scoreRow = scoreMatrix.ptr<float>(y);
-
-                for (int x = 0; x < width; x++)
-                {
-                    float depth = *depthRow;
-                    if (depth != 0)
-                    {
-                        cv::Point3f worldPosition = mapper.convert_depth_to_world(x, y, depth);
-
-                        float score = 0;
-                        score += worldPosition.y * heightFactor;
-                        score += (MAX_DEPTH - worldPosition.z) * depthFactor;
-
-                        *scoreRow = score;
+                        nextSearchStart.y = y;
                     }
                     else
                     {
-                        *scoreRow = 0;
-                    }
-                    ++depthRow;
-                    ++scoreRow;
-                }
-            }
-        }
-
-        void calculate_edge_distance(cv::Mat& segmentationMatrix,
-                                     cv::Mat& areaSqrtMatrix,
-                                     cv::Mat& edgeDistanceMatrix)
-        {
-            cv::Mat eroded;
-            cv::Mat crossElement = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(3, 3));
-
-            edgeDistanceMatrix = cv::Mat::zeros(segmentationMatrix.size(), CV_32FC1);
-            cv::Mat ones = cv::Mat::ones(segmentationMatrix.size(), CV_32FC1);
-            segmentationMatrix.copyTo(eroded);
-
-            //close small holes
-            int dilateCount = 1;
-            for (int i = 0; i < dilateCount; i++)
-            {
-                cv::dilate(eroded, eroded, crossElement);
-            }
-
-            int nonZeroCount = 0;
-            const int imageLength = eroded.cols * eroded.rows;
-            int iterations = 0;
-            const int maxIterations = segmentationMatrix.cols / 2;
-            bool done;
-            do
-            {
-                //erode makes the image smaller
-                cv::erode(eroded, eroded, crossElement);
-                //accumulate the eroded image to the edgeDistance buffer
-                cv::add(areaSqrtMatrix, edgeDistanceMatrix, edgeDistanceMatrix, eroded, CV_32FC1);
-
-                nonZeroCount = cv::countNonZero(eroded);
-                done = (nonZeroCount == 0);
-
-                //nonZeroCount < imageLength guards against segmentation with all 1's, which will never erode
-            } while (!done && nonZeroCount < imageLength && ++iterations < maxIterations);
-        }
-
-        static float get_depth_area(cv::Point3f& p1,
-                                    cv::Point3f& p2,
-                                    cv::Point3f& p3,
-                                    const ScalingCoordinateMapper& mapper)
-        {
-            cv::Point3f world1 = mapper.convert_depth_to_world(p1);
-            cv::Point3f world2 = mapper.convert_depth_to_world(p2);
-            cv::Point3f world3 = mapper.convert_depth_to_world(p3);
-
-            cv::Point3f v1 = world2 - world1;
-            cv::Point3f v2 = world3 - world1;
-
-            float area = static_cast<float>(0.5 * cv::norm(v1.cross(v2)));
-            return area;
-        }
-
-        void calculate_segment_area(cv::Mat& depthMatrix, cv::Mat& areaMatrix, cv::Mat& areaSqrtMatrix, const ScalingCoordinateMapper& mapper)
-        {
-            int width = depthMatrix.cols;
-            int height = depthMatrix.rows;
-
-            areaMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
-            areaSqrtMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
-
-            for (int y = 0; y < height - 1; y++)
-            {
-                float* depthRow = depthMatrix.ptr<float>(y);
-                float* nextDepthRow = depthMatrix.ptr<float>(y + 1);
-                float* areaRow = areaMatrix.ptr<float>(y);
-                float* areaSqrtRow = areaSqrtMatrix.ptr<float>(y);
-
-                for (int x = 0; x < width - 1; x++)
-                {
-                    float area = 0;
-                    float depth1 = *depthRow;
-
-                    if (depth1 != 0)
-                    {
-                        cv::Point3f p1(x, y, depth1);
-                        cv::Point3f p2(x + 1, y, depth1);
-                        cv::Point3f p3(x, y + 1, depth1);
-                        cv::Point3f p4(x + 1, y + 1, depth1);
-
-                        area += get_depth_area(p1, p2, p3, mapper);
-                        area += get_depth_area(p2, p3, p4, mapper);
-                    }
-
-                    *areaRow = area;
-                    *areaSqrtRow = sqrt(area);
-
-                    ++depthRow;
-                    ++nextDepthRow;
-                    ++areaRow;
-                    ++areaSqrtRow;
-                }
-            }
-        }
-
-
-        float count_neighborhood_area(cv::Mat& segmentationMatrix,
-                                      cv::Mat& depthMatrix,
-                                      cv::Mat& areaMatrix,
-                                      const cv::Point& center,
-                                      const float bandwidth,
-                                      const float bandwidthDepth,
-                                      const ScalingCoordinateMapper& mapper)
-        {
-            if (center.x < 0 || center.y < 0 ||
-                center.x >= depthMatrix.cols || center.y >= depthMatrix.rows)
-            {
-                return 0;
-            }
-
-            float startingDepth = depthMatrix.at<float>(center);
-
-            cv::Point topLeft = offset_pixel_location_by_mm(mapper, center, -bandwidth, bandwidth, startingDepth);
-            cv::Point bottomRight = offset_pixel_location_by_mm(mapper, center, bandwidth, -bandwidth, startingDepth);
-
-            int32_t x0 = MAX(0, topLeft.x);
-            int32_t y0 = MAX(0, topLeft.y);
-            int32_t x1 = MIN(depthMatrix.cols - 1, bottomRight.x);
-            int32_t y1 = MIN(depthMatrix.rows - 1, bottomRight.y);
-
-            float area = 0;
-
-            for (int y = y0; y < y1; y++)
-            {
-                float* depthRow = depthMatrix.ptr<float>(y);
-                char* segmentationRow = segmentationMatrix.ptr<char>(y);
-                float* areaRow = areaMatrix.ptr<float>(y);
-
-                depthRow += x0;
-                segmentationRow += x0;
-                areaRow += x0;
-                for (int x = x0; x < x1; x++)
-                {
-                    if (*segmentationRow == PixelType::Foreground)
-                    {
-                        float depth = *depthRow;
-                        if (std::fabs(depth - startingDepth) < bandwidthDepth)
+                        nextSearchStart.x = 0;
+                        nextSearchStart.y = y + 1;
+                        if (nextSearchStart.y >= height)
                         {
-                            area += *areaRow;
+                            return false;
                         }
                     }
-                    ++depthRow;
-                    ++areaRow;
-                    ++segmentationRow;
-                }
-            }
-
-            return area;
-        }
-    }
-
-}}}
+                    return true;
+                }
+            }
+        }
+        foregroundPosition.x = -1;
+        foregroundPosition.y = -1;
+        nextSearchStart.x = width;
+        nextSearchStart.y = height;
+        return false;
+    }
+
+    void calculate_basic_score(cv::Mat& depthMatrix,
+                                cv::Mat& scoreMatrix,
+                                const float heightFactor,
+                                const float depthFactor,
+                                const ScalingCoordinateMapper& mapper)
+    {
+        scoreMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
+
+        int width = depthMatrix.cols;
+        int height = depthMatrix.rows;
+
+        for (int y = 0; y < height; y++)
+        {
+            float* depthRow = depthMatrix.ptr<float>(y);
+            float* scoreRow = scoreMatrix.ptr<float>(y);
+
+            for (int x = 0; x < width; x++)
+            {
+                float depth = *depthRow;
+                if (depth != 0)
+                {
+                    cv::Point3f worldPosition = mapper.convert_depth_to_world(x, y, depth);
+
+                    float score = 0;
+                    score += worldPosition.y * heightFactor;
+                    score += (MAX_DEPTH - worldPosition.z) * depthFactor;
+
+                    *scoreRow = score;
+                }
+                else
+                {
+                    *scoreRow = 0;
+                }
+                ++depthRow;
+                ++scoreRow;
+            }
+        }
+    }
+
+    void calculate_edge_distance(cv::Mat& segmentationMatrix,
+                                    cv::Mat& areaSqrtMatrix,
+                                    cv::Mat& edgeDistanceMatrix)
+    {
+        cv::Mat eroded;
+        cv::Mat crossElement = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(3, 3));
+
+        edgeDistanceMatrix = cv::Mat::zeros(segmentationMatrix.size(), CV_32FC1);
+        cv::Mat ones = cv::Mat::ones(segmentationMatrix.size(), CV_32FC1);
+        segmentationMatrix.copyTo(eroded);
+
+        //close small holes
+        int dilateCount = 1;
+        for (int i = 0; i < dilateCount; i++)
+        {
+            cv::dilate(eroded, eroded, crossElement);
+        }
+
+        int nonZeroCount = 0;
+        const int imageLength = eroded.cols * eroded.rows;
+        int iterations = 0;
+        const int maxIterations = segmentationMatrix.cols / 2;
+        bool done;
+        do
+        {
+            //erode makes the image smaller
+            cv::erode(eroded, eroded, crossElement);
+            //accumulate the eroded image to the edgeDistance buffer
+            cv::add(areaSqrtMatrix, edgeDistanceMatrix, edgeDistanceMatrix, eroded, CV_32FC1);
+
+            nonZeroCount = cv::countNonZero(eroded);
+            done = (nonZeroCount == 0);
+
+            //nonZeroCount < imageLength guards against segmentation with all 1's, which will never erode
+        } while (!done && nonZeroCount < imageLength && ++iterations < maxIterations);
+    }
+
+    static float get_depth_area(cv::Point3f& p1,
+                                cv::Point3f& p2,
+                                cv::Point3f& p3,
+                                const ScalingCoordinateMapper& mapper)
+    {
+        cv::Point3f world1 = mapper.convert_depth_to_world(p1);
+        cv::Point3f world2 = mapper.convert_depth_to_world(p2);
+        cv::Point3f world3 = mapper.convert_depth_to_world(p3);
+
+        cv::Point3f v1 = world2 - world1;
+        cv::Point3f v2 = world3 - world1;
+
+        float area = static_cast<float>(0.5 * cv::norm(v1.cross(v2)));
+        return area;
+    }
+
+    void calculate_segment_area(cv::Mat& depthMatrix, cv::Mat& areaMatrix, cv::Mat& areaSqrtMatrix, const ScalingCoordinateMapper& mapper)
+    {
+        int width = depthMatrix.cols;
+        int height = depthMatrix.rows;
+
+        areaMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
+        areaSqrtMatrix = cv::Mat::zeros(depthMatrix.size(), CV_32FC1);
+
+        for (int y = 0; y < height - 1; y++)
+        {
+            float* depthRow = depthMatrix.ptr<float>(y);
+            float* nextDepthRow = depthMatrix.ptr<float>(y + 1);
+            float* areaRow = areaMatrix.ptr<float>(y);
+            float* areaSqrtRow = areaSqrtMatrix.ptr<float>(y);
+
+            for (int x = 0; x < width - 1; x++)
+            {
+                float area = 0;
+                float depth1 = *depthRow;
+
+                if (depth1 != 0)
+                {
+                    cv::Point3f p1(x, y, depth1);
+                    cv::Point3f p2(x + 1, y, depth1);
+                    cv::Point3f p3(x, y + 1, depth1);
+                    cv::Point3f p4(x + 1, y + 1, depth1);
+
+                    area += get_depth_area(p1, p2, p3, mapper);
+                    area += get_depth_area(p2, p3, p4, mapper);
+                }
+
+                *areaRow = area;
+                *areaSqrtRow = sqrt(area);
+
+                ++depthRow;
+                ++nextDepthRow;
+                ++areaRow;
+                ++areaSqrtRow;
+            }
+        }
+    }
+
+
+    float count_neighborhood_area(cv::Mat& segmentationMatrix,
+                                    cv::Mat& depthMatrix,
+                                    cv::Mat& areaMatrix,
+                                    const cv::Point& center,
+                                    const float bandwidth,
+                                    const float bandwidthDepth,
+                                    const ScalingCoordinateMapper& mapper)
+    {
+        if (center.x < 0 || center.y < 0 ||
+            center.x >= depthMatrix.cols || center.y >= depthMatrix.rows)
+        {
+            return 0;
+        }
+
+        float startingDepth = depthMatrix.at<float>(center);
+
+        cv::Point topLeft = offset_pixel_location_by_mm(mapper, center, -bandwidth, bandwidth, startingDepth);
+        cv::Point bottomRight = offset_pixel_location_by_mm(mapper, center, bandwidth, -bandwidth, startingDepth);
+
+        int32_t x0 = MAX(0, topLeft.x);
+        int32_t y0 = MAX(0, topLeft.y);
+        int32_t x1 = MIN(depthMatrix.cols - 1, bottomRight.x);
+        int32_t y1 = MIN(depthMatrix.rows - 1, bottomRight.y);
+
+        float area = 0;
+
+        for (int y = y0; y < y1; y++)
+        {
+            float* depthRow = depthMatrix.ptr<float>(y);
+            char* segmentationRow = segmentationMatrix.ptr<char>(y);
+            float* areaRow = areaMatrix.ptr<float>(y);
+
+            depthRow += x0;
+            segmentationRow += x0;
+            areaRow += x0;
+            for (int x = x0; x < x1; x++)
+            {
+                if (*segmentationRow == PixelType::Foreground)
+                {
+                    float depth = *depthRow;
+                    if (std::fabs(depth - startingDepth) < bandwidthDepth)
+                    {
+                        area += *areaRow;
+                    }
+                }
+                ++depthRow;
+                ++areaRow;
+                ++segmentationRow;
+            }
+        }
+
+        return area;
+    }
+
+}}}}


KitModel: Fix crash on removing kits introduced in 7fd21d22a

Removing a kit removes the item from the TreeModel and puts it into
KitModel::m_toRemoveList. A later update to that kit would trigger
the lambda connected to the dirty signal, thus calling node->update(),
which eventually ends up calling node->parent()->m_children, and
node->parent() is a null pointer there.

Change-Id: I9006f1eea036ae99b48a47baa2bc2a33bdcb84b1
Reviewed-by: hjk <4622a3e4640ee19ab4ebad197849e45b7170d50c@theqtcompany.com>

--- src/plugins/projectexplorer/kitmodel.cpp
+++ src/plugins/projectexplorer/kitmodel.cpp
@@ -259,8 +259,10 @@
 {
     KitNode *node = new KitNode(k);
     m_parentLayout->addWidget(node->widget);
-    connect(node->widget, &KitManagerConfigWidget::dirty, [node] {
-        node->update();
+    connect(node->widget, &KitManagerConfigWidget::dirty, [this, node] {
+        if (m_autoRoot->children().contains(node)
+                || m_manualRoot->children().contains(node))
+            node->update();
     });
     return node;
 }


Change sort order of maps from hasBBox/name to hasBBox/area. This has the advantage that smaller maps are automatically preferred, which is useful for overlapping maps (e.g. baden-wurttemberg vs germany vs europe) to prefer the smaller map and only fall back to the larger (slower) one if really needed.

svn path=/trunk/KDE/kdeedu/marble/; revision=1184464

--- src/plugins/runner/monav/MonavPlugin.cpp
+++ src/plugins/runner/monav/MonavPlugin.cpp
@@ -66,7 +66,7 @@

     void loadMaps();

-    static bool bordersFirst( const MonavMap &first, const MonavMap &second );
+    static bool areaLessThan( const MonavMap &first, const MonavMap &second );

 private:
     void loadMap( const QString &path );
@@ -200,7 +200,7 @@
         loadMap( iter.filePath() );
     }
     // Prefer maps where bounding boxes are known
-    qSort( m_maps.begin(), m_maps.end(), MonavPluginPrivate::bordersFirst );
+    qSort( m_maps.begin(), m_maps.end(), MonavPluginPrivate::areaLessThan );
 }

 void MonavPluginPrivate::loadMap( const QString &path )
@@ -214,7 +214,7 @@
     }
 }

-bool MonavPluginPrivate::bordersFirst( const MonavMap &first, const MonavMap &second )
+bool MonavPluginPrivate::areaLessThan( const MonavMap &first, const MonavMap &second )
 {
     if ( !first.m_tiles.isEmpty() && second.m_tiles.isEmpty() ) {
         return true;
@@ -224,7 +224,9 @@
         return false;
     }

-    return first.m_directory.absolutePath() < second.m_directory.absolutePath();
+    qreal const areaOne = first.m_boundingBox.width() * first.m_boundingBox.height();
+    qreal const areaTwo = second.m_boundingBox.width() * second.m_boundingBox.height();
+    return areaOne < areaTwo;
 }

 MonavPlugin::MonavPlugin( QObject *parent ) : RunnerPlugin( parent ), d( new MonavPluginPrivate )


Only compile freertos RRealtimeTimer when R_OS_FREERTOS defined

--- src/portable/freertos/RRealtimeTimer.cpp
+++ src/portable/freertos/RRealtimeTimer.cpp
@@ -1,3 +1,5 @@
+#ifdef R_OS_FREERTOS
+
 #include "RRealtimeTimer.h"
 #include "RScopedPointer.h"
 #include "RIsr.h"
@@ -217,3 +219,5 @@

   xTimerStart(self->mHandle, 0);
 }
+
+#endif // #ifdef R_OS_FREERTOS


Flip x values

Flip x values

--- src/position/tracking/TrackingWorker.cpp
+++ src/position/tracking/TrackingWorker.cpp
@@ -71,7 +71,7 @@

 			if (position.isValid()) {
 				// Invert x axis for controller
-				// position.setV1(-position.getV1());
+				position.setV1(-position.getV1());

 				std::vector<Vector> positions;
 				std::vector<int> ids;


Update validity checks for Exchange.

Update validity checks for Exchange.

--- src/problems/cvrp/operators/exchange.cpp
+++ src/problems/cvrp/operators/exchange.cpp
@@ -115,13 +115,19 @@
   bool valid = _input.vehicle_ok_with_job(t_vehicle, s_job_rank);
   valid &= _input.vehicle_ok_with_job(s_vehicle, t_job_rank);

-  valid &= (_sol_state.fwd_amounts[t_vehicle].back() -
-              _input.jobs[t_job_rank].amount + _input.jobs[s_job_rank].amount <=
-            _input.vehicles[t_vehicle].capacity);
+  valid &=
+    target.is_valid_addition_for_capacity(_input,
+                                          _input.jobs[s_route[s_rank]].pickup,
+                                          _input.jobs[s_route[s_rank]].delivery,
+                                          t_rank,
+                                          t_rank + 1);

-  valid &= (_sol_state.fwd_amounts[s_vehicle].back() -
-              _input.jobs[s_job_rank].amount + _input.jobs[t_job_rank].amount <=
-            _input.vehicles[s_vehicle].capacity);
+  valid &=
+    source.is_valid_addition_for_capacity(_input,
+                                          _input.jobs[t_route[t_rank]].pickup,
+                                          _input.jobs[t_route[t_rank]].delivery,
+                                          s_rank,
+                                          s_rank + 1);

   return valid;
 }


Update GetProgress.cpp

Update GetProgress.cpp

--- src/progress/WvUnpackDec/GetProgress.cpp
+++ src/progress/WvUnpackDec/GetProgress.cpp
@@ -1,20 +1,5 @@
-//
-// BatchEncoder - GetProgress WvUnpackDec
-// Copyright (C) 2005-2017 Wiesław Šoltés <wieslaw.soltes@gmail.com>
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; version 2 of the License.
-//
-// This program 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 this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-//
+// Copyright (c) Wiesław Šoltés. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.

 #include <stdio.h>
 #include <stdlib.h>


Fix redundant std::move(). (#49)

Fix redundant std::move(). (#49)

This commit removes the following warnings.

redisclient/src/redisclient/impl/redisclientimpl.cpp:263:24:
warning: moving a temporary object prevents copy elision
[-Wpessimizing-move]

data.push_back(std::move(makeCommand(command)));
               ^

--- src/redisclient/impl/redisclientimpl.cpp
+++ src/redisclient/impl/redisclientimpl.cpp
@@ -260,7 +260,7 @@

     for(const auto &command: commands)
     {
-        data.push_back(std::move(makeCommand(command)));
+        data.push_back(makeCommand(command));
         buffers.push_back(boost::asio::buffer(data.back()));
     }

@@ -276,7 +276,7 @@

     for(size_t i = 0; i < commands.size(); ++i)
     {
-        responses.push_back(std::move(syncReadResponse()));
+        responses.push_back(syncReadResponse());
     }

     return RedisValue(std::move(responses));
@@ -348,7 +348,7 @@

         if( result.second == RedisParser::Completed )
         {
-            doProcessMessage(std::move(redisParser.result()));
+            doProcessMessage(redisParser.result());
         }
         else if( result.second == RedisParser::Incompleted )
         {
@@ -437,8 +437,8 @@
     }
 }

-void RedisClientImpl::unsubscribe(const std::string &command,
-                                  size_t handleId,
+void RedisClientImpl::unsubscribe(const std::string &command,
+                                  size_t handleId,
                                   const std::string &channel,
                                   std::function<void(RedisValue)> handler)
 {


Put const on some locals in gimme_some_new_offsets and many_writes.

--- src/serializer/log/data_block_manager.cc
+++ src/serializer/log/data_block_manager.cc
@@ -391,40 +391,40 @@
         iocallback_t *cb;
     };

-    intermediate_cb_t *intermediate_cb = new intermediate_cb_t;
+    intermediate_cb_t *const intermediate_cb = new intermediate_cb_t;
     intermediate_cb->ops_remaining = token_groups.size();
     intermediate_cb->bufs.init(token_groups.size());
     intermediate_cb->cb = cb;

     size_t write_number = 0;
     for (size_t i = 0; i < token_groups.size(); ++i) {
-        int64_t front_offset = token_groups[i].front()->offset();
-        int64_t back_offset = token_groups[i].back()->offset()
+        const int64_t front_offset = token_groups[i].front()->offset();
+        const int64_t back_offset = token_groups[i].back()->offset()
             + token_groups[i].back()->ser_block_size();

         guarantee(divides(DEVICE_BLOCK_SIZE, front_offset));

-        int64_t write_size = ceil_aligned(back_offset - front_offset, DEVICE_BLOCK_SIZE);
+        const int64_t write_size = ceil_aligned(back_offset - front_offset,
+                                                DEVICE_BLOCK_SIZE);

         scoped_malloc_t<char> buf(malloc_aligned(write_size, DEVICE_BLOCK_SIZE));

-        // Used to zero out unused portions of the buf, so that we don't write undefined
-        // data (arbitrary contents of memory) to disk.
+        // Used to zero out unused portions of the buf, so that we don't write
+        // undefined data (arbitrary contents of memory) to disk.
         int64_t last_written_offset = front_offset;

         for (auto it = token_groups[i].begin(); it != token_groups[i].end(); ++it) {
-            int64_t it_offset = (*it)->offset();
-            uint32_t it_ser_block_size = (*it)->ser_block_size();
+            const int64_t it_offset = (*it)->offset();
+            const uint32_t it_ser_block_size = (*it)->ser_block_size();
             guarantee(it_offset >= last_written_offset);

-            buf_write_info_t the_write = writes[write_number];
-            // The behavior of gimme_some_new_offsets is supposed to retain order, so we
-            // expect writes[write_number] to have the currently-relevant write.
-            guarantee(the_write.ser_block_size == it_ser_block_size);
+            // The behavior of gimme_some_new_offsets is supposed to retain order, so
+            // we expect writes[write_number] to have the currently-relevant write.
+            guarantee(writes[write_number].ser_block_size == it_ser_block_size);

             memset(buf.get() + (last_written_offset - front_offset), 0,
                    it_offset - last_written_offset);
-            memcpy(buf.get() + (it_offset - front_offset), the_write.buf,
+            memcpy(buf.get() + (it_offset - front_offset), writes[write_number].buf,
                    it_ser_block_size);

             last_written_offset = it_offset + it_ser_block_size;
@@ -927,7 +927,6 @@
         ++stats->pm_serializer_data_extents_allocated;
     }

-    std::vector<std::vector<counted_t<ls_block_token_pointee_t> > > ret;

     // RSI: Make sure that file async write calls and read calls use spawn_ordered
     // or whatever order-preserving cross-thread communication is necessary.  SIGH.
@@ -936,6 +935,8 @@
     guarantee(active_extent->state == gc_entry_t::state_active);

     bool align_to_device_block_size = true;
+
+    std::vector<std::vector<counted_t<ls_block_token_pointee_t> > > ret;

     std::vector<counted_t<ls_block_token_pointee_t> > tokens;
     for (auto it = writes.begin(); it != writes.end(); ++it) {
@@ -966,7 +967,7 @@

         align_to_device_block_size = false;

-        int64_t offset = active_extent->extent_ref.offset() + relative_offset;
+        const int64_t offset = active_extent->extent_ref.offset() + relative_offset;
         active_extent->was_written = true;
         active_extent->mark_live_tokenwise(block_index);


- debug prints

- debug prints

--- src/shogun/machine/MulticlassMachine.cpp
+++ src/shogun/machine/MulticlassMachine.cpp
@@ -151,8 +151,6 @@
 	{
 		for (int32_t j=i+1; j<num_classes; j++)
 		{
-			/** TODO fix this, there must be a way not to allocate these guys on every
-			 * iteration */
 			SGVector<index_t> subset_labels(num_vectors);
 			SGVector<index_t> subset_feats(num_vectors);

@@ -185,8 +183,6 @@
 			remove_machine_subset();
 		}
 	}
-
-	SG_PRINT(">>>> at the end of training num_machines = %d\n", get_num_machines());

 	SG_UNREF(train_labels);
 	return true;
@@ -257,8 +253,6 @@
 {
 	int32_t num_classes  = m_labels->get_num_classes();
 	int32_t num_machines = get_num_machines();
-	SG_PRINT(">>>> at the beginning of classify num_machines = %d\n", num_machines);
-	SG_PRINT(">>>> at the beginning of classify num_classes = %d\n",  num_classes);
 	if ( num_machines != num_classes*(num_classes-1)/2 )
 		SG_ERROR("Dimension mismatch in classify_one_vs_one between number \
 			of machines = %d and number of classes = %d\n", num_machines,
@@ -281,8 +275,6 @@
 			outputs[i]=m_machines[i]->apply();
 		}

-		SG_PRINT(">>>> Starting to go through the vectors\n");
-
 		SGVector<float64_t> votes(num_classes);
 		for (int32_t v=0; v<num_vectors; v++)
 		{
@@ -293,7 +285,6 @@
 			{
 				for (int32_t j=i+1; j<num_classes; j++)
 				{
-					SG_PRINT(">>>> s = %d v  = %d\n", s, v);
 					if ( ! outputs[s] )
 						SG_ERROR(">>>>>> outputs[%d] is null!!!\n", s);
 					if (outputs[s++]->get_label(v)>0)
@@ -303,7 +294,6 @@
 				}
 			}

-			SG_PRINT(">>>> votes counted\n");

 			int32_t winner=0;
 			int32_t max_votes=votes[0];
@@ -317,11 +307,9 @@
 				}
 			}

-			SG_PRINT(">>>> max_votes found\n");
 			result->set_label(v, winner);
 		}

-		SG_PRINT(">>>> Destroy votes\n");
 		votes.destroy_vector();

 		for (int32_t i=0; i<num_machines; i++)


cleanup namespace

cleanup namespace

--- secp256k1.cc
+++ secp256k1.cc
@@ -3,16 +3,7 @@
 #include <node.h>

 #include "./secp256k1-src/include/secp256k1.h"
-using v8::Function;
-using v8::Local;
-using v8::Number;
-using v8::Boolean;
-using v8::Value;
-using v8::Object;
-using Nan::AsyncWorker;
-using Nan::Callback;
-using Nan::HandleScope;
-using Nan::New;
+using namespace v8;

 /* secp256k1ctx context to be used for calling secp256k1 functions; it is safe
  * to use same context across all of the calls in this wrapper, as per comment
@@ -52,11 +43,11 @@

 //Create a async Signature
-class SignWorker : public AsyncWorker {
+class SignWorker : public Nan::AsyncWorker {
  public:
   // Constructor
-  SignWorker(Callback *callback, const unsigned char *msg32, const unsigned char *seckey, bool DER=false)
-    : AsyncWorker(callback), msg32(msg32), seckey(seckey), DER(DER) {}
+  SignWorker(Nan::Callback *callback, const unsigned char *msg32, const unsigned char *seckey, bool DER=false)
+    : Nan::AsyncWorker(callback), msg32(msg32), seckey(seckey), DER(DER) {}
   // Destructor
   ~SignWorker() {}

@@ -72,7 +63,7 @@
   // this function will be run inside the main event loop
   // so it is safe to use V8 again
   void HandleOKCallback () {
-    HandleScope scope;
+    Nan::HandleScope scope;

     char* output;
     int outputlen;
@@ -81,9 +72,9 @@
     serialize_sig(DER, output, &outputlen, &recid, &sig);

     Local<Value> argv[3] = {
-      New<Number>(result),
+      Nan::New<Number>(result),
       node::Buffer::New(output, outputlen),
-      New<Number>(recid)
+      Nan::New<Number>(recid)
     };

     delete output;
@@ -99,11 +90,11 @@
 };

 //recover's the public key from a signature
-class RecoverWorker : public AsyncWorker {
+class RecoverWorker : public Nan::AsyncWorker {
  public:
   // Constructor
-  RecoverWorker(Callback *callback, const unsigned char *msg32, secp256k1_ecdsa_signature_t *sig, int compressed=true)
-    : AsyncWorker(callback), msg32(msg32), sig(sig), compressed(compressed) {}
+  RecoverWorker(Nan::Callback *callback, const unsigned char *msg32, secp256k1_ecdsa_signature_t *sig, int compressed=true)
+    : Nan::AsyncWorker(callback), msg32(msg32), sig(sig), compressed(compressed) {}
   // Destructor
   ~RecoverWorker() {
     delete sig;
@@ -114,7 +105,7 @@
   }

   void HandleOKCallback () {
-    HandleScope scope;
+    Nan::HandleScope scope;

     unsigned char output[65];
     int outputlen;
@@ -122,7 +113,7 @@
     secp256k1_ec_pubkey_serialize(secp256k1ctx, output, &outputlen, &pubkey, compressed);

     Local<Value> argv[] = {
-      New<Number>(result),
+      Nan::New<Number>(result),
       node::Buffer::New((char *)output, outputlen)
     };
     callback->Call(2, argv);
@@ -136,11 +127,11 @@
   int result;
 };

-class VerifyWorker : public AsyncWorker {
+class VerifyWorker : public Nan::AsyncWorker {
  public:
   // Constructor
-  VerifyWorker(Callback *callback, const unsigned char *msg32, secp256k1_ecdsa_signature_t *sig, secp256k1_pubkey_t *pubkey)
-    : AsyncWorker(callback), msg32(msg32), sig(sig), pubkey(pubkey) {}
+  VerifyWorker(Nan::Callback *callback, const unsigned char *msg32, secp256k1_ecdsa_signature_t *sig, secp256k1_pubkey_t *pubkey)
+    : Nan::AsyncWorker(callback), msg32(msg32), sig(sig), pubkey(pubkey) {}
   // Destructor
   ~VerifyWorker() {
     delete sig;
@@ -152,9 +143,9 @@
   }

   void HandleOKCallback () {
-    HandleScope scope;
+    Nan::HandleScope scope;
     Local<Value> argv[] = {
-      New<Number>(result),
+      Nan::New<Number>(result),
     };
     callback->Call(1, argv);
   }
@@ -167,7 +158,7 @@
 };

 NAN_METHOD(Verify){
-  HandleScope scope;
+  Nan::HandleScope scope;

   //parse the argments
   const unsigned char *pubkey_data = (unsigned char *) node::Buffer::Data(info[0].As<Object>());
@@ -191,10 +182,10 @@
     int result = secp256k1_ecdsa_verify(secp256k1ctx, msg_data, sig, pubkey);
     delete sig;
     delete pubkey;
-    info.GetReturnValue().Set(New<Boolean>(result));
+    info.GetReturnValue().Set(Nan::New<Boolean>(result));
   }else{
     //if there is a callback run asyc version
-    Callback *nanCallback = new Callback(info[5].As<Function>());
+    Nan::Callback *nanCallback = new Nan::Callback(info[5].As<Function>());
     VerifyWorker *worker = new VerifyWorker(nanCallback, msg_data, sig, pubkey);
     Nan::AsyncQueueWorker(worker);
     info.GetReturnValue().SetUndefined();
@@ -202,7 +193,7 @@
 }

 NAN_METHOD(Sign){
-  HandleScope scope;
+  Nan::HandleScope scope;

   //the message that we are signing
   const unsigned char *msg_data = (unsigned char *) node::Buffer::Data(info[0].As<Object>());
@@ -221,9 +212,9 @@

       serialize_sig(DER, output, &outputlen, &recid, &sig);

-      Local<v8::Array> results = New<v8::Array>();
+      Local<Array> results = Nan::New<Array>();
       results->Set(0, node::Buffer::New(output, outputlen));
-      results->Set(1, New<Number>(recid));
+      results->Set(1, Nan::New<Number>(recid));

       delete output; //output was allocated by serialize_sig

@@ -233,7 +224,7 @@
     }
   }else{
     //if there is a callback run asyc version
-    Callback *nanCallback = new Callback(info[3].As<Function>());
+    Nan::Callback *nanCallback = new Nan::Callback(info[3].As<Function>());
     SignWorker* worker = new SignWorker(nanCallback, msg_data, seckey_data, DER);
     Nan::AsyncQueueWorker(worker);
     info.GetReturnValue().SetUndefined();
@@ -241,7 +232,7 @@
 }

 NAN_METHOD(Recover){
-  HandleScope scope;
+  Nan::HandleScope scope;

   const unsigned char *msg = (unsigned char *) node::Buffer::Data(info[0].As<Object>());
   Local<Object> sig_buf = info[1].As<Object>();
@@ -268,7 +259,7 @@
     }
   }else{
     //the callback
-    Callback* nanCallback = new Callback(info[5].As<Function>());
+    Nan::Callback* nanCallback = new Nan::Callback(info[5].As<Function>());
     RecoverWorker* worker = new RecoverWorker(nanCallback, msg, sig);
     Nan::AsyncQueueWorker(worker);
     info.GetReturnValue().SetUndefined();
@@ -276,15 +267,15 @@
 }

 NAN_METHOD(Seckey_Verify){
-  HandleScope scope;
+  Nan::HandleScope scope;

   const unsigned char *data = (const unsigned char*) node::Buffer::Data(info[0]);
   int result =  secp256k1_ec_seckey_verify(secp256k1ctx, data);
-  info.GetReturnValue().Set(New<Number>(result));
+  info.GetReturnValue().Set(Nan::New<Number>(result));
 }

 NAN_METHOD(Pubkey_Create){
-  HandleScope scope;
+  Nan::HandleScope scope;

   const unsigned char *seckey = (unsigned char *) node::Buffer::Data(info[0].As<Object>());
   int compressed = info[1]->IntegerValue();
@@ -302,7 +293,7 @@
 }

 NAN_METHOD(Privkey_Import){
-  HandleScope scope;
+  Nan::HandleScope scope;

   //the first argument should be the private key as a buffer
   Local<Object> privkey_buf = info[0].As<Object>();
@@ -321,7 +312,7 @@
 }

 NAN_METHOD(Privkey_Export){
-  HandleScope scope;
+  Nan::HandleScope scope;

   const unsigned char *seckey = (unsigned char *) node::Buffer::Data(info[0].As<Object>());
   const int compressed = info[1]->IntegerValue();
@@ -337,7 +328,7 @@
 }

 NAN_METHOD(Privkey_Tweak_Add){
-  HandleScope scope;
+  Nan::HandleScope scope;

   //the first argument should be the private key as a buffer
   unsigned char *seckey = (unsigned char *) node::Buffer::Data(info[0].As<Object>());
@@ -352,7 +343,7 @@
 }

 NAN_METHOD(Privkey_Tweak_Mul){
-  HandleScope scope;
+  Nan::HandleScope scope;

   //the first argument should be the private key as a buffer
   unsigned char *seckey = (unsigned char *) node::Buffer::Data(info[0].As<Object>());
@@ -367,7 +358,7 @@
 }

 NAN_METHOD(Pubkey_Tweak_Add){
-  HandleScope scope;
+  Nan::HandleScope scope;

   //the first argument should be the private key as a buffer
   Local<Object> pk_buf = info[0].As<Object>();
@@ -388,7 +379,7 @@
 }

 NAN_METHOD(Pubkey_Tweak_Mul){
-  HandleScope scope;
+  Nan::HandleScope scope;

   //the first argument should be the private key as a buffer
   Local<Object> pk_buf = info[0].As<Object>();
@@ -411,16 +402,16 @@
 NAN_MODULE_INIT(Init){
   secp256k1ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);

-  Nan::Set(target, New<v8::String>("sign").ToLocalChecked(), New<v8::FunctionTemplate>(Sign)->GetFunction());
-  Nan::Set(target, New<v8::String>("recover").ToLocalChecked(), New<v8::FunctionTemplate>(Recover)->GetFunction());
-  Nan::Set(target, New<v8::String>("verify").ToLocalChecked(), New<v8::FunctionTemplate>(Verify)->GetFunction());
-  Nan::Set(target, New<v8::String>("secKeyVerify").ToLocalChecked(), New<v8::FunctionTemplate>(Seckey_Verify)->GetFunction());
-  Nan::Set(target, New<v8::String>("pubKeyCreate").ToLocalChecked(), New<v8::FunctionTemplate>(Pubkey_Create)->GetFunction());
-  Nan::Set(target, New<v8::String>("privKeyExport").ToLocalChecked(), New<v8::FunctionTemplate>(Privkey_Export)->GetFunction());
-  Nan::Set(target, New<v8::String>("privKeyImport").ToLocalChecked(), New<v8::FunctionTemplate>(Privkey_Import)->GetFunction());
-  Nan::Set(target, New<v8::String>("privKeyTweakAdd").ToLocalChecked(), New<v8::FunctionTemplate>(Privkey_Tweak_Add)->GetFunction());
-  Nan::Set(target, New<v8::String>("privKeyTweakMul").ToLocalChecked(), New<v8::FunctionTemplate>(Privkey_Tweak_Mul)->GetFunction());
-  Nan::Set(target, New<v8::String>("pubKeyTweakAdd").ToLocalChecked(), New<v8::FunctionTemplate>(Pubkey_Tweak_Add)->GetFunction());
-  Nan::Set(target, New<v8::String>("pubKeyTweakMul").ToLocalChecked(), New<v8::FunctionTemplate>(Pubkey_Tweak_Mul)->GetFunction());
+  Nan::Set(target, Nan::New<String>("sign").ToLocalChecked(), Nan::New<FunctionTemplate>(Sign)->GetFunction());
+  Nan::Set(target, Nan::New<String>("recover").ToLocalChecked(), Nan::New<FunctionTemplate>(Recover)->GetFunction());
+  Nan::Set(target, Nan::New<String>("verify").ToLocalChecked(), Nan::New<FunctionTemplate>(Verify)->GetFunction());
+  Nan::Set(target, Nan::New<String>("secKeyVerify").ToLocalChecked(), Nan::New<FunctionTemplate>(Seckey_Verify)->GetFunction());
+  Nan::Set(target, Nan::New<String>("pubKeyCreate").ToLocalChecked(), Nan::New<FunctionTemplate>(Pubkey_Create)->GetFunction());
+  Nan::Set(target, Nan::New<String>("privKeyExport").ToLocalChecked(), Nan::New<FunctionTemplate>(Privkey_Export)->GetFunction());
+  Nan::Set(target, Nan::New<String>("privKeyImport").ToLocalChecked(), Nan::New<FunctionTemplate>(Privkey_Import)->GetFunction());
+  Nan::Set(target, Nan::New<String>("privKeyTweakAdd").ToLocalChecked(), Nan::New<FunctionTemplate>(Privkey_Tweak_Add)->GetFunction());
+  Nan::Set(target, Nan::New<String>("privKeyTweakMul").ToLocalChecked(), Nan::New<FunctionTemplate>(Privkey_Tweak_Mul)->GetFunction());
+  Nan::Set(target, Nan::New<String>("pubKeyTweakAdd").ToLocalChecked(), Nan::New<FunctionTemplate>(Pubkey_Tweak_Add)->GetFunction());
+  Nan::Set(target, Nan::New<String>("pubKeyTweakMul").ToLocalChecked(), Nan::New<FunctionTemplate>(Pubkey_Tweak_Mul)->GetFunction());
 }
 NODE_MODULE(secp256k1, Init)


utility.hpp missed std utility header

utility.hpp missed std utility header

--- utility.hpp
+++ utility.hpp
@@ -1,6 +1,7 @@
 #ifndef HMLIB_UTILITY_INC
 #define HMLIB_UTILITY_INC 100
 #
+#include<utility>
 /*===utility===
 主にオブジェクトの操作等に関わる汎用クラス/マクロ類を宣言する


Fix usage message of map_builder_server_main.cc (#1302)

--- cartographer/cloud/map_builder_server_main.cc
+++ cartographer/cloud/map_builder_server_main.cc
@@ -75,7 +75,7 @@
   google::ParseCommandLineFlags(&argc, &argv, true);
   if (FLAGS_configuration_directory.empty() ||
       FLAGS_configuration_basename.empty()) {
-    google::ShowUsageWithFlagsRestrict(argv[0], "cloud_server");
+    google::ShowUsageWithFlagsRestrict(argv[0], "map_builder_server");
     return EXIT_FAILURE;
   }
   cartographer::cloud::Run(FLAGS_configuration_directory,


Don't leak cfgfile handle when reading settings file.

--- settings.cpp
+++ settings.cpp
@@ -22,6 +22,7 @@
 #include <string_theory/stdio>
 #include <vector>
 #include <cstdio>
+#include <memory>

 /* Constants configured via CMake */
 uint32_t DS::Settings::BranchId()
@@ -115,7 +116,7 @@
     else
         s_settings.m_settingsPath = ".";

-    FILE* cfgfile = fopen(filename.c_str(), "r");
+    std::unique_ptr<FILE, decltype(&fclose)> cfgfile(fopen(filename.c_str(), "r"), &fclose);
     if (!cfgfile) {
         ST::printf(stderr, "Cannot open {} for reading\n", filename);
         return false;
@@ -123,7 +124,7 @@

     {
         char buffer[4096];
-        while (fgets(buffer, 4096, cfgfile)) {
+        while (fgets(buffer, 4096, cfgfile.get())) {
             ST::string line = ST::string(buffer).before_first('#').trim();
             if (line.empty())
                 continue;
@@ -206,7 +207,6 @@
             }
         }
     }
-    fclose(cfgfile);
     return true;
 }


Fix Windows compile problem

Fix Windows compile problem

--- Libs/DICOM/Core/ctkDICOMDatabase.cpp
+++ Libs/DICOM/Core/ctkDICOMDatabase.cpp
@@ -239,7 +239,7 @@

   QSqlQuery fileExists ( d->Database );
   fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == ?");
-  fileExists.bindValue(0,QString::fromStdString(sopInstanceUID));
+  fileExists.bindValue(0,QString(sopInstanceUID.c_str()));
   fileExists.exec();
   if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
     {


Fixed an error in get_CTML_Tree() where the program wouldn't use the path where the file was found, but would assume the file was located in the current directory. This caused an empty ifstream to be send to build(), which then created an infinite loop (probably another error in build() that needs to be fixed).

--- Cantera/src/ct2ctml.cpp
+++ Cantera/src/ct2ctml.cpp
@@ -1,10 +1,19 @@
+/**
+ * @file ct2ctml.cpp
+ *
+ * $Author$
+ * $Revision$
+ * $Date$
+ */
+
+// Copyright 2001  California Institute of Technology
+
 #include "ct_defs.h"
 #include "ctexceptions.h"
 #include <fstream>
 #include <string>
 #include <stdlib.h>
 #include "ctml.h"
-#include "../../include/pypath.h"

 using namespace Cantera;

@@ -85,7 +94,9 @@
                 msg += "\nError in Python installation.";
             else
                 msg += "\nCheck error messages above for syntax errors.";
-            throw CanteraError("ct2ctml", "could not convert input file to CTML\n command line was: "+msg);
+            throw CanteraError("ct2ctml",
+			       "could not convert input file to CTML\n "
+			       "command line was: " + msg);
         }
     }

@@ -95,7 +106,7 @@
      * first.
      */
     void get_CTML_Tree(XML_Node* rootPtr, string file) {
-        string ff;
+        string ff, ext = "";

         // find the input file on the Cantera search path
         string inname = findInputFile(file);
@@ -106,15 +117,17 @@
          * Check whether or not the file is XML. If not, it will be first
          * processed with the preprocessor.
          */
-        int idot = file.find('.');
-        string ext = file.substr(idot,file.size());
+        string::size_type idot = inname.rfind('.');
+	if (idot != string::npos) {
+	  ext = inname.substr(idot, inname.size());
+	}
         if (ext != ".xml" && ext != ".ctml") {
-            ct2ctml(file.c_str());
-            ff = file.substr(0,idot)+".xml";
+	  ct2ctml(inname.c_str());
+	  ff = inname.substr(0,idot) + ".xml";
         }
-        else
-            ff = file;
-
+        else {
+	  ff = inname;
+	}
         ifstream fin(ff.c_str());
         rootPtr->build(fin);
         fin.close();


Fix problems with my previous patch (r70105) with gmock.

TBR=joi

Review URL: http://codereview.chromium.org/6010005

git-svn-id: http://src.chromium.org/svn/trunk/src@70138 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 86ae0735fd1bf825ad51bc8f756b305ed87674cb

--- chrome/browser/extensions/extension_uitest.cc
+++ chrome/browser/extensions/extension_uitest.cc
@@ -134,7 +134,7 @@
   EXPECT_CALL(*mock_, OnForwardMessageToExternalHost(
       _, keys::kAutomationOrigin, keys::kAutomationRequestTarget))
       .WillOnce(DoAll(
-        SaveArg<1>(&message_received),
+        SaveArg<0>(&message_received),
         InvokeWithoutArgs(
             CreateFunctor(&loop_, &TimedMessageLoopRunner::Quit))));

@@ -285,7 +285,7 @@
   EXPECT_CALL(*mock_, OnForwardMessageToExternalHost(
     _, keys::kAutomationOrigin, keys::kAutomationRequestTarget))
     .Times(2)
-    .WillRepeatedly(WithArgs<1>(Invoke(
+    .WillRepeatedly(WithArgs<0>(Invoke(
         CreateFunctor(this,
             &ExtensionTestRoundtripApiCall::CheckAndSendResponse))));

@@ -472,7 +472,7 @@

   EXPECT_CALL(*mock_, OnForwardMessageToExternalHost(
     _, keys::kAutomationOrigin, _))
-    .WillRepeatedly(WithArgs<1, 2>(Invoke(
+    .WillRepeatedly(WithArgs<0, 2>(Invoke(
         CreateFunctor(this,
             &ExtensionTestBrowserEvents::HandleMessageFromChrome))));


Save a few lines since I don't need a test fixture.  This was just silly oversight on my part due to not having written a new unittest in a while.

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@56 0039d316-1c4b-4281-b951-d872f2087c98

--- chrome/browser/google_url_tracker_unittest.cc
+++ chrome/browser/google_url_tracker_unittest.cc
@@ -30,9 +30,7 @@
 #include "chrome/browser/google_url_tracker.h"
 #include "testing/gtest/include/gtest/gtest.h"

-class GoogleURLTrackerTest : public testing::Test { };
-
-TEST_F(GoogleURLTrackerTest, CheckAndConvertURL) {
+TEST(GoogleURLTrackerTest, CheckAndConvertURL) {
   static const struct {
     const char* const source_url;
     const bool can_convert;


[Sync] Rename SVLOG to SDVLOG in sync_backend_host.cc

That's a more accurate name, since it uses DVLOG.

BUG=101424
TEST=

Review URL: http://codereview.chromium.org/8855002

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@114329 0039d316-1c4b-4281-b951-d872f2087c98

--- chrome/browser/sync/glue/sync_backend_host.cc
+++ chrome/browser/sync/glue/sync_backend_host.cc
@@ -55,7 +55,7 @@

 #define SLOG(severity) LOG(severity) << name_ << ": "

-#define SVLOG(verbose_level) DVLOG(verbose_level) << name_ << ": "
+#define SDVLOG(verbose_level) DVLOG(verbose_level) << name_ << ": "

 SyncBackendHost::SyncBackendHost(const std::string& name,
                                  Profile* profile,
@@ -146,7 +146,7 @@
 }

 void SyncBackendHost::StartSyncingWithServer() {
-  SVLOG(1) << "SyncBackendHost::StartSyncingWithServer called.";
+  SDVLOG(1) << "SyncBackendHost::StartSyncingWithServer called.";
   sync_thread_.message_loop()->PostTask(FROM_HERE,
       base::Bind(&SyncBackendHost::Core::DoStartSyncing, core_.get()));
 }
@@ -818,7 +818,7 @@

   host_->last_snapshot_.reset(snapshot);

-  SVLOG(1) << "Got snapshot " << snapshot->ToString();
+  SDVLOG(1) << "Got snapshot " << snapshot->ToString();

   const syncable::ModelTypeSet to_migrate =
       snapshot->syncer_status.types_needing_local_migration;
@@ -843,7 +843,7 @@
         snapshot->initial_sync_ended;
     const syncable::ModelTypeSet failed_configuration_types =
         Difference(added_types, initial_sync_ended);
-    SVLOG(1)
+    SDVLOG(1)
         << "Added types: "
         << syncable::ModelTypeSetToString(added_types)
         << ", configured types: "
@@ -971,8 +971,8 @@
   // complete, the configure_state_.ready_task_ is run via an
   // OnInitializationComplete notification.

-  SVLOG(1) << "Syncer in config mode. SBH executing "
-           << "FinishConfigureDataTypesOnFrontendLoop";
+  SDVLOG(1) << "Syncer in config mode. SBH executing "
+            << "FinishConfigureDataTypesOnFrontendLoop";

   if (pending_config_mode_state_->added_types.Empty() &&
       !core_->sync_manager()->InitialSyncEndedForAllEnabledTypes()) {
@@ -1000,7 +1000,7 @@
   // If we've added types, we always want to request a nudge/config (even if
   // the initial sync is ended), in case we could not decrypt the data.
   if (pending_config_mode_state_->added_types.Empty()) {
-    SVLOG(1) << "No new types added; calling ready_task directly";
+    SDVLOG(1) << "No new types added; calling ready_task directly";
     // No new types - just notify the caller that the types are available.
     const syncable::ModelTypeSet failed_configuration_types;
     pending_config_mode_state_->ready_task.Run(failed_configuration_types);
@@ -1018,9 +1018,8 @@
       // migraiton error for nigori during config.
       types_to_config.Put(syncable::NIGORI);
     }
-    SVLOG(1) << "Types "
-             << syncable::ModelTypeSetToString(types_to_config)
-            << " added; calling DoRequestConfig";
+    SDVLOG(1) << "Types " << syncable::ModelTypeSetToString(types_to_config)
+              << " added; calling DoRequestConfig";
     sync_thread_.message_loop()->PostTask(FROM_HERE,
          base::Bind(&SyncBackendHost::Core::DoRequestConfig,
                     core_.get(),
@@ -1075,7 +1074,7 @@
                  core_.get(), sync_thread_done_callback));
 }

-#undef SVLOG
+#undef SDVLOG

 #undef SLOG


Fix a bug that caused the site info bubble from a panel to be shown in a wrong location.

Before the fix, the bubble was shown under the location bar of the
main browser window, rather than the location bar of the panel.

The #ifdef'ed code was originally added in
http://src.chromium.org/viewvc/chrome?view=rev&revision=46627
to fix crosbug.com/2783, but the code is no longer necessary:

1. We no longer have an issue that causes the site info popup to be shown full screen. In fact, the site info is now shown as a bubble.
2. We no longer show the location bar for the content browser (Ctrl-O)

BUG=chromium-os:9022
TEST=confirmed that the location is fixed on the netbook.

Review URL: http://codereview.chromium.org/6168001

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@71025 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

--- chrome/browser/ui/views/frame/browser_view.cc
+++ chrome/browser/ui/views/frame/browser_view.cc
@@ -1198,10 +1198,6 @@
                                bool show_history) {
   gfx::NativeWindow parent = GetWindow()->GetNativeWindow();

-#if defined(OS_CHROMEOS)
-  parent = GetNormalBrowserWindowForBrowser(browser(), profile);
-#endif  // defined(OS_CHROMEOS)
-
   browser::ShowPageInfoBubble(parent, profile, url, ssl, show_history);
 }


[listview]
added +S flag to parseGroupState() to support selecting the whole group.
added /xdid -G [dname] [id] [gid] [+mask] [+state] command which takes the flags used in parseGroupState() in the +mask & +state.
The +mask sets the states you wish to change.
The +state sets the on/off status of them. eg: +C +C enabled collapsibility & +C + disables it.

git-svn-id: 9f6a531b1eccf48281891b884df4d15f0e1b68ac@1084 17a06da3-8c20-fa79-550f-e9588e724b77

--- Classes/dcxlistview.cpp
+++ Classes/dcxlistview.cpp
@@ -1902,8 +1902,19 @@
 		}
 		else
 			this->showErrorEx(NULL, TEXT("-H"), TEXT("Unknown flags %s"), input.gettok(5).to_chr());
-
-		return;
+	}
+	// xdid -G [NAME] [ID] [SWITCH] [GID] [+MASK] [+STATES]
+	else if (flags[TEXT('G')] && numtok == 6) {
+		const int gid = (int)input.gettok( 4 ).to_num();
+
+		if (ListView_HasGroup(this->m_Hwnd, gid)) {
+			const UINT iMask = this->parseGroupState( input.gettok( 5 ) );
+			const UINT iState = this->parseGroupState( input.gettok( 6 ) );
+
+			ListView_SetGroupState(this->m_Hwnd, gid, iMask, iState);
+		}
+		else
+			this->showErrorEx(NULL,TEXT("-G"), TEXT("Group doesn't exist: %d"), gid);
 	}
 	else
 		this->parseGlobalCommandRequest(input, flags);
@@ -2203,6 +2214,8 @@
 		iFlags |= LVGS_NOHEADER;
 	if ( xflags[TEXT('O')] )
 		iFlags |= LVGS_COLLAPSED;
+	if ( xflags[TEXT('S')] )
+		iFlags |= LVGS_SELECTED;

 	return iFlags;
 }


[Sync] UMA: log only datatypes explicitly listed on the sync prefs page

The sync UMA logging logic that is in place first checks to see if the sync config has changed before logging a user's choices. This logic was broken by the implicitly enabled preferences that are currently behind a flag, resulting in more logging than necessary.

This patch changes the UMA logging logic to include only the datatypes that are explicitly listed on the preferences page. It also does the actual logging prior to applying the config via OnUserConfigured(), and adds extra checks that will remind anyone who adds a new datatype to also add UMA logging for the datatype.

BUG=96507
TEST=Change your sync config in a bunch of ways and look at about:histograms

Review URL: http://codereview.chromium.org/8566023

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@110028 0039d316-1c4b-4281-b951-d872f2087c98

--- chrome/browser/ui/webui/sync_setup_handler.cc
+++ chrome/browser/ui/webui/sync_setup_handler.cc
@@ -174,6 +174,11 @@
                              Profile* profile) {
   CHECK(profile);

+  // This function must be updated every time a new sync datatype is added to
+  // the sync preferences page.
+  COMPILE_ASSERT(17 == syncable::MODEL_TYPE_COUNT,
+                 UpdateCustomConfigHistogram);
+
   // If service is null or if this is a first time configuration, return true.
   ProfileSyncService* service = profile->GetProfileSyncService();
   if (!service || !service->HasSyncSetupCompleted())
@@ -193,6 +198,8 @@
       pref_service->GetBoolean(prefs::kSyncKeepEverythingSynced))
     return true;

+  // Only check the data types that are explicitly listed on the sync
+  // preferences page.
   const syncable::ModelTypeSet& types = config.data_types;
   if (((types.find(syncable::BOOKMARKS) != types.end()) !=
        pref_service->GetBoolean(prefs::kSyncBookmarks)) ||
@@ -206,16 +213,12 @@
        pref_service->GetBoolean(prefs::kSyncAutofill)) ||
       ((types.find(syncable::EXTENSIONS) != types.end()) !=
        pref_service->GetBoolean(prefs::kSyncExtensions)) ||
-      ((types.find(syncable::EXTENSION_SETTINGS) != types.end()) !=
-       pref_service->GetBoolean(prefs::kSyncExtensionSettings)) ||
       ((types.find(syncable::TYPED_URLS) != types.end()) !=
        pref_service->GetBoolean(prefs::kSyncTypedUrls)) ||
       ((types.find(syncable::SESSIONS) != types.end()) !=
        pref_service->GetBoolean(prefs::kSyncSessions)) ||
       ((types.find(syncable::APPS) != types.end()) !=
-       pref_service->GetBoolean(prefs::kSyncApps)) ||
-      ((types.find(syncable::APP_SETTINGS) != types.end()) !=
-       pref_service->GetBoolean(prefs::kSyncAppSettings)))
+       pref_service->GetBoolean(prefs::kSyncApps)))
     return true;

   return false;
@@ -555,6 +558,44 @@
     return;
   }

+  // We do not do UMA logging during unit tests.
+  if (web_ui_) {
+    Profile* profile = Profile::FromWebUI(web_ui_);
+    if (HasConfigurationChanged(configuration, profile)) {
+      UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything",
+                            configuration.sync_everything);
+      if (!configuration.sync_everything) {
+        // Only log the data types that are explicitly listed on the sync
+        // preferences page.
+        const syncable::ModelTypeSet& types = configuration.data_types;
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncBookmarks",
+            types.find(syncable::BOOKMARKS) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncPreferences",
+            types.find(syncable::PREFERENCES) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncThemes",
+            types.find(syncable::THEMES) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncPasswords",
+            types.find(syncable::PASSWORDS) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncAutofill",
+            types.find(syncable::AUTOFILL) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncExtensions",
+            types.find(syncable::EXTENSIONS) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncTypedUrls",
+            types.find(syncable::TYPED_URLS) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncSessions",
+            types.find(syncable::SESSIONS) != types.end());
+        UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncApps",
+            types.find(syncable::APPS) != types.end());
+        COMPILE_ASSERT(17 == syncable::MODEL_TYPE_COUNT,
+                       UpdateCustomConfigHistogram);
+      }
+      UMA_HISTOGRAM_BOOLEAN("Sync.EncryptAllData", configuration.encrypt_all);
+      UMA_HISTOGRAM_BOOLEAN("Sync.CustomPassphrase",
+                            configuration.set_gaia_passphrase ||
+                            configuration.set_secondary_passphrase);
+    }
+  }
+
   DCHECK(flow_);
   flow_->OnUserConfigured(configuration);

@@ -567,47 +608,6 @@
   }
   if (!configuration.sync_everything) {
     ProfileMetrics::LogProfileSyncInfo(ProfileMetrics::SYNC_CHOOSE);
-  }
-
-  // Happens during unit tests.
-  if (!web_ui_)
-    return;
-
-  Profile* profile = Profile::FromWebUI(web_ui_);
-  if (HasConfigurationChanged(configuration, profile)) {
-    UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything",
-                          configuration.sync_everything);
-    if (!configuration.sync_everything) {
-      const syncable::ModelTypeSet& types = configuration.data_types;
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncBookmarks",
-          types.find(syncable::BOOKMARKS) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncPreferences",
-          types.find(syncable::PREFERENCES) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncThemes",
-          types.find(syncable::THEMES) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncPasswords",
-          types.find(syncable::PASSWORDS) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncAutofill",
-          types.find(syncable::AUTOFILL) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncExtensions",
-          types.find(syncable::EXTENSIONS) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncExtensionSettings",
-          types.find(syncable::EXTENSION_SETTINGS) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncTypedUrls",
-          types.find(syncable::TYPED_URLS) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncSessions",
-          types.find(syncable::SESSIONS) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncApps",
-          types.find(syncable::APPS) != types.end());
-      UMA_HISTOGRAM_BOOLEAN("Sync.CustomSyncAppSettings",
-          types.find(syncable::APP_SETTINGS) != types.end());
-      COMPILE_ASSERT(17 == syncable::MODEL_TYPE_COUNT,
-                     UpdateCustomConfigHistogram);
-    }
-    UMA_HISTOGRAM_BOOLEAN("Sync.EncryptAllData", configuration.encrypt_all);
-    UMA_HISTOGRAM_BOOLEAN("Sync.CustomPassphrase",
-                          configuration.set_gaia_passphrase ||
-                          configuration.set_secondary_passphrase);
   }
 }


Change "Customer Network" to "Organization Network"

--- Common/Code/MapData.cpp
+++ Common/Code/MapData.cpp
@@ -225,7 +225,7 @@
     friendlyTypeStrings[(int)AS_UNKNOWN] = "Unknown Network Type";
     friendlyTypeStrings[(int)AS_T1] = "Large ISP";
     friendlyTypeStrings[(int)AS_T2] = "Small ISP";
-    friendlyTypeStrings[(int)AS_COMP] = "Customer Network";
+    friendlyTypeStrings[(int)AS_COMP] = "Organization Network";
     friendlyTypeStrings[(int)AS_EDU] = "University";
     friendlyTypeStrings[(int)AS_IX] = "Internet Exchange Point";
     friendlyTypeStrings[(int)AS_NIC] = "Network Information Center";


BUG: singular matrix should not force a warning

--- Common/vtkMatrix4x4.cxx
+++ Common/vtkMatrix4x4.cxx
@@ -19,7 +19,7 @@
 #include <stdlib.h>
 #include <math.h>

-vtkCxxRevisionMacro(vtkMatrix4x4, "1.61");
+vtkCxxRevisionMacro(vtkMatrix4x4, "1.62");
 vtkStandardNewMacro(vtkMatrix4x4);

 // Useful for viewing a double[16] as a double[4][4]
@@ -157,7 +157,6 @@
   det = vtkMatrix4x4::Determinant(inElements);
   if ( det == 0.0 )
     {
-    vtkGenericWarningMacro(<< "Singular matrix, no inverse!" );
     return;
     }


Cleaning up code.

Cleaning up code.

	modified:   code/ylikuutio/load/srtm_heightmap_loader.cpp


Allowing more test iterations.

Allowing more test iterations.

--- rai/core_test/node.cpp
+++ rai/core_test/node.cpp
@@ -139,7 +139,7 @@
 	{
 		system.poll ();
 		++iterations;
-		ASSERT_LT (iterations, 2000);
+		ASSERT_LT (iterations, 4000);
 	}
 }


Bug 415326 The mmap option in mprotect is set wrong in GCHeapUnix.cpp. treilly: review+

--- MMgc/GCHeapUnix.cpp
+++ MMgc/GCHeapUnix.cpp
@@ -162,7 +162,7 @@
 		int retval =
 #endif
 		  mprotect((maddr_ptr)beginPage, sizePaged,
-			   executableFlag ? (PROT_READ|PROT_EXEC) : (PROT_READ|PROT_WRITE|PROT_EXEC));
+			   executableFlag ? (PROT_READ|PROT_WRITE|PROT_EXEC) : (PROT_READ|PROT_WRITE));

 		GCAssert(retval == 0);
 	}


Fix for: Lenient UTF-8 -> UTF-16 transcoding (insert replacement characters)

--- realm-jni/src/util.cpp
+++ realm-jni/src/util.cpp
@@ -286,11 +286,11 @@
         bool copy_stack_buf = dyn_buf.size() == 0;
         size_t used_dyn_buf_size = copy_stack_buf ? 0 : used_size;
         dyn_buf.reserve(used_dyn_buf_size, min_capacity);
+        if (copy_stack_buf)
+            copy(out_begin, out, dyn_buf.data());
         out_begin = dyn_buf.data();
         out_end = dyn_buf.data() + dyn_buf.size();
         out = out_begin + used_size;
-        if (copy_stack_buf)
-            copy(stack_buf, stack_buf_out_end, out_begin);
         if (bad_input)
             *out++ = JcharTraits::to_char_type(0xFFFD); // Unicode replacement character
     }


Fix for "RTP dynamic payload type 100 is reserved"

TBR=perkj
BUG=227036 (in crbug.com)

TEST=out\Debug\voe_auto_test.exe --automated --gtest_filter=Dtmf* where I
manually modified the test and used 100 as new PT (which I first verified was
already used by CN, 48000).

BUG=

Review URL: https://webrtc-codereview.appspot.com/1319010

git-svn-id: 917f5d3ca488f358c4d40eaec14422cf392ccec9@3859 4adac7df-926f-26a2-2b94-8c16560cd09d

--- webrtc/voice_engine/channel.cc
+++ webrtc/voice_engine/channel.cc
@@ -3182,11 +3182,14 @@
     memcpy(codec.plname, "telephone-event", 16);
     if (_rtpRtcpModule->RegisterSendPayload(codec) != 0)
     {
-        _engineStatisticsPtr->SetLastError(
-            VE_RTP_RTCP_MODULE_ERROR, kTraceError,
-            "SetSendTelephoneEventPayloadType() failed to register send"
-            "payload type");
-        return -1;
+        _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
+        if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
+            _engineStatisticsPtr->SetLastError(
+                VE_RTP_RTCP_MODULE_ERROR, kTraceError,
+                "SetSendTelephoneEventPayloadType() failed to register send"
+                "payload type");
+            return -1;
+        }
     }
     _sendTelephoneEventPayloadType = type;
     return 0;


Fix trivial bug introduced in #683

Fix trivial bug introduced in #683


Fixed NOSERVICE handling in client.

Fixed NOSERVICE handling in client.

--- src/Application/Client/SDBPShardConnection.cpp
+++ src/Application/Client/SDBPShardConnection.cpp
@@ -108,8 +108,7 @@
 bool ShardConnection::OnMessage(ReadBuffer& rbuf)
 {
     SDBPResponseMessage msg;
-    Request*            it;
-    uint64_t            quorumID;
+    Request*            request;

     CLIENT_MUTEX_GUARD_DECLARE();

@@ -121,22 +120,21 @@
         return false;

     // find the request in sent requests by commandID
-    FOREACH (it, sentRequests)
-    {
-        if (it->commandID == response.commandID)
+    FOREACH (request, sentRequests)
+    {
+        if (request->commandID == response.commandID)
         {
-            // TODO: what to do when the first in the queue returns NOSERVICE
-            // but the others return OK ?!?
-
+            // put back the request to the quorum queue and
             // invalidate quorum state on NOSERVICE response
             if (response.type == CLIENTRESPONSE_NOSERVICE)
             {
-                quorumID = it->quorumID;
-                InvalidateQuorum(quorumID);
+                sentRequests.Remove(request);
+                client->AddRequestToQuorum(request, false);
+                client->InvalidateQuorum(request->quorumID, nodeID);
                 return false;
             }

-            sentRequests.Remove(it);
+            sentRequests.Remove(request);
             break;
         }
     }


Fix floating point exception with bps calculation 	modified:   tensorflow/contrib/tensorboard/db/loader.cc

--- tensorflow/contrib/tensorboard/db/loader.cc
+++ tensorflow/contrib/tensorboard/db/loader.cc
@@ -112,8 +112,10 @@
   }
   uint64 elapsed = env->NowMicros() - start;
   LOG(INFO) << "Loaded " << AddCommas(offset) << " bytes with "
-            << AddCommas(records) << " records at "
-            << AddCommas(offset / (elapsed / 1000000)) << " bps";
+            << AddCommas(records) << " records";
+  if (elapsed > 0) {
+    LOG(INFO) << "bps=" << (uint64)(offset / (elapsed / 1000000.0));
+  }

   return 0;
 }


Fix block where setter/getters are cached to be skipped

--- editor/doc/doc_data.cpp
+++ editor/doc/doc_data.cpp
@@ -214,10 +214,11 @@
 	ClassDB::get_class_list(&classes);
 	classes.sort_custom<StringName::AlphCompare>();

-	Set<StringName> setters_getters;
 	bool skip_setter_getter_methods = true;

 	while (classes.size()) {
+
+		Set<StringName> setters_getters;

 		String name = classes.front()->get();
 		String cname = name;


test that fails

test that fails

--- test/options.cpp
+++ test/options.cpp
@@ -219,6 +219,36 @@
   REQUIRE(result["implicit"].as<std::string>() == "");
 }

+TEST_CASE("Default values", "[default]")
+{
+  cxxopts::Options options("defaults", "has defaults");
+  options.add_options()
+    ("default", "Has implicit", cxxopts::value<int>()
+      ->default_value("42"));
+
+  SECTION("Sets defaults") {
+    Argv av({"implicit"});
+
+    char** argv = av.argv();
+    auto argc = av.argc();
+
+    auto result = options.parse(argc, argv);
+    CHECK(result.count("default") == 1);
+    CHECK(result["default"].as<int>() == 42);
+  }
+
+  SECTION("When values provided") {
+    Argv av({"implicit", "default", "5"});
+
+    char** argv = av.argv();
+    auto argc = av.argc();
+
+    auto result = options.parse(argc, argv);
+    CHECK(result.count("default") == 1);
+    CHECK(result["default"].as<int>() == 5);
+  }
+}
+
 TEST_CASE("Parse into a reference", "[reference]")
 {
   int value = 0;


Add error handler function

Add error handler function

--- private/phpqt5_zm.cpp
+++ private/phpqt5_zm.cpp
@@ -190,26 +190,48 @@
     return read_bytes;
 }

+static void phpqt5_error_handler(int error_num, const char *error_filename, const uint error_lineno, const char *format, va_list args) {
+    QString error_type;
+
+    switch(error_num) {
+    case E_ERROR: error_type = "Error"; break;
+    case E_WARNING: error_type = "Warning"; break;
+    case E_CORE_ERROR: error_type = "Core Error"; break;
+    case E_CORE_WARNING: error_type = "Core Warning"; break;
+    case E_COMPILE_ERROR: error_type = "Compile Error"; break;
+    case E_COMPILE_WARNING: error_type = "Compile Warning"; break;
+    case E_USER_ERROR: error_type = "User Error"; break;
+    case E_USER_WARNING: error_type = "User Warning"; break;
+    case E_RECOVERABLE_ERROR: error_type = "Recoverable Error"; break;
+    default: return;
+    }
+
+    pq_pre(QString("%1: %2 in %3 on line %4")
+           .arg(error_type)
+           .arg(format)
+           .arg(error_filename)
+           .arg(error_lineno),
+           error_type);
+}
+
 int PHPQt5::zm_startup_phpqt5(INIT_FUNC_ARGS)
 {
 #ifdef PQDEBUG
     PQDBG_LVL_START(__FUNCTION__);
 #endif
+
+    zend_error_cb = phpqt5_error_handler; //

     qRegisterMetaType<zval>("zval");
     qRegisterMetaType<zval*>("zval*");

-    #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG)
     PQDBGLPUP("register stream wrapper");
-    #endif
     php_register_url_stream_wrapper("qrc", &php_qrc_stream_wrapper);

-    #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG)
     PQDBGLPUP("register handlers");
-    #endif
     memcpy(&pqobject_handlers,
-           zend_get_std_object_handlers(),
-           sizeof(zend_object_handlers));
+    zend_get_std_object_handlers(),
+    sizeof(zend_object_handlers));

     pqobject_handlers.offset = XtOffsetOf(PQObjectWrapper, zo);

@@ -224,17 +246,11 @@
    // pqobject_handlers.read_property	= pqobject_read_property;
    // pqobject_handlers.has_property	= pqobject_has_property;

-    #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG)
     PQDBGLPUP("register extensions");
-    #endif
     PQEnginePrivate::pq_register_extensions(PQDBG_LVL_C);
     phpqt5Connections = new PHPQt5Connection(PQDBG_LVL_C);

-    #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG)
-    PQDBGLPUP("done");
-    #endif
-
-    PQDBG_LVL_DONE();
+    PQDBG_LVL_DONE_LPUP();
     return SUCCESS;
 }


Fix a crasher in CXFA_LayoutPageMgr::GetAvailHeight()

BUG=pdfium:407
R=tsepez@chromium.org

Review URL: https://codereview.chromium.org/1717243002 .

--- xfa/src/fxfa/src/parser/xfa_layout_pagemgr_new.cpp
+++ xfa/src/fxfa/src/parser/xfa_layout_pagemgr_new.cpp
@@ -251,19 +251,19 @@
   }
 }
 FX_FLOAT CXFA_LayoutPageMgr::GetAvailHeight() {
+  CXFA_ContainerLayoutItem* pLayoutItem =
+      GetCurrentContainerRecord()->pCurContentArea;
+  if (!pLayoutItem || !pLayoutItem->m_pFormNode)
+    return 0.0f;
   FX_FLOAT fAvailHeight =
-      GetCurrentContainerRecord()
-          ->pCurContentArea->m_pFormNode->GetMeasure(XFA_ATTRIBUTE_H)
-          .ToUnit(XFA_UNIT_Pt);
-  if (fAvailHeight < XFA_LAYOUT_FLOAT_PERCISION) {
-    if (m_pCurrentContainerRecord ==
-        m_rgProposedContainerRecord.GetHeadPosition()) {
-      fAvailHeight = 0;
-    } else {
-      fAvailHeight = XFA_LAYOUT_FLOAT_MAX;
-    }
-  }
-  return fAvailHeight;
+      pLayoutItem->m_pFormNode->GetMeasure(XFA_ATTRIBUTE_H).ToUnit(XFA_UNIT_Pt);
+  if (fAvailHeight >= XFA_LAYOUT_FLOAT_PERCISION)
+    return fAvailHeight;
+  if (m_pCurrentContainerRecord ==
+      m_rgProposedContainerRecord.GetHeadPosition()) {
+    return 0.0f;
+  }
+  return XFA_LAYOUT_FLOAT_MAX;
 }
 static CXFA_Node* XFA_ResolveBreakTarget(CXFA_Node* pPageSetRoot,
                                          FX_BOOL bNewExprStyle,


Clean up logging.

Clean up logging.

--- src/Core/ConsoleApplication/ConsoleCommands.cc
+++ src/Core/ConsoleApplication/ConsoleCommands.cc
@@ -58,6 +58,9 @@
   }
 }

+/// @todo: real logger
+#define LOG_CONSOLE(x) std::cout << "[SCIRun] " << x << std::endl;
+
 bool LoadFileCommandConsole::execute()
 {
   quietModulesIfNotVerbose();
@@ -71,11 +74,10 @@
     filename = get(Variables::Filename).toFilename().string();
   }

-  /// @todo: real logger
-  std::cout << "Attempting load of " << filename << std::endl;
+  LOG_CONSOLE("Attempting load of " << filename);
   if (!boost::filesystem::exists(filename))
   {
-    std::cout << "File does not exist: " << filename << std::endl;
+    LOG_CONSOLE("File does not exist: " << filename);
     return false;
   }
   try
@@ -86,17 +88,14 @@
     {
       Application::Instance().controller()->clear();
       Application::Instance().controller()->loadNetwork(openedFile);
-      /// @todo: real logger
-      std::cout << "File load done: " << filename << std::endl;
+      LOG_CONSOLE("File load done: " << filename);
       return true;
     }
-    /// @todo: real logger
-    std::cout << "File load failed: " << filename << std::endl;
+    LOG_CONSOLE("File load failed: " << filename);
   }
   catch (...)
   {
-    /// @todo: real logger
-    std::cout << "File load failed: " << filename << std::endl;
+    LOG_CONSOLE("File load failed: " << filename);
   }
   return false;
 }
@@ -108,13 +107,13 @@

 bool ExecuteCurrentNetworkCommandConsole::execute()
 {
-  std::cout << "....Executing network..." << std::endl;
-  Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ std::cout << "Execution finished with code " << code << std::endl; });
+  LOG_CONSOLE("Executing network...");
+  Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ LOG_CONSOLE("Execution finished with code " << code); });
   Application::Instance().controller()->stopExecutionContextLoopWhenExecutionFinishes();
   auto t = Application::Instance().controller()->executeAll(nullptr);
-  std::cout << "....Execute started..." << std::endl;
+  LOG_CONSOLE("Execution started.");
   t->join();
-  std::cout << "....Execute thread stopped...entering interactive mode." << std::endl;
+  LOG_CONSOLE("Execute thread stopped. Entering interactive mode.");

   InteractiveModeCommandConsole interactive;
   return interactive.execute();
@@ -127,8 +126,12 @@

 bool QuitAfterExecuteCommandConsole::execute()
 {
-  std::cout << "Quit after execute is set." << std::endl;
-  Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ exit(code); });
+  LOG_CONSOLE("Quit after execute is set.");
+  Application::Instance().controller()->connectNetworkExecutionFinished([](int code)
+  {
+    LOG_CONSOLE("Goodbye! Exit code: " << code);
+    exit(code);
+  });
   return true;
 }

@@ -139,7 +142,7 @@

 bool QuitCommandConsole::execute()
 {
-  std::cout << "Goodbye!" << std::endl;
+  LOG_CONSOLE("Goodbye!");
   exit(0);
   return true;
 }
@@ -180,7 +183,7 @@
     if (!PythonInterpreter::Instance().run_string(line))
       break;
   }
-  std::cout << "\nGoodbye!" << std::endl;
+  std::cout << "\n[SCIRun] Goodbye!" << std::endl;
   exit(0);
 #endif
   return true;
@@ -194,7 +197,7 @@
   if (script)
   {
 #ifdef BUILD_WITH_PYTHON
-    std::cout << "RUNNING PYTHON SCRIPT: " << *script << std::endl;;
+    LOG_CONSOLE("RUNNING PYTHON SCRIPT: " << *script);

     Application::Instance().controller()->clear();
     PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *");
@@ -205,14 +208,14 @@
     {
       while (true)
       {
-        std::cout << "Running Python script." << std::endl;
+        LOG_CONSOLE("Running Python script.");
         boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
       }
     }
-    std::cout << "Done running Python script." << std::endl;
+    LOG_CONSOLE("Done running Python script.");
     return true;
 #else
-    std::cout << "Python disabled, cannot run script " << *script << std::endl;
+    LOG_CONSOLE("Python disabled, cannot run script " << *script);
     return false;
 #endif
   }