问:
How to zoom image with angularJS
How can i zoom the image when i click on the image itself using angularJS. I cant happen to do it when i using this website given: https://github.com/owlsomely/angular-image-zoom?utm_source=angular-js.in&utm_medium=website&utm_campaign=content-curation . Anyone can help?

My js file:

```<code>var camListApp = angular.module('camListApp', ['ui.bootstrap'])

camListApp.filter('unique', function() {
    return function(input, key) {
        var unique = {};
        var uniqueList = [];
        for(var i = 0; i < input.length; i++){
            if(typeof unique[input[i][key]] == "undefined"){
                unique[input[i][key]] = "";
                uniqueList.push(input[i]);
            }
        }
        return uniqueList;
    };
});
camListApp.controller("Hello", ["$scope", "$http", function($scope, $http){

$scope.custom = true;
$scope.toggleCustom = function(url) {
    $scope.custom = ! $scope.custom;
     $scope.imageView = url;

};

$http.get('http://localhost:8082/camera/list').then(function(response) {
     console.log(response);
        $scope.records= response.data;
    });
 }]);
</code>```

My html file:

```<code> <div ng-controller="Hello" class="col-xs-12">

 <b>Search:</b><br>

<input type = "text" ng-model="searchBox" uib-typeahead="state.cameraid as state.cameraid for state in records | filter:searchBox | limitTo:8 | unique:'cameraid'">

<br>
<br>
<br>
<br>
 <table border = 1 class="table table-striped table-hover" style="width:45%">
    <thead>
      <tr>

        <th><center>CamID</th></center>
        <th><center>Timestamp</th></center>
        <th><center>View Image</center></th>
      </tr>
    </thead>

    <tbody>
      <tr ng-repeat="record in records | filter:searchBox | orderBy:'+timestamp'">

        <td>{{record.cameraid}}</td>
        <td>{{record.timestamp}}</td>
        <td><center> <button class="btn btn-primary" ng-click="toggleCustom(record.filename)" onclick="myFunction()">View</center></button></td>
      </tr>

    </tbody>
  </table>

   <span id="myDIV" ng-hide="custom">
   <img ng-src="http://localhost:9100/Images/{{imageView}}.png" image-zoom width="500" height="400">
    </span>

    <!--<span ng-hide="custom">To:
        <input type="text" id="to" />
    </span>-->
    <span ng-show="custom"></span>
</div>
<script>
function myFunction() {
document.getElementById("myDIV").style.position = "absolute";
}
</script>

</body>
</html>
</code>```

答:
my simple directive to increase the image reduction and image movement. I hope will be useful to you.

```<code>  (function () {
        angular
            .module('app')
            .directive('zoom', [function () {
                return {
                    restrict: 'A',
                    link: function (scope, elem, attrs) {
                        var img = elem[0];
                        $(img).css({
                            "position": "absolute",
                            "top": "0",
                            "bottom": "0",
                            "left": "0",
                            "right": "0",
                            "margin": "auto",
                            "padding-left": "1px",
                            "padding-right": "1px",
                            "padding-top": "1px",
                            "padding-bottom": "1px",
                            "-webkit - user - select": "none",
                            "-webkit - user - drag": "none"
                        });
                        var imageContainer = img.parentNode.parentNode;
                        $(imageContainer).css({
                            "text-align": "center",
                            "margin": "0",
                            "padding": "0",
                            "height": "100%",
                            "max- height": "100%",
                            "width": "100%",
                            "background-color": "#000",
                            "overflow": "hidden",
                            "-webkit - user - select": "none",
                            "cursor": "context - menu",
                        });
                        var parent = img.parentNode;
                        $(parent).css({
                            "width": "100%",
                            "height": "auto",
                            "margin": 0,
                            "padding": 0,
                            "display": "-webkit - box",
                            "-webkit - box - pack": "center",
                            "-webkit - box - align": "center",
                            "z-index": "5"
                        });
                        var currentScale = 1;
                        var currentRotation = 90
                        let transformOriginX = 0, transformOriginY = 0;
                        let translateX = 0, translateY = 0;
                        function setTransformOrigin() {
                            let imgRect = img.getBoundingClientRect();
                            let parentRect = parent.getBoundingClientRect();
                            let visibleWidth = (imgRect.width > parent.offsetWidth) ? imgRect.left + parentRect.width : imgRect.width;
                            let visibleHeight = (imgRect.height > parent.offsetHeight) ? imgRect.top + parentRect.height : imgRect.height;
                            let beginX = parentRect.right - visibleWidth, beginY = parentRect.bottom - visibleHeight;
                            let endX = beginX + visibleWidth, endY = beginY + visibleHeight;
                            let midX = beginX + ((endX - beginX) / 2), midY = beginY + ((endY - beginY) / 2);
                           // if (midY > imageContainer.clientHeight / 2) midY = imageContainer.clientHeight / 2;
                            //if (midX > imageContainer.clientWidth / 2) midX = imageContainer.clientWidth / 2;
                            if (midY > imageContainer.clientHeight / 2) { parent.style.transformOrigin = midX + 'px ' + midY + 'px' } else {
                                parent.style.transformOrigin = midX + 'px ' + imageContainer.clientHeight / 2 + 'px'
                            }
                        }
                        function scaleImage(scale, event) {

                            img.style.transform = 'scale(' + scale + ') ' + 'rotate(' + (currentRotation - 90) + 'deg)';
                            if (scale < currentScale) {
                                let imgRect = img.getBoundingClientRect();
                                let imageContainerRect = imageContainer.getBoundingClientRect();
                                if (parent.style.transform.match('translate')) {
                                    let parentTransform = parent.style.transform.replace('translate(', '').replace(')', '').split(', ');
                                    let moveX = parentTransform[0].replace('px', ''), moveY = parentTransform[1].replace('px', '');
                                    if ((imageContainerRect.right - imgRect.right) > 0 || (imageContainerRect.left - imgRect.left) < 0) {
                                        let moveBy = ((imageContainerRect.right - imgRect.right) > 0) ? (imageContainerRect.right - imgRect.right) : (imageContainerRect.left - imgRect.left);
                                        moveX = (imgRect.width > parent.offsetWidth) ? (parseFloat(parentTransform[0]) + moveBy) : 0;
                                        transformOriginX = (transformOriginX - moveBy);
                                    }
                                    if ((imageContainerRect.bottom - imgRect.bottom) > 0 || (imageContainerRect.top - imgRect.top) < 0) {
                                        let moveBy = ((imageContainerRect.bottom - imgRect.bottom) > 0) ? (imageContainerRect.bottom - imgRect.bottom) : (imageContainerRect.top - imgRect.top);
                                        moveY = (imgRect.height > parent.offsetHeight) ? (parseFloat(parentTransform[1]) + moveBy) : 0;
                                        transformOriginY = (transformOriginY + moveBy);
                                    }
                                    if (scale <= 1) { translateX = 0; translateY = 0; }
                                    parent.style.transformOrigin = transformOriginX + 'px ' + transformOriginY + 'px';
                               }
                            }
                            currentScale = scale;
                            let imgRect = img.getBoundingClientRect();
                            let parentRect = parent.getBoundingClientRect();
                            let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
                            let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
                            let startX = event.pageX - translateX, startY = event.pageY - translateY;
                            let max_left = parentRect.left - imgRect.left;
                            let max_top = parentRect.top - imgRect.top;
                            var evt = window.event;
                            translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
                            translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
                            translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
                            if ((translateX != 0) && (translateY != 0)) {
                                if (translateY > imageContainer.clientHeight/2) { parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)' } else {
                                    parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+'px)'
                                }
                            } else {
                                parent.style['-webkit-transform'] = ''
                            };
                            return false;
                        }

                        function tap() {
                            let imgRect = img.getBoundingClientRect();
                            let parentRect = parent.getBoundingClientRect();
                            let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
                            let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
                            let startX = event.pageX - translateX, startY = event.pageY - translateY;
                            let max_left = parentRect.left - imgRect.left;
                            let max_top = parentRect.top - imgRect.top;
                            var evt = window.event;
                            translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
                            translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
                            translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
                            if ((translateX != 0) && (translateY != 0)) {
                                if (translateY > imageContainer.clientHeight / 2) {
                                    parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
                                } else {
                                    parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
                                }
                            } else {
                                parent.style['-webkit-transform'] = ''
                            };
                        }
                        function makeDraggable(event) {

                            parent = img.parentNode;
                            imageContainer = img.parentNode.parentNode;
                            $(parent).css({

                                "display": "-webkit - box",
                                "-webkit - box - pack": "center",
                                "-webkit - box - align": "center",
                                "z-index": "5"
                            });
                            $(imageContainer).css({
                                "text-align": "center",
                                "margin": "0",
                                "padding": "0",
                                "overflow": "hidden",
                                "-webkit - user - select": "none",
                                "cursor": "context - menu",
                            });
                            let imgRect = img.getBoundingClientRect();
                            let parentRect =parent.getBoundingClientRect();
                            let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
                            let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
                            let startX = event.pageX - translateX, startY = event.pageY - translateY;
                            let max_left = parentRect.left - imgRect.left;
                            let max_top = parentRect.top - imgRect.top;

                            window.onmousemove = function (evt) {
                                if (evt == null) { evt = window.event; }
                                translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
                                translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
                                translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
                                if ((translateX != 0) && (translateY != 0)) {
                                    if (translateY > imageContainer.clientHeight) {
                                        parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
                                    } else {
                                       parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
                                    }
                                } else {
                                    parent.style['-webkit-transform'] = ''
                                };
                                return false;
                            }

                            window.onmouseup = function (evt) {
                                setTransformOrigin();
                                window.onmousemove = null;
                            }

                            return false;
                        };
                        img.addEventListener('mousedown', function () { makeDraggable(event); });
                              elem.bind('mousewheel', function (e) {
                            var img = e.currentTarget.style.width;
                            var scaleX = e.currentTarget.getBoundingClientRect().width / e.currentTarget.offsetWidth;
                            var w = "";
                            var resW = "";
                            var resL = "";
                            var resT = "";
                            var zValue = 1.2;
                            var newScale = scaleX * zValue;
                            var newScale = "scale(1)";
                            var val = parseInt(w.replace('%', ''));
                            if (e.originalEvent.wheelDelta / 120 > 0) {
                                newScale = scaleX * zValue;
                            }
                            else {
                                if ((scaleX / zValue) > 1) {
                                    newScale = scaleX / zValue
                                } else {
                                    newScale = 1.0;
                                }
                            }
                            scaleImage(newScale, e);
                            setTransformOrigin();
                            window.onmousemove = null;
                       });
                    }
                }
            }]);

    })();
</code>```

Use at HTML as

```<code><image zoom  src="" ></image>
</code>```

Title: How to zoom image with angularJS

Body:
How can i zoom the image when i click on the image itself using angularJS. I cant happen to do it when i using this website given: https://github.com/owlsomely/angular-image-zoom?utm_source=angular-js.in&utm_medium=website&utm_campaign=content-curation . Anyone can help?

My js file:

var camListApp = angular.module('camListApp', ['ui.bootstrap'])

camListApp.filter('unique', function() {
    return function(input, key) {
        var unique = {};
        var uniqueList = [];
        for(var i = 0; i < input.length; i++){
            if(typeof unique[input[i][key]] == "undefined"){
                unique[input[i][key]] = "";
                uniqueList.push(input[i]);
            }
        }
        return uniqueList;
    };
});
camListApp.controller("Hello", ["$scope", "$http", function($scope, $http){

$scope.custom = true;
$scope.toggleCustom = function(url) {
    $scope.custom = ! $scope.custom;
     $scope.imageView = url;

};

$http.get('http://localhost:8082/camera/list').then(function(response) {
     console.log(response);
        $scope.records= response.data;
    });
 }]);

My html file:

 Search:

<input type = "text" ng-model="searchBox" uib-typeahead="state.cameraid as state.cameraid for state in records | filter:searchBox | limitTo:8 | unique:'cameraid'">

        CamID
        Timestamp
        View Image

        {{record.cameraid}}
        {{record.timestamp}}
         <button class="btn btn-primary" ng-click="toggleCustom(record.filename)" onclick="myFunction()">View</button>

Body:
my simple directive to increase the image reduction and image movement. I hope will be useful to you.

  (function () {
        angular
            .module('app')
            .directive('zoom', [function () {
                return {
                    restrict: 'A',
                    link: function (scope, elem, attrs) {
                        var img = elem[0];
                        $(img).css({
                            "position": "absolute",
                            "top": "0",
                            "bottom": "0",
                            "left": "0",
                            "right": "0",
                            "margin": "auto",
                            "padding-left": "1px",
                            "padding-right": "1px",
                            "padding-top": "1px",
                            "padding-bottom": "1px",
                            "-webkit - user - select": "none",
                            "-webkit - user - drag": "none"
                        });
                        var imageContainer = img.parentNode.parentNode;
                        $(imageContainer).css({
                            "text-align": "center",
                            "margin": "0",
                            "padding": "0",
                            "height": "100%",
                            "max- height": "100%",
                            "width": "100%",
                            "background-color": "#000",
                            "overflow": "hidden",
                            "-webkit - user - select": "none",
                            "cursor": "context - menu",
                        });
                        var parent = img.parentNode;
                        $(parent).css({
                            "width": "100%",
                            "height": "auto",
                            "margin": 0,
                            "padding": 0,
                            "display": "-webkit - box",
                            "-webkit - box - pack": "center",
                            "-webkit - box - align": "center",
                            "z-index": "5"
                        });
                        var currentScale = 1;
                        var currentRotation = 90
                        let transformOriginX = 0, transformOriginY = 0;
                        let translateX = 0, translateY = 0;
                        function setTransformOrigin() {
                            let imgRect = img.getBoundingClientRect();
                            let parentRect = parent.getBoundingClientRect();
                            let visibleWidth = (imgRect.width > parent.offsetWidth) ? imgRect.left + parentRect.width : imgRect.width;
                            let visibleHeight = (imgRect.height > parent.offsetHeight) ? imgRect.top + parentRect.height : imgRect.height;
                            let beginX = parentRect.right - visibleWidth, beginY = parentRect.bottom - visibleHeight;
                            let endX = beginX + visibleWidth, endY = beginY + visibleHeight;
                            let midX = beginX + ((endX - beginX) / 2), midY = beginY + ((endY - beginY) / 2);
                           // if (midY > imageContainer.clientHeight / 2) midY = imageContainer.clientHeight / 2;
                            //if (midX > imageContainer.clientWidth / 2) midX = imageContainer.clientWidth / 2;
                            if (midY > imageContainer.clientHeight / 2) { parent.style.transformOrigin = midX + 'px ' + midY + 'px' } else {
                                parent.style.transformOrigin = midX + 'px ' + imageContainer.clientHeight / 2 + 'px'
                            }
                        }
                        function scaleImage(scale, event) {

                            img.style.transform = 'scale(' + scale + ') ' + 'rotate(' + (currentRotation - 90) + 'deg)';
                            if (scale < currentScale) {
                                let imgRect = img.getBoundingClientRect();
                                let imageContainerRect = imageContainer.getBoundingClientRect();
                                if (parent.style.transform.match('translate')) {
                                    let parentTransform = parent.style.transform.replace('translate(', '').replace(')', '').split(', ');
                                    let moveX = parentTransform[0].replace('px', ''), moveY = parentTransform[1].replace('px', '');
                                    if ((imageContainerRect.right - imgRect.right) > 0 || (imageContainerRect.left - imgRect.left) < 0) {
                                        let moveBy = ((imageContainerRect.right - imgRect.right) > 0) ? (imageContainerRect.right - imgRect.right) : (imageContainerRect.left - imgRect.left);
                                        moveX = (imgRect.width > parent.offsetWidth) ? (parseFloat(parentTransform[0]) + moveBy) : 0;
                                        transformOriginX = (transformOriginX - moveBy);
                                    }
                                    if ((imageContainerRect.bottom - imgRect.bottom) > 0 || (imageContainerRect.top - imgRect.top) < 0) {
                                        let moveBy = ((imageContainerRect.bottom - imgRect.bottom) > 0) ? (imageContainerRect.bottom - imgRect.bottom) : (imageContainerRect.top - imgRect.top);
                                        moveY = (imgRect.height > parent.offsetHeight) ? (parseFloat(parentTransform[1]) + moveBy) : 0;
                                        transformOriginY = (transformOriginY + moveBy);
                                    }
                                    if (scale <= 1) { translateX = 0; translateY = 0; }
                                    parent.style.transformOrigin = transformOriginX + 'px ' + transformOriginY + 'px';
                               }
                            }
                            currentScale = scale;
                            let imgRect = img.getBoundingClientRect();
                            let parentRect = parent.getBoundingClientRect();
                            let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
                            let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
                            let startX = event.pageX - translateX, startY = event.pageY - translateY;
                            let max_left = parentRect.left - imgRect.left;
                            let max_top = parentRect.top - imgRect.top;
                            var evt = window.event;
                            translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
                            translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
                            translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
                            if ((translateX != 0) && (translateY != 0)) {
                                if (translateY > imageContainer.clientHeight/2) { parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)' } else {
                                    parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+'px)'
                                }
                            } else {
                                parent.style['-webkit-transform'] = ''
                            };
                            return false;
                        }

                        function tap() {
                            let imgRect = img.getBoundingClientRect();
                            let parentRect = parent.getBoundingClientRect();
                            let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
                            let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
                            let startX = event.pageX - translateX, startY = event.pageY - translateY;
                            let max_left = parentRect.left - imgRect.left;
                            let max_top = parentRect.top - imgRect.top;
                            var evt = window.event;
                            translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
                            translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
                            translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
                            if ((translateX != 0) && (translateY != 0)) {
                                if (translateY > imageContainer.clientHeight / 2) {
                                    parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
                                } else {
                                    parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
                                }
                            } else {
                                parent.style['-webkit-transform'] = ''
                            };
                        }
                        function makeDraggable(event) {

                            parent = img.parentNode;
                            imageContainer = img.parentNode.parentNode;
                            $(parent).css({

                                "display": "-webkit - box",
                                "-webkit - box - pack": "center",
                                "-webkit - box - align": "center",
                                "z-index": "5"
                            });
                            $(imageContainer).css({
                                "text-align": "center",
                                "margin": "0",
                                "padding": "0",
                                "overflow": "hidden",
                                "-webkit - user - select": "none",
                                "cursor": "context - menu",
                            });
                            let imgRect = img.getBoundingClientRect();
                            let parentRect =parent.getBoundingClientRect();
                            let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
                            let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
                            let startX = event.pageX - translateX, startY = event.pageY - translateY;
                            let max_left = parentRect.left - imgRect.left;
                            let max_top = parentRect.top - imgRect.top;

                            window.onmousemove = function (evt) {
                                if (evt == null) { evt = window.event; }
                                translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
                                translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
                                translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
                                if ((translateX != 0) && (translateY != 0)) {
                                    if (translateY > imageContainer.clientHeight) {
                                        parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
                                    } else {
                                       parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
                                    }
                                } else {
                                    parent.style['-webkit-transform'] = ''
                                };
                                return false;
                            }

                            window.onmouseup = function (evt) {
                                setTransformOrigin();
                                window.onmousemove = null;
                            }

                            return false;
                        };
                        img.addEventListener('mousedown', function () { makeDraggable(event); });
                              elem.bind('mousewheel', function (e) {
                            var img = e.currentTarget.style.width;
                            var scaleX = e.currentTarget.getBoundingClientRect().width / e.currentTarget.offsetWidth;
                            var w = "";
                            var resW = "";
                            var resL = "";
                            var resT = "";
                            var zValue = 1.2;
                            var newScale = scaleX * zValue;
                            var newScale = "scale(1)";
                            var val = parseInt(w.replace('%', ''));
                            if (e.originalEvent.wheelDelta / 120 > 0) {
                                newScale = scaleX * zValue;
                            }
                            else {
                                if ((scaleX / zValue) > 1) {
                                    newScale = scaleX / zValue
                                } else {
                                    newScale = 1.0;
                                }
                            }
                            scaleImage(newScale, e);
                            setTransformOrigin();
                            window.onmousemove = null;
                       });
                    }
                }
            }]);

    })();

Use at HTML as

<image zoom  src="" ></image>


来源: stackexchange

问:
Difference between `cout << x` and `cout.operator <<(x)`?
I've been trying to use for_each to print a vector of strings to cout. However, when formulating the statement I found that std::ostream::operator<<(const std::string &); is not defined leading to compiler errors. The following code illustrates the problem:

```<code>#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";

    // This works
    std::cout << message;

    // Compiler error
    std::cout.operator <<(message);
}
</code>```

I thought that both statements should appear identical to the compiler. Apparently they are not. So what is the difference then?

Solved

As Tomalak and Prasoon indicated I needed to call this function:

```<code>std::ostream& operator<<(std::ostream&, const std::string&);
</code>```

So the following sample will work:

```<code>#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";
    operator<<(std::cout, message);
}
</code>```

Concerning my original goal (to use for_each to print a vector of strings): It seems like it's better to use std::copy with std::ostream_iterator as illustrated here: How do I use for_each to output to cout?

答:
std::cout << message; would be equivalent to operator << (std::cout, message) not what you've written.

operator << has been defined as a free function and not as a member function

std::ostream& operator<<(std::ostream& out, const std::string& s) { ... }

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to use for_each to print a vector of strings to cout. However, when formulating the statement I found that std::ostream::operator<<(const std::string &); is not defined leading to compiler errors. The following code illustrates the problem:

#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";

    // This works
    std::cout << message;

    // Compiler error
    std::cout.operator <<(message);
}

I thought that both statements should appear identical to the compiler. Apparently they are not. So what is the difference then?

Solved

As Tomalak and Prasoon indicated I needed to call this function:

std::ostream& operator<<(std::ostream&, const std::string&);

So the following sample will work:

#include <iostream>
#include <string>

int main()
{
    std::string message = "Hello World!\n";
    operator<<(std::cout, message);
}

Concerning my original goal (to use for_each to print a vector of strings): It seems like it's better to use std::copy with std::ostream_iterator as illustrated here: How do I use for_each to output to cout?


问:
Two components binding Vuejs
How would be perfect to organize data and interaction between two vuejs components? For example:
1) i have one component

```<code>item(v-for="item in items)
 a {{item.name}}
</code>```

2) and the second

```<code>card(v-for="item in items")
 div.content
  img {{item.photo}}
  div {{item.desc}}
  button Details
</code>```

The main idea is when i click on list item i want to toggle the card with the same id, as list has. I use one file conponent management from vue webpack template.

答:
A lot of folk seem to be trying to use Vue without a store. Could you be one of them? Perhaps because the store is not strictly part of Vue? Perhaps because the docs spend more time on parent-child communication, events etc (complicated) than on state management (simple)? Perhaps because OO has rotted our brains?

Vue wants to talk to a store. The whole point of bidirectional binding is to separate state from markup. The whole reason why this is such a genius idea is that many (most?) items of state have more than one representation on screen, like your items array. Your store, which can be as simple as a js object in window scope, should contain all your page state at a given moment. You should be able to copy-paste the store between pages, and be looking at the same thing on screen. The important qualities of a store are...

that there's only one of them.

that you 'normalize' your store so that an item of state is only stored once, and there are minimal dependencies between items of state.

Your items array should be in the store, and both components refer to this 'single source of truth'. If you're using other people's components, then you'll need to feed them some properties, but properties are for creating tunnels through Vue components to link leaf components with your store. Your items are your state, and state shouldn't generally live in Vue stuff. Does that help?

ContentLicense: CC BY-SA 3.0

Title: Two components binding Vuejs

Body:
How would be perfect to organize data and interaction between two vuejs components? For example:
1) i have one component

item(v-for="item in items)
 a {{item.name}}

2) and the second

card(v-for="item in items")
 div.content
  img {{item.photo}}
  div {{item.desc}}
  button Details

The main idea is when i click on list item i want to toggle the card with the same id, as list has. I use one file conponent management from vue webpack template.

ContentLicense: CC BY-SA 4.0


问:
Laravel Join 2 tables , one data from first table and multiple row from second table

FirstTable

id   |   name   |

1   | student1 |

2   | student2 |

3   | student3 |

4   | student4 |

==============================

SecondTable

Id | stud_id | subject | mark

1  |  1     | maths   | 50

2  |  1     | english   | 45

3  |  2     | maths   | 20

4  |  3     | maths   | 40

How would i query  in laravel with the above table structure..
i need outpus as

```<code>{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}
</code>```

答:
You can create a relationships with these tables. In here you need that one to many relationships.

You need students , lessons tables

Students

```<code>Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('student_name')
});
</code>```

Lessons

```<code>Schema::create('lessons', function (Blueprint $table) {
$table->increments('id');
$table->integer('student_id');
$table->integer('exam_number'); // there will be many exams right ?
$table->integer('lesson1')
$table->integer('lesson2');
$table->integer('lesson-etc');
$table->timestamps();

$table->foreign('student_id')->references('id')->on('students')
});
</code>```

Then edit your models as below

Student model;

```<code>public function lessons(){

       return $this->hasMany('App\Lesson','student_id','id');
    }
</code>```

and in your lessons model;

```<code> public function students(){

      return $this->belongsTo('App\Student');
    }
</code>```

Then in your controller,

```<code>$students = Student::whereHas('lessons', function ($query) {

            $query->where("exam_number", 2 (or which exam));
        })->get();
</code>```

Finally, in your blade;

```<code> <table >
  <tr>
    <th>Student Name</th>
    <th>Lesson 1</th>
    <th>Lesson 2</th>
  </tr>
@foreach($students as $student)
  <tr>
    <td>{{$student->student_name}}</td>
    <td>{{$student->lessons->lesson1}}</td>
    <td>{{$student->lessons->lesson2}}</td>
  </tr>
@endforeach
</table>
</code>```

This should be work

Body:
FirstTable

id   |   name   |

1   | student1 |

2   | student2 |

3   | student3 |

4   | student4 |

==============================

SecondTable

Id | stud_id | subject | mark

1  |  1     | maths   | 50

2  |  1     | english   | 45

3  |  2     | maths   | 20

4  |  3     | maths   | 40

How would i query  in laravel with the above table structure..
i need outpus as

{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}

Body:
You can create a relationships with these tables. In here you need that one to many relationships.

You need students , lessons tables

Students

Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('student_name')
});

Lessons

Schema::create('lessons', function (Blueprint $table) {
$table->increments('id');
$table->integer('student_id');
$table->integer('exam_number'); // there will be many exams right ?
$table->integer('lesson1')
$table->integer('lesson2');
$table->integer('lesson-etc');
$table->timestamps();

$table->foreign('student_id')->references('id')->on('students')
});

Then edit your models as below

Student model;

public function lessons(){

       return $this->hasMany('App\Lesson','student_id','id');
    }

and in your lessons model;

 public function students(){

      return $this->belongsTo('App\Student');
    }

Then in your controller,

$students = Student::whereHas('lessons', function ($query) {

            $query->where("exam_number", 2 (or which exam));
        })->get();

Finally, in your blade;

 <table >
  <tr>
    <th>Student Name</th>
    <th>Lesson 1</th>
    <th>Lesson 2</th>
  </tr>
@foreach($students as $student)
  <tr>
    <td>{{$student->student_name}}</td>
    <td>{{$student->lessons->lesson1}}</td>
    <td>{{$student->lessons->lesson2}}</td>
  </tr>
@endforeach
</table>

This should be work


问:
Representing @EmbeddedId as SQL for H2 database
I am currently working on a Java project with Hibernate entities (more below). In order to test my data access object layers, I am using H2 database to populate an in-memory database and throwing queries at it. Until this point, everything is fine.

However, the problem comes when simulating the @EmbeddedId annotation.

```<code>@Entity
@Table(name = "BSCOBJ")
public class BasicObject extends AbstractDomainObject {

    @EmbeddedId // This annotation here
    private RestrainPK restrain;

@Embeddable
public static class RestrainPK implements Serializable {

    private static final long   serialVersionUID    = 1L;
    @Column(name = "CODI", nullable = false)
    private String  coDi;

    @Column(name = "COGA", nullable = false)
    private String  coGa;

    @Column(name = "TYOR", nullable = false)
    private String  tyOr;

    public RestrainPK() {
    }

    ... // Getters and setters

    }
}
</code>```

"Simply" creating the table BSCOBJ and populating it gives no value when fetching data (of course, I checked that the request would give result "normally"). How do I represent this nested class in a SQL table creation / value insertion request ? Is that even possible ?

Thanks in advance,

EDIT

As requested, here is some samples about the SQL / Hibernate ran.

Creation request:

```<code>CREATE TABLE BSCOBJ (CODI VARCHAR(5) NOT NULL, COGA VARCHAR(5) NOT NULL, TYOR VARCHAR(5) NOT NULL);
</code>```

Insertion request:

```<code>INSERT INTO BSCOBJ (CODI, COGA, TYOR) VALUES
('HELLO', 'MAT', 'REF'),
('BONJ', 'SOME', 'DAIL'),
('SOPA', 'KDA', 'RATIO');
</code>```

Request given by Hibernate when trying to run the test code:

```<code>select r.restrain.tyOr from mypackage.BasicObject r where r.restrain.coDi = :coDi and r.restrain.coGa = :coGa
</code>```

With the following values:

```<code>coDi = "BONJ";
coGa = "SOME";
</code>```

Throws a NoResultException. I am expecting DAIL, from the second line of the INSERT request.

答:
I have used @EmbeddedId only one time, but I think that you need @AttributeOverrides under your @EmbeddedId

```<code>@EmbeddedId
@AttributeOverrides({
    @AttributeOverride(name = "idpk", column = @Column(name="IDPK", nullable = false),
    @AttributeOverride(name = "code", column = @Column(name="CODE")
})
</code>```

and remove your @Column annotations from FormulePK

Body:
I am currently working on a Java project with Hibernate entities (more below). In order to test my data access object layers, I am using H2 database to populate an in-memory database and throwing queries at it. Until this point, everything is fine.

However, the problem comes when simulating the @EmbeddedId annotation.

@Entity
@Table(name = "BSCOBJ")
public class BasicObject extends AbstractDomainObject {

    @EmbeddedId // This annotation here
    private RestrainPK restrain;

@Embeddable
public static class RestrainPK implements Serializable {

    private static final long   serialVersionUID    = 1L;
    @Column(name = "CODI", nullable = false)
    private String  coDi;

    @Column(name = "COGA", nullable = false)
    private String  coGa;

    @Column(name = "TYOR", nullable = false)
    private String  tyOr;

    public RestrainPK() {
    }

    ... // Getters and setters

    }
}

"Simply" creating the table BSCOBJ and populating it gives no value when fetching data (of course, I checked that the request would give result "normally"). How do I represent this nested class in a SQL table creation / value insertion request ? Is that even possible ?

Thanks in advance,

EDIT

As requested, here is some samples about the SQL / Hibernate ran.

Creation request:

CREATE TABLE BSCOBJ (CODI VARCHAR(5) NOT NULL, COGA VARCHAR(5) NOT NULL, TYOR VARCHAR(5) NOT NULL);

Insertion request:

INSERT INTO BSCOBJ (CODI, COGA, TYOR) VALUES
('HELLO', 'MAT', 'REF'),
('BONJ', 'SOME', 'DAIL'),
('SOPA', 'KDA', 'RATIO');

Request given by Hibernate when trying to run the test code:

select r.restrain.tyOr from mypackage.BasicObject r where r.restrain.coDi = :coDi and r.restrain.coGa = :coGa

With the following values:

coDi = "BONJ";
coGa = "SOME";

Throws a NoResultException. I am expecting DAIL, from the second line of the INSERT request.

Body:
I have used @EmbeddedId only one time, but I think that you need @AttributeOverrides under your @EmbeddedId

@EmbeddedId
@AttributeOverrides({
    @AttributeOverride(name = "idpk", column = @Column(name="IDPK", nullable = false),
    @AttributeOverride(name = "code", column = @Column(name="CODE")
})

and remove your @Column annotations from FormulePK


问:
SQL Server parse a column's XML value into a table (for each row)
Sorry if the topic isn't very clear, but here is what I need to accomplish. I have a table like so:

```<code> user_id   | friends
==============================
75          | <friend name="bob" /><friend name="joe" />
76          | <friend name="bill" /><friend name="bob" />
77          | <friend name="sam" /><friend name="gary" /><friend name="john" />
</code>```

I need to get the number of friends (ie, number of XML nodes) for each user.
The resulting table should look like this:

```<code> user_id   | number_of_friends
==============================
75         | 2
76         | 2
77         | 3
</code>```

The following SQL can do it for one column at a time, but I'm not sure how to do it for all columns in one go.

```<code>DECLARE @x XML;

SELECT @x = pval
FROM [mytable]
WHERE uid=75 AND pkey='roster';

SELECT COUNT(t.c.value('@name', 'NVARCHAR(MAX)')) AS number_of_friends
FROM @x.nodes('//friend') t(c);
</code>```

This results in the table:

```<code>number_of_friends
=================
2
</code>```

答:
If it is SQL Server you can use XQuery count function:

```<code>SELECT  [user_id],
        friends.value('count(/friend)','integer') as number_of_friends
FROM YourTable
</code>```

In MySQL - ExtractValue():

```<code>SELECT  `user_id`,
        ExtractValue(`friends`, 'count(/friend)')
FROM `YourTable`
</code>```

Body:
Sorry if the topic isn't very clear, but here is what I need to accomplish. I have a table like so:

 user_id   | friends
==============================
75          | <friend name="bob" /><friend name="joe" />
76          | <friend name="bill" /><friend name="bob" />
77          | <friend name="sam" /><friend name="gary" /><friend name="john" />

I need to get the number of friends (ie, number of XML nodes) for each user.
The resulting table should look like this:

 user_id   | number_of_friends
==============================
75         | 2
76         | 2
77         | 3

The following SQL can do it for one column at a time, but I'm not sure how to do it for all columns in one go.

DECLARE @x XML;

SELECT @x = pval
FROM [mytable]
WHERE uid=75 AND pkey='roster';

SELECT COUNT(t.c.value('@name', 'NVARCHAR(MAX)')) AS number_of_friends
FROM @x.nodes('//friend') t(c);

This results in the table:

number_of_friends
=================
2

Body:
If it is SQL Server you can use XQuery count function:

SELECT  [user_id],
        friends.value('count(/friend)','integer') as number_of_friends
FROM YourTable

In MySQL - ExtractValue():

SELECT  `user_id`,
        ExtractValue(`friends`, 'count(/friend)')
FROM `YourTable`


问:
Using hidden frame to store or pass data between pages
We need to implement a mechanism to persist information between web pages in the same session. There is a lot of information on the client-side and passing it back and forth to the server across requests is something we want to avoid. HTML5 local storage is one option.

The other option mentioned was "using a hidden frame where the data is kept".  I am not sure what this option really means.

Does it mean keeping a hidden frame that holds on to the data across page requests?

How would this be accomplished? Are there any jquery plugins or sample code I can look at?

What are the advantages and disadvantages?

答:
I am not aware of a way where you can keep data in the main page and use a hidden iframe/frame to persist data. This is because once the main page is reloaded (when you go to another page), everything in the iframe is lost.

You would basically use the main page as your data-storage location. On top of the main page, you would superimpose an iframe. The user would interact with your site through the iframe. From the user's perspective, there is no difference. You can persist information by writing to the parent frame (the main page). Since the main page is never getting reloaded, you can persist data inside it.

I am not aware of any Javascript libraries that do this; I will take a look though.

Keep in mind that this might affect SEO and possibly navigation (not back/forward buttons). Another point, as Guffa noted, is that users cannot share links to your page since the URL in the address bar never changes (all interaction is via the iframe). So when your user sends someone a link, they will end up at the very first page.


问:
Most efficient solution for reading CLOB to String, and String to CLOB in Java?
I have a big CLOB (more than 32kB) that I want to read to a String, using StringBuilder. How do I do this in the most efficient way? I can not use the "int length" constructor for StringBuilder since the lenght of my CLOB is longer than a "int" and needs a "long" value.

I am not that confortable with the Java I/O classes, and would like to get some guidance.

Edit - I have tried with this code for clobToString():

```<code>private String clobToString(Clob data) {
    StringBuilder sb = new StringBuilder();
    try {
        Reader reader = data.getCharacterStream();
        BufferedReader br = new BufferedReader(reader);

        String line;
        while(null != (line = br.readLine())) {
            sb.append(line);
        }
        br.close();
    } catch (SQLException e) {
        // handle this exception
    } catch (IOException e) {
        // handle this exception
    }
    return sb.toString();
}
</code>```

答:
```<code>private String convertToString(java.sql.Clob data)
{
    final StringBuilder builder= new StringBuilder();

    try
    {
        final Reader         reader = data.getCharacterStream();
        final BufferedReader br     = new BufferedReader(reader);

        int b;
        while(-1 != (b = br.read()))
        {
            builder.append((char)b);
        }

        br.close();
    }
    catch (SQLException e)
    {
        log.error("Within SQLException, Could not convert CLOB to string",e);
        return e.toString();
    }
    catch (IOException e)
    {
        log.error("Within IOException, Could not convert CLOB to string",e);
        return e.toString();
    }
    //enter code here
    return builder.toString();
}
</code>```

Body:
I have a big CLOB (more than 32kB) that I want to read to a String, using StringBuilder. How do I do this in the most efficient way? I can not use the "int length" constructor for StringBuilder since the lenght of my CLOB is longer than a "int" and needs a "long" value.

I am not that confortable with the Java I/O classes, and would like to get some guidance.

Edit - I have tried with this code for clobToString():

private String clobToString(Clob data) {
    StringBuilder sb = new StringBuilder();
    try {
        Reader reader = data.getCharacterStream();
        BufferedReader br = new BufferedReader(reader);

        String line;
        while(null != (line = br.readLine())) {
            sb.append(line);
        }
        br.close();
    } catch (SQLException e) {
        // handle this exception
    } catch (IOException e) {
        // handle this exception
    }
    return sb.toString();
}


问:
Hide "Open in app" banner while using Universal links
I'm using Universal links and everything is working perfectly but I can't seem to hide the Open in app banner which shows in the safari. Is there any way to do this?

答:
Hey you can hide the smart banner by edit your apple-app-association file in the root directory of your website. You can control the banner on the pages you want to show.

you cannot hide the banner while using the universal links at the same time.
You can only hide the banner where you do not want the universal links to work by restricting the paths in apple-app-association file.

If you want to hide the banner form all the pages just add
"paths":["NOT /*"] in details object in this case universal links will not work.


问:
Speeding up Cloudant query for type text index
We have a table with this type of structure:

```<code> {_id:15_0, createdAt: 1/1/1, task_id:[16_0, 17_0, 18_0], table:”details”, a:b, c: d, more}
</code>```

We created indexes using

```<code> {
   "index": {},
   "name": "paginationQueryIndex",
   "type": "text"
 }
</code>```

It auto created

```<code> {
  "ddoc": "_design/28e8db44a5a0862xxx",
  "name": "paginationQueryIndex",
  "type": "text",
  "def": {
    "default_analyzer": "keyword",
    "default_field": {
    },
    "selector": {
    },
    "fields": [
    ],
    "index_array_lengths": true
  }
 }
</code>```

We are using the following query

```<code>{
  "selector": {
   "createdAt": { "$gt": 0 },
   "task_id": { "$in": [ "18_0" ] },
   "table": "details"
  },
  "sort": [ { "createdAt": "desc" } ],
  "limit”: 20
 }
</code>```

It takes 700-800 ms for first time, after that it decreases to 500-600 ms

Why does it take longer the first time?

Any way to speed up the query?

Any way to add indexes to specific fields if type is “text”?  (instead of indexing all the fields in these records)

答:
You could try creating the index more explicitly, defining the type of each field you wish to index e.g.:

```<code>{
  "index": {
    "fields": [
      {
        "name": "createdAt",
        "type": "string"
      },
      {
        "name": "task_id",
        "type": "string"
      },
      {
        "name": "table",
        "type": "string"
      }
    ]
  },
  "name": "myindex",
  "type": "text"
}
</code>```

Then your query becomes:

```<code>{
  "selector": {
    "createdAt": { "$gt": "1970/01/01" },
    "task_id": { "$in": [ "18_0" ] },
    "table": "details"
  },
  "sort": [ { "createdAt": "desc" } ],
  "limit": 20
}
</code>```

Notice that I used strings where the data type is a string.

If you're interested in performance, try removing clauses from your query one at-a-time to see if one is causing the performance problem. You can also look at the explanation of your query to see if it using your index correctly.

Documentation on creating an explicit text query index is here

Body:
We have a table with this type of structure:

 {_id:15_0, createdAt: 1/1/1, task_id:[16_0, 17_0, 18_0], table:”details”, a:b, c: d, more}

We created indexes using

 {
   "index": {},
   "name": "paginationQueryIndex",
   "type": "text"
 }

It auto created

 {
  "ddoc": "_design/28e8db44a5a0862xxx",
  "name": "paginationQueryIndex",
  "type": "text",
  "def": {
    "default_analyzer": "keyword",
    "default_field": {
    },
    "selector": {
    },
    "fields": [
    ],
    "index_array_lengths": true
  }
 }

We are using the following query

{
  "selector": {
   "createdAt": { "$gt": 0 },
   "task_id": { "$in": [ "18_0" ] },
   "table": "details"
  },
  "sort": [ { "createdAt": "desc" } ],
  "limit”: 20
 }

It takes 700-800 ms for first time, after that it decreases to 500-600 ms

Why does it take longer the first time?

Any way to speed up the query?

Any way to add indexes to specific fields if type is “text”?  (instead of indexing all the fields in these records)

Body:
You could try creating the index more explicitly, defining the type of each field you wish to index e.g.:

{
  "index": {
    "fields": [
      {
        "name": "createdAt",
        "type": "string"
      },
      {
        "name": "task_id",
        "type": "string"
      },
      {
        "name": "table",
        "type": "string"
      }
    ]
  },
  "name": "myindex",
  "type": "text"
}

Then your query becomes:

{
  "selector": {
    "createdAt": { "$gt": "1970/01/01" },
    "task_id": { "$in": [ "18_0" ] },
    "table": "details"
  },
  "sort": [ { "createdAt": "desc" } ],
  "limit": 20
}

Notice that I used strings where the data type is a string.

If you're interested in performance, try removing clauses from your query one at-a-time to see if one is causing the performance problem. You can also look at the explanation of your query to see if it using your index correctly.

Documentation on creating an explicit text query index is here


问:
Searching through a 2D array in python 2.7 if a char is in that position
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

```<code>students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))
</code>```

答:
You can use filter,

```<code>filter(lambda i: i[1]=='Y', students)
</code>```

Body:
Hi im trying to search through my array if a particular char is in that position and then printing it to the console.

this is my code so far.

students = [['Gary','Y'],['Steve','N'],['Tom','Y']]

for i in range (len(students)):
        if students[i,1] == 'Y':
            print (students(i,0))

Body:
You can use filter,

filter(lambda i: i[1]=='Y', students)


问:
Write image downloaded in the media content
I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.

I do not understand why because I set up the permission in the manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seb.sebastien.reddit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.

Thanks

答:
For Android Running on Android 6.0 (API level 23) and above , we need to add runtime permission to work, you can follow this link  Storage permission error in Marshmallow

----Updated ----

Code reference

```<code>public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}
</code>```

Permission result callback:

```<code>@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}
</code>```

Body:
I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.

I do not understand why because I set up the permission in the manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seb.sebastien.reddit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.

Thanks

Body:
For Android Running on Android 6.0 (API level 23) and above , we need to add runtime permission to work, you can follow this link  Storage permission error in Marshmallow

----Updated ----

Code reference

public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

Permission result callback:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}


问:
toggle pseudo class :active with css/jquery
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

```<code>(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);
</code>```

And the HTML around the Elements we are looking for

```<code><div class="helpmark">
    <img class="emoticon" src="http://*********/plugins/cute/static/resource/SD-CGM-TT/help_16.gif"> </div>
<div class="description">
    <p>Hier können Sie einen kurzen Betreff einfügen</p>
</div>
</code>```

by clicking on .helpmark .description is displayed

And the CSS i have

```<code>.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}
</code>```

I hope anybody can help me.

Best regards,
Stephan

答:
$(".tab_button").click(function(){
 $(".tab_description").slideToggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tab_button{
  background: #990000 none repeat scroll 0 0;
    cursor: pointer;
    height: 30px;
    width: 40px;
}
.tab_description{
   border: 1px solid #000000;
    display: none;
    max-width: 500px;
    padding: 15px;
    text-align: justify;
}
.tab_description p{
 margin:0px;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis massa nec odio rutrum, eget luctus metus vestibulum. Aliquam id volutpat eros, sit amet imperdiet risus. Vivamus a nisi enim. Curabitur accumsan rutrum egestas. Morbi orci purus, vehicula non risus ac, auctor tincidunt tortor. Vivamus felis lectus, scelerisque sed turpis vel, aliquet vehicula tellus. Vestibulum sit amet lorem sodales, malesuada purus a, dapibus turpis. Phasellus imperdiet eros leo, sit amet sollicitudin neque sodales non.

```

Body:
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('
'
+ ''
+ ' @message'
+   '
');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);

And the HTML around the Elements we are looking for

Hier können Sie einen kurzen Betreff einfügen

by clicking on .helpmark .description is displayed

And the CSS i have

.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}

I hope anybody can help me.

Best regards,
Stephan

Body:
$(".tab_button").click(function(){
 $(".tab_description").slideToggle();
});

.tab_button{
  background: #990000 none repeat scroll 0 0;
    cursor: pointer;
    height: 30px;
    width: 40px;
}
.tab_description{
   border: 1px solid #000000;
    display: none;
    max-width: 500px;
    padding: 15px;
    text-align: justify;
}
.tab_description p{
 margin:0px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab_button"> </div>
<div class="tab_description">
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis massa nec odio rutrum, eget luctus metus vestibulum. Aliquam id volutpat eros, sit amet imperdiet risus. Vivamus a nisi enim. Curabitur accumsan rutrum egestas. Morbi orci purus, vehicula non risus ac, auctor tincidunt tortor. Vivamus felis lectus, scelerisque sed turpis vel, aliquet vehicula tellus. Vestibulum sit amet lorem sodales, malesuada purus a, dapibus turpis. Phasellus imperdiet eros leo, sit amet sollicitudin neque sodales non. </p>
</div>


问:
Check if dynamically added element is ready
I'm trying to find a way for checking if a dynamically added HTML element is ready.

I have a button that when clicked, it starts to animate and on-click it recreates existing iframe. The idea to do that is new iframe comes with something needed in it.
I want to check if the iframe ready (not added but real mean, is the elements in it loaded?) and stop the animation.

Have any idea?

```<code>var frm = $('#allin');
frm.submit(function (ev) {
    $('#loading').show(); //here I show the loading animate
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            $('#framewrap').html('');
            var nfr = document.createElement('iframe');
            $(nfr).attr('src','iframe.php');
            $(nfr).attr('id','frame');
            $(nfr).attr('class','grid');
            $('#framewrap').html(nfr);
            $('#frame').ready(function(){
            $('#loading').fadeOut(); //here I wanted to stop it
            });
        }
    });

    ev.preventDefault();
});
</code>```

答:
The best way to check whether to check whether the content of an iframe has fully loaded is using the load event, just as @Gaafar proposes:

```<code>$("#iframe").on("load", function() {
   // code to execute after the content has loaded.
}
</code>```

While your own answer suggests a viable alternative, it's not really the best option, because unless the content of both the parent window and the iframe are served by the same domain you will be blocked due to the Same-Origin Policy. So this solution has no value for other users that may be serving external iframes.

So, your code can be edited until it reaches the following optimal form:

```<code>var frm = $("#allin");
frm.submit(function(ev) {
  /* Show the loading. */
  $("#loading").show();

  /* Send an AJAX request. */
  $.ajax({
    type: frm.attr("method"),
    url: frm.attr("action"),
    data: frm.serialize(),
    success: function(data) {
      /* Create the iframe and set its properties. */
      var nfr = $("<iframe>", {
        "id": "frame",
        "class": "grid",
        "src": "iframe.php",
      });

      /* Set the 'load' event. */
      nfr.on("load", function () {
        /* Fade the loading out. */
        $("#loading").fadeOut();
      });

      /* Empty framewrap and the append the created iframe. */
      $("#framewrap").empty().append(nfr);
    }
  });

  /* Prevent the default behaviour. */
  ev.preventDefault();
});
</code>```

I've created a simple snippet to help illustrate my point using a timeout instead of an XMLHttpRequest for simplicity:

Snippet:

/* ----- JavaScript ----- */
setTimeout(function () {
  /* Create the iframe and set its properties. */
  var nfr = $("", {
    "id": "frame",
    "class": "grid",
    "src": "https://example.com",
  });

  /* Set the 'load' event. */
  nfr.on("load", function () {
    /* Fade the loading out. */
    $("#loading").fadeOut();
  });

  /* Empty framewrap and the append the created iframe. */
  $("#framewrap").empty().append(nfr);
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* ----- CSS ----- */
#loading {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
  background: black;
}

#frame {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
}</code>```

```
</div>
</div>
</p>

<hr>

<p>As you have mentioned in a comment of yours, <em>"There already is an iframe with same name..."</em>, an <code>iframe</code> with the same name already exists and that's why <code>load</code> doesn't work for you.</p>

<p>I'm not sure exactly what you mean, because you say the <code>iframe</code> already exists, but you create it <em>(again?)</em> in the code you have added to your question, but the following snippet proves that even though the <code>iframe</code> may exist before the <code>load</code> event listener is attached by just changing the <code>src</code> attribute you can get it to work:</p>

<p><strong>Snippet:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* ----- JavaScript ----- */
setTimeout(function () {
  /* Cache the iframe. */
  var nfr = $("#frame");

  /* Res-set the 'src' attribute. */
  nfr[0].src = nfr[0].src;

  /* Set the 'load' event. */
  $("#frame").on("load", function () {
    /* Fade the loading out. */
    $("#loading").fadeOut();
  });
}, 1000);</code>```

/* ----- CSS ----- */
#loading {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
  background: black;
}

#frame {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "framewrap">
  <iframe id = "frame" class = "grid" src = "https://example.com"></iframe>
</div>
<div id = "loading"></div></code>```

Body:
I'm trying to find a way for checking if a dynamically added HTML element is ready.

I have a button that when clicked, it starts to animate and on-click it recreates existing iframe. The idea to do that is new iframe comes with something needed in it.
I want to check if the iframe ready (not added but real mean, is the elements in it loaded?) and stop the animation.

Have any idea?

var frm = $('#allin');
frm.submit(function (ev) {
    $('#loading').show(); //here I show the loading animate
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            $('#framewrap').html('');
            var nfr = document.createElement('iframe');
            $(nfr).attr('src','iframe.php');
            $(nfr).attr('id','frame');
            $(nfr).attr('class','grid');
            $('#framewrap').html(nfr);
            $('#frame').ready(function(){
            $('#loading').fadeOut(); //here I wanted to stop it
            });
        }
    });

    ev.preventDefault();
});

Body:
The best way to check whether to check whether the content of an iframe has fully loaded is using the load event, just as @Gaafar proposes:

$("#iframe").on("load", function() {
   // code to execute after the content has loaded.
}

While your own answer suggests a viable alternative, it's not really the best option, because unless the content of both the parent window and the iframe are served by the same domain you will be blocked due to the Same-Origin Policy. So this solution has no value for other users that may be serving external iframes.

So, your code can be edited until it reaches the following optimal form:

var frm = $("#allin");
frm.submit(function(ev) {
  /* Show the loading. */
  $("#loading").show();

  /* Send an AJAX request. */
  $.ajax({
    type: frm.attr("method"),
    url: frm.attr("action"),
    data: frm.serialize(),
    success: function(data) {
      /* Create the iframe and set its properties. */
      var nfr = $("<iframe>", {
        "id": "frame",
        "class": "grid",
        "src": "iframe.php",
      });

      /* Set the 'load' event. */
      nfr.on("load", function () {
        /* Fade the loading out. */
        $("#loading").fadeOut();
      });

      /* Empty framewrap and the append the created iframe. */
      $("#framewrap").empty().append(nfr);
    }
  });

  /* Prevent the default behaviour. */
  ev.preventDefault();
});

I've created a simple snippet to help illustrate my point using a timeout instead of an XMLHttpRequest for simplicity:

Snippet:

/* ----- JavaScript ----- */
setTimeout(function () {
  /* Create the iframe and set its properties. */
  var nfr = $("<iframe>", {
    "id": "frame",
    "class": "grid",
    "src": "https://example.com",
  });

  /* Set the 'load' event. */
  nfr.on("load", function () {
    /* Fade the loading out. */
    $("#loading").fadeOut();
  });

  /* Empty framewrap and the append the created iframe. */
  $("#framewrap").empty().append(nfr);
}, 1000);

/* ----- CSS ----- */
#loading {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
  background: black;
}

#frame {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
}

<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "framewrap"></div>
<div id = "loading"></div>

As you have mentioned in a comment of yours, "There already is an iframe with same name...", an iframe with the same name already exists and that's why load doesn't work for you.

I'm not sure exactly what you mean, because you say the iframe already exists, but you create it (again?) in the code you have added to your question, but the following snippet proves that even though the iframe may exist before the load event listener is attached by just changing the src attribute you can get it to work:

Snippet:

/* ----- JavaScript ----- */
setTimeout(function () {
  /* Cache the iframe. */
  var nfr = $("#frame");

  /* Res-set the 'src' attribute. */
  nfr[0].src = nfr[0].src;

  /* Set the 'load' event. */
  $("#frame").on("load", function () {
    /* Fade the loading out. */
    $("#loading").fadeOut();
  });
}, 1000);

/* ----- CSS ----- */
#loading {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
  background: black;
}

#frame {
  position: absolute;
  top: 0;
  height: 300px;
  width: 500px;
}

<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "framewrap">
  <iframe id = "frame" class = "grid" src = "https://example.com"></iframe>
</div>
<div id = "loading"></div>


问:
How to display thumbnail in floating container using Angular?
I've created a couple of sample product. Right now I able to display it just fine, but somehow the product is shown vertically. I would like it to appear horizontally once it max out the floating space next thumbnail can move onto the next line.

I've created a floating container and put my *ngfor inside it. Anything that I'm missing?

Here is my html code,

```<code><div class="text-center m-t-lg">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet">

  <h1>Public Shared Diary</h1>

  <div class="container-fluid">

  <div *ngFor="let pub_diary of diaries_temp;let i = index" [attr.data-index]="i">

    <div class="container-fluid">
      <div class="thumbnail" style="min-height:320px;height:320px;min-width:220px;width:220px;">
        <h2>Project title = {{pub_diary.project_name}}</h2>
        <img style="min-height:150px;height:150px;" src="{{pub_diary.project_image}}">
      </div>
    </div>

  </div>
  </div>

</div>
</code>```

and here is the current output. The red marking is where I would like the thumbnail to be.

答:
I've found the answer. I need to create a new div to include a

Issue solved.

Body:
I've created a couple of sample product. Right now I able to display it just fine, but somehow the product is shown vertically. I would like it to appear horizontally once it max out the floating space next thumbnail can move onto the next line.

I've created a floating container and put my *ngfor inside it. Anything that I'm missing?

Here is my html code,

  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet">

Public Shared Diary

Project title = {{pub_diary.project_name}}

and here is the current output. The red marking is where I would like the thumbnail to be.


问:
Java -Listen for variable changes in different class
This is for an Android app using Android Studio.

I have a class that listens to, and handles RFID reader events.
This is a separate class the the one associated with the activity. The RFID EPC is being read in the class that handles the RFID events, but I want to display this EPC on the UI, but I am not sure how to achieve this.

I have tried implementing ValueSubmittedListener, but not sure how to bind it all together to make it work:

what I have is

```<code>public class ReadMemoryActivity extends Activity implements
    View.OnClickListener, ValueSubmittedListener
{
    private TextView txtSelection = (TextView) findViewById(R.id.selection);//where EPC is to be displayed

    public void onSubmitted(String epc)
    {
       txtSelection.setText(epc);
    }
</code>```

and then the class for the Events

```<code>public class BaseReadAction  implements RfidReaderEventListener
{
    private List<ValueSubmittedListener> epcListener = new
    ArrayList<ValueSubmittedListener>();

    public void addListener(ValueSubmittedListener epc)
    {
        epcListener.clear();
        epcListener.add(epc);
    }

    private void notifyListeners()
    {
        for(ValueSubmittedListener epc : epcListener)
        {
            epc.onSubmitted(getSelection());
        }
    }

    public void setSelection(String epc) {

        setEPC = epc;
        notifyListeners();

    }
</code>```

I see there are quite a few listeners out there. had a look at TextWatcher as well, but at a glance it looks like it watches a TextView more than just a string variable. I'm still quite new to android dev and Java in general so my knowledge falls well short of what fits with what.

答:
So this is what I ended up doing to get it to work.
it is an answer, may not be the best answer, certainly not the only answer but here it is...

in the baseClass I added the following

```<code>public class BaseReadAction extends Activity  implements
RfidReaderEventListener {

  private String epcNo;
  private ChangeListener listener;

 public String getEpcNo()
 {
     return epcNo;
 }

 public void setEpcNo(String epc)
 {
     this.epcNo = epc;
     if(listener != null) listener.onChange();
 }

 public ChangeListener getListener() {
     return listener;
 }

 public void setListener(ChangeListener listener) {
     this.listener = listener;
 }

 public interface ChangeListener
 {
     void onChange();
 }
}
</code>```

Then in the UI class in the key_Down event that triggers the scanning I put this.

```<code>   // listens for event when epc is assigned to variable (ReadAction is an instance of BaseReadAction class
            ReadAction.setListener(new BaseReadAction.ChangeListener(){
            @Override
            public void onChange()
            {
                txtSelection.setText(ReadAction.getEpcNo());//sets the read value to the textView
            }
</code>```

Body:
This is for an Android app using Android Studio.

I have a class that listens to, and handles RFID reader events.
This is a separate class the the one associated with the activity. The RFID EPC is being read in the class that handles the RFID events, but I want to display this EPC on the UI, but I am not sure how to achieve this.

I have tried implementing ValueSubmittedListener, but not sure how to bind it all together to make it work:

what I have is

public class ReadMemoryActivity extends Activity implements
    View.OnClickListener, ValueSubmittedListener
{
    private TextView txtSelection = (TextView) findViewById(R.id.selection);//where EPC is to be displayed

    public void onSubmitted(String epc)
    {
       txtSelection.setText(epc);
    }

and then the class for the Events

public class BaseReadAction  implements RfidReaderEventListener
{
    private List<ValueSubmittedListener> epcListener = new
    ArrayList<ValueSubmittedListener>();

    public void addListener(ValueSubmittedListener epc)
    {
        epcListener.clear();
        epcListener.add(epc);
    }

    private void notifyListeners()
    {
        for(ValueSubmittedListener epc : epcListener)
        {
            epc.onSubmitted(getSelection());
        }
    }

    public void setSelection(String epc) {

        setEPC = epc;
        notifyListeners();

    }

I see there are quite a few listeners out there. had a look at TextWatcher as well, but at a glance it looks like it watches a TextView more than just a string variable. I'm still quite new to android dev and Java in general so my knowledge falls well short of what fits with what.

Body:
So this is what I ended up doing to get it to work.
it is an answer, may not be the best answer, certainly not the only answer but here it is...

in the baseClass I added the following

public class BaseReadAction extends Activity  implements
RfidReaderEventListener {

  private String epcNo;
  private ChangeListener listener;

 public String getEpcNo()
 {
     return epcNo;
 }

 public void setEpcNo(String epc)
 {
     this.epcNo = epc;
     if(listener != null) listener.onChange();
 }

 public ChangeListener getListener() {
     return listener;
 }

 public void setListener(ChangeListener listener) {
     this.listener = listener;
 }

 public interface ChangeListener
 {
     void onChange();
 }
}

Then in the UI class in the key_Down event that triggers the scanning I put this.

   // listens for event when epc is assigned to variable (ReadAction is an instance of BaseReadAction class
            ReadAction.setListener(new BaseReadAction.ChangeListener(){
            @Override
            public void onChange()
            {
                txtSelection.setText(ReadAction.getEpcNo());//sets the read value to the textView
            }


问:
Crawl Image using Apache Nutch
I installed Apache Nutch 2.3.1 and Solr 6.5.1 and MongoDB 3.4.7.
After I crawl urls that contain many images, in Solr and mongoDB isn't any image and video.
I also changed regex-urlfilter.txt file in  apache nutch and delete postfix that were related to image(.png,.jpeg,.gift,...).
After that I changed suffix-urlfilter.txt file and comment jpeg,gif,png too.

After do that works the Apache Nutch doesn't  crawl image.
Now I want to know how I can crawl image and see that in Solr?
As I read about it, I understand that I should create plug-ins.Is my impression correct?

答:
If I understand your question what you want to accomplish is extracting all the metadata from the images and indexing only this in Solr, right?

If Nutch is not even fetching your images then is more likely that some of the URL filters is excluding the URL from being fetched (check the logs). You need to describe your changes to the different files otherwise it will be impossible to help you.

Now, back to the original question, if you want to only index image URLs (along with the metadata) then you need to filter what you index into Solr. Unfortunately Nutch 2.3 doesn't offer (out of the box) this feature. In Nutch 1.x you could use mimetype-filter which allows you to specify what you want to index into Solr/ES depending on the mime type of the URL. My suggestion is to use Nutch 1.x unless you have a very good reason to use Nutch 2.x. Otherwise you could port the mimetype-filter plugin to 2.x or write your own IndexingFiler that supports your own logic.

Keep in mind that the information that you'll get in Solr is only limited to what tika can extract from the image file (metadata) which is usually not very well curated.

Title: Crawl Image using Apache Nutch


问:
Form sometimes fails to send $_POST data to PHP script
It is happening randomly. I've noticed it usually fails after 2nd or 3rd attempt. Using $_REQUEST doesn't seem to work either. Here is my form-

```<code><form method="post" action='updateImage' enctype="multipart/form-data">
<input type="hidden" name="uname" value="user">
<input type="hidden" name="image" value="photograph">
<label data-toggle="tooltip" data-placement="bottom" title="Click here to select an image">
<input type="file" name="file" accept="image/*" class="input" onchange="preview()" style="display: none;" required/>
</label>
<input type="submit" name="submit_student_photograph" value="Update Student Photograph">
</form>
</code>```

Edit 1: Here is the php script-

```<code>$foldername = $this->student()->setStudentData($_POST)->setFoldername();
  $filename = $foldername.'_photograph_1';
  $handle = new upload($_FILES['file']);
  if ($handle->uploaded) {
    $handle->file_new_name_body   = $filename;
    $handle->image_resize         = true;
    $handle->image_x              = 600;
    $handle->image_ratio_y        = true;
    $handle->process('all_student_files/'.$foldername);
    if ($handle->processed) {
      $handle->clean();
      $_SESSION['success'] = "Image has been updated.";
      header("Location:?controller=students&action=showStudentProfile&uname=".$_POST['uname']."#".$_POST['direction']);
    } else {
      $_SESSION['error'] = "There was a problem updating the Image. Please try again!";
      header("Location:?controller=students&action=showStudentProfile&uname=".$_POST['uname']."#".$_POST['direction']);
    }
  }
</code>```

答: Alright, I've found the cause for this problem! PHP settings doesn't accept any file that exceeds the size of 2 MB, hence the execution of my script fails.</p>

Body:
It is happening randomly. I've noticed it usually fails after 2nd or 3rd attempt. Using $_REQUEST doesn't seem to work either. Here is my form-

<form method="post" action='updateImage' enctype="multipart/form-data">
<input type="hidden" name="uname" value="user">
<input type="hidden" name="image" value="photograph">

<input type="file" name="file" accept="image/*" class="input" onchange="preview()" style="display: none;" required/>

<input type="submit" name="submit_student_photograph" value="Update Student Photograph">
</form>

Edit 1: Here is the php script-

$foldername = $this->student()->setStudentData($_POST)->setFoldername();
  $filename = $foldername.'_photograph_1';
  $handle = new upload($_FILES['file']);
  if ($handle->uploaded) {
    $handle->file_new_name_body   = $filename;
    $handle->image_resize         = true;
    $handle->image_x              = 600;
    $handle->image_ratio_y        = true;
    $handle->process('all_student_files/'.$foldername);
    if ($handle->processed) {
      $handle->clean();
      $_SESSION['success'] = "Image has been updated.";
      header("Location:?controller=students&action=showStudentProfile&uname=".$_POST['uname']."#".$_POST['direction']);
    } else {
      $_SESSION['error'] = "There was a problem updating the Image. Please try again!";
      header("Location:?controller=students&action=showStudentProfile&uname=".$_POST['uname']."#".$_POST['direction']);
    }
  }


问:
How can I initialize a std::vector with a size parameter and have each object constructed independently?
I like creating vectors with a given size and value, for example like this:

```<code>std::vector<std::string> names(10);
</code>```

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

```<code>#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}
</code>```

Console output:

```<code>0 0 0 0 0 0 0 0 0 0
</code>```

It does make sense when looking at std::vector's constructor:

```<code>explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());
</code>```

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

答:
There are two ways of doing that.

The nice, and C++0x way, is to take advantage of initializers list:

```<code>std::vector<UniqueNumber> vec = { UniqueNumber(0), UniqueNumber(1) };
</code>```

Obviously the issue here is that you have to specify them out in full.

In C++03, I would simply use a loop:

```<code>std::vector<UniqueNumber> vec;
vec.reserve(10);
for (size_t i = 0; i != 10; ++i) { vec.push_back(UniqueNumber(i)); }
</code>```

Of course this could perfectly get embedded in a builder function:

```<code>template <typename ValueType, typename Generator>
std::vector<ValueType> generateVector(size_t size, Generator generator)
{
  std::vector<ValueType> vec;
  vec.reserve(size);
  for (size_t i = 0; i != size; ++i) { vec.push_back(generator()); }
  return vec;
}
</code>```

With NRVO kicking in, it's about the same, and it lets you specify the values created freely.

The same can be achieved with the STL generate_n in <algorithm>, and I'll include a feel of lambda syntax.

```<code>std::vector<ValueType> vec;
size_t count = 0;
std::generate_n(std::back_inserter(vec), 10, [&]() { return Foo(++count); });
</code>```

Proposed by @Eugen in the comments :)

Note: wrt to "surprise", if you wish to have unique elements, perhaps that a vector is not the most suitable data structure. And if you actually need a vector, I would consider wrapping into a class to ensure, as an invariant, that elements are unique.

Body:
I like creating vectors with a given size and value, for example like this:

std::vector<std::string> names(10);

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}

Console output:

0 0 0 0 0 0 0 0 0 0

It does make sense when looking at std::vector's constructor:

explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

Body:
There are two ways of doing that.

The nice, and C++0x way, is to take advantage of initializers list:

std::vector<UniqueNumber> vec = { UniqueNumber(0), UniqueNumber(1) };

Obviously the issue here is that you have to specify them out in full.

In C++03, I would simply use a loop:

std::vector<UniqueNumber> vec;
vec.reserve(10);
for (size_t i = 0; i != 10; ++i) { vec.push_back(UniqueNumber(i)); }

Of course this could perfectly get embedded in a builder function:

template <typename ValueType, typename Generator>
std::vector<ValueType> generateVector(size_t size, Generator generator)
{
  std::vector<ValueType> vec;
  vec.reserve(size);
  for (size_t i = 0; i != size; ++i) { vec.push_back(generator()); }
  return vec;
}

With NRVO kicking in, it's about the same, and it lets you specify the values created freely.

The same can be achieved with the STL generate_n in <algorithm>, and I'll include a feel of lambda syntax.

std::vector<ValueType> vec;
size_t count = 0;
std::generate_n(std::back_inserter(vec), 10, [&]() { return Foo(++count); });

Proposed by @Eugen in the comments :)

Note: wrt to "surprise", if you wish to have unique elements, perhaps that a vector is not the most suitable data structure. And if you actually need a vector, I would consider wrapping into a class to ensure, as an invariant, that elements are unique.