问:
How to play and pause a Youtube video in a webpage while scrolling(using javascript or jquery)?
I mean to say that the video should not be playing when the page is loaded.
It should play when the video player comes in the focus of the window screen and it should pause when it is not visible on the screen using the scroll function.
I am not expecting to play videos on separate tabs. </p>

```<code>        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

            </head>
            <body>
                <p>
                    This is some text
                </p>

                <div style="margin-top:1000px;margin-bottom:1000px;">
                <iframe width="445" height="245" src="https://www.youtube.com/embed/LA5XtlyVILo?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>
               </div>

                <script type="text/javascript">
                   var videos = document.getElementsByTagName("iframe"), fraction = 0.8;

                    function checkScroll() {

                      for(var i = 0; i < videos.length; i++) {
                        var video = videos[i];

                        var x = 0,
                            y = 0,
                            w = video.width,
                            h = video.height,
                            r, //right
                            b, //bottom
                            visibleX, visibleY, visible,
                            parent;

                        parent = video;
                        while (parent && parent !== document.body) {
                          x += parent.offsetLeft;
                          y += parent.offsetTop;
                          parent = parent.offsetParent;

                        }

                        r = x + parseInt(w);
                        b = y + parseInt(h);

                        visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
                        visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));

                        visible = visibleX * visibleY / (w * h);

                        if (visible > fraction) {

                          playVideo();
                        } else if(visible < fraction) {
                          pauseVideo();

                        }

                      }

                    };

                    window.addEventListener('scroll', checkScroll, false);
                    window.addEventListener('resize', checkScroll, false);

                    //check at least once so you don't have to wait for scrolling for the video to start
                    window.addEventListener('load', checkScroll, false);

                    checkScroll();

                    function playVideo() {
                      player.playVideo();
                    }

                    function pauseVideo() {
                      player.pauseVideo();
                    }
                </script>
            </body>
        </html>
</code>```

答:
Correct Code for this question.</p>

```<code>        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <script src="//www.youtube.com/player_api"></script>
            </head>
            <body>
                <p>
                    This is some text
                </p>

                <div style="margin-top:1000px;margin-bottom:1000px;">
               </div>
                <div id="player"></div>
                <script type="text/javascript">
                    src="//www.youtube.com/player_api"
                    var player;
                    function onYouTubeIframeAPIReady() {
                      player = new YT.Player('player', {
                        height: '245',
                        width: '445',
                        videoId: 'FSfz0NxzN80',
                        rel:'0'
                      });
                    }

                   var videos = document.getElementsByTagName("iframe"), fraction = 0.8;
                    function checkScroll() {

                      for(var i = 0; i < videos.length; i++) {
                        var video = videos[i];

                        var x = 0,
                            y = 0,
                            w = video.width,
                            h = video.height,
                            r, //right
                            b, //bottom
                            visibleX, visibleY, visible,
                            parent;

                        parent = video;
                        while (parent && parent !== document.body) {
                          x += parent.offsetLeft;
                          y += parent.offsetTop;
                          parent = parent.offsetParent;
                        }

                        r = x + parseInt(w);
                        b = y + parseInt(h);

                        visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
                        visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
                        visible = visibleX * visibleY / (w * h);

                        if (visible > fraction) {
                      player.playVideo();
                        }
                        else if(visible < fraction) {
                      player.pauseVideo();
                        }
                      }
                    };

                    window.addEventListener('scroll', checkScroll, false);
                    window.addEventListener('resize', checkScroll, false);
                    //check at least once so you don't have to wait for scrolling for the video to start
                    window.addEventListener('load', checkScroll, false);

                    checkScroll();

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

Body:
I mean to say that the video should not be playing when the page is loaded.
It should play when the video player comes in the focus of the window screen and it should pause when it is not visible on the screen using the scroll function.
I am not expecting to play videos on separate tabs.

                    This is some text

Body:
Correct Code for this question.

        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <script src="//www.youtube.com/player_api"></script>
            </head>
            <body>
                <p>
                    This is some text
                </p>

                <div style="margin-top:1000px;margin-bottom:1000px;">
               </div>
                <div id="player"></div>
                <script type="text/javascript">
                    src="//www.youtube.com/player_api"
                    var player;
                    function onYouTubeIframeAPIReady() {
                      player = new YT.Player('player', {
                        height: '245',
                        width: '445',
                        videoId: 'FSfz0NxzN80',
                        rel:'0'
                      });
                    }

                   var videos = document.getElementsByTagName("iframe"), fraction = 0.8;
                    function checkScroll() {

                      for(var i = 0; i < videos.length; i++) {
                        var video = videos[i];

                        var x = 0,
                            y = 0,
                            w = video.width,
                            h = video.height,
                            r, //right
                            b, //bottom
                            visibleX, visibleY, visible,
                            parent;

                        parent = video;
                        while (parent && parent !== document.body) {
                          x += parent.offsetLeft;
                          y += parent.offsetTop;
                          parent = parent.offsetParent;
                        }

                        r = x + parseInt(w);
                        b = y + parseInt(h);

                        visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
                        visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
                        visible = visibleX * visibleY / (w * h);

                        if (visible > fraction) {
                      player.playVideo();
                        }
                        else if(visible < fraction) {
                      player.pauseVideo();
                        }
                      }
                    };

                    window.addEventListener('scroll', checkScroll, false);
                    window.addEventListener('resize', checkScroll, false);
                    //check at least once so you don't have to wait for scrolling for the video to start
                    window.addEventListener('load', checkScroll, false);

                    checkScroll();

                </script>
            </body>
        </html>


来源: stackexchange

问:
How to report JMX from Spark Streaming on EC2 to VisualVM?
I have been trying to get a Spark Streaming job, running on a EC2 instance to report to VisualVM using JMX.

As of now I have the following config file:

spark/conf/metrics.properties:

```<code>*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink
master.source.jvm.class=org.apache.spark.metrics.source.JvmSource

worker.source.jvm.class=org.apache.spark.metrics.source.JvmSource

driver.source.jvm.class=org.apache.spark.metrics.source.JvmSource

executor.source.jvm.class=org.apache.spark.metrics.source.JvmSource
</code>```

And I start the spark streaming job like this:
(the  -D bits I have added afterwards in the hopes of getting remote access to the ec2's jmx)

terminal:

```<code>spark/bin/spark-submit --class my.class.StarterApp --master local --deploy-mode client \
  project-1.0-SNAPSHOT.jar \
    -Dcom.sun.management.jmxremote \
    -Dcom.sun.management.jmxremote.port=54321 \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false
</code>```

答:
```<code>spark-submit --conf "spark.driver.extraJavaOptions=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8090  -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"/path/example/src/main/python/pi.py 10000
</code>```

Notes:the configurations format : --conf "params" . tested under spark 2.+

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to get a Spark Streaming job, running on a EC2 instance to report to VisualVM using JMX.

As of now I have the following config file:

spark/conf/metrics.properties:

*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink
master.source.jvm.class=org.apache.spark.metrics.source.JvmSource

worker.source.jvm.class=org.apache.spark.metrics.source.JvmSource

driver.source.jvm.class=org.apache.spark.metrics.source.JvmSource

executor.source.jvm.class=org.apache.spark.metrics.source.JvmSource

And I start the spark streaming job like this:
(the  -D bits I have added afterwards in the hopes of getting remote access to the ec2's jmx)

terminal:

spark/bin/spark-submit --class my.class.StarterApp --master local --deploy-mode client \
  project-1.0-SNAPSHOT.jar \
    -Dcom.sun.management.jmxremote \
    -Dcom.sun.management.jmxremote.port=54321 \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false

Body:
spark-submit --conf "spark.driver.extraJavaOptions=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8090  -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"/path/example/src/main/python/pi.py 10000

Notes:the configurations format : --conf "params" . tested under spark 2.+


问:
Programmatically getting the MAC of an Android device
I need to obtain the MAC address of my android device using Java. I've searched online, but I haven't found anything useful.</p>

答:
I founded this solution from http://robinhenniges.com/en/android6-get-mac-address-programmatically and it's working for me! Hope helps!  </p>

```<code>public static String getMacAddr() {
    try {
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                String hex = Integer.toHexString(b & 0xFF);
                if (hex.length() == 1)
                    hex = "0".concat(hex);
                res1.append(hex.concat(":"));
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
    }
    return "";
}
</code>```

Body:
I founded this solution from http://robinhenniges.com/en/android6-get-mac-address-programmatically and it's working for me! Hope helps!

public static String getMacAddr() {
    try {
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                String hex = Integer.toHexString(b & 0xFF);
                if (hex.length() == 1)
                    hex = "0".concat(hex);
                res1.append(hex.concat(":"));
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
    }
    return "";
}


问:
Count down to a week later from current date and time in Python?
I want to make an app that when run, it will get the current date and time from the user's computer, and then count down to a week later at the time of running.

So for example:

The user runs the app on 06-06-2017 11:00:00, it must do a count down to a deadline a week later and display the deadline date and time, and show a count down of how many days, hours, minutes and seconds are left.

EDIT:

So far I have only been able to get the date and time and the time increments normally per second. I am having difficulty decrementing it. Without the last line of the code the time decrements but does not update automatically. I have yet to find a way to perform a count down from a week in advance.

```<code>def updateTime():
    X = 1
    t = datetime.datetime.now()
    s = t.replace(microsecond=0)
    result = s - datetime.timedelta(seconds=X)
    future = s + datetime.timedelta(days=7, hours=0, minutes=0, seconds=0)
    lblTime.configure(text=result, font=("", 14))
    lblTime.after(100, updateTime)
</code>```

答:
You definitely want to calculate the target time only once instead of getting it every time the updateTime handler runs. Furthermore, you can simply do arithmetic on datetime objects to get a timedelta object back which you can then display in your GUI.

Here is an example that is printing the output to the console. You can probably adjust this as needed to make it display in your GUI.

```<code>import datetime

target_time = datetime.datetime.now() + datetime.timedelta(days=7)
target_time = target_time.replace(microsecond=0)

def get_remaining_time():
    delta = target_time - datetime.datetime.now()

    hours = delta.seconds // 3600
    minutes = (delta.seconds % 3600) // 60
    seconds = delta.seconds % 60
    print('{} days, {} hours, {} minutes, {} seconds'.format(delta.days, hours, minutes, seconds))

while True:
    get_remaining_time()
</code>```

Body:
I want to make an app that when run, it will get the current date and time from the user's computer, and then count down to a week later at the time of running.

So for example:

The user runs the app on 06-06-2017 11:00:00, it must do a count down to a deadline a week later and display the deadline date and time, and show a count down of how many days, hours, minutes and seconds are left.

EDIT:

So far I have only been able to get the date and time and the time increments normally per second. I am having difficulty decrementing it. Without the last line of the code the time decrements but does not update automatically. I have yet to find a way to perform a count down from a week in advance.

def updateTime():
    X = 1
    t = datetime.datetime.now()
    s = t.replace(microsecond=0)
    result = s - datetime.timedelta(seconds=X)
    future = s + datetime.timedelta(days=7, hours=0, minutes=0, seconds=0)
    lblTime.configure(text=result, font=("", 14))
    lblTime.after(100, updateTime)

Body:
You definitely want to calculate the target time only once instead of getting it every time the updateTime handler runs. Furthermore, you can simply do arithmetic on datetime objects to get a timedelta object back which you can then display in your GUI.

Here is an example that is printing the output to the console. You can probably adjust this as needed to make it display in your GUI.

import datetime

target_time = datetime.datetime.now() + datetime.timedelta(days=7)
target_time = target_time.replace(microsecond=0)

def get_remaining_time():
    delta = target_time - datetime.datetime.now()

    hours = delta.seconds // 3600
    minutes = (delta.seconds % 3600) // 60
    seconds = delta.seconds % 60
    print('{} days, {} hours, {} minutes, {} seconds'.format(delta.days, hours, minutes, seconds))

while True:
    get_remaining_time()


问:
Create a canvas with rounded corners in p5.js
I can't seem to find any information on the p5.js reference page as to how to round the corners on a canvas created through createCanvas(). This is possible with rectangles, as the fifth input the function takes is the border radius. This is not the case when creating a canvas.

I've put together a little example demonstrating a flat-cornered canvas with a curved-cornered rectangle inside, what I am aiming to reflect in the canvas' shape.

Any help would be appreciated. Thanks.

function setup() {
  createCanvas(200,200);
}

function draw() {
  background(32);
  rectangle();
}

function rectangle() {
  stroke(255);
  fill(255,255,255,100);
  rect(70,70,60,60,10);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.js"></script>
</head>
<body>
</body></code>```

答:
function setup() {
  createCanvas(200,200);
}

function draw() {
  background(32);
  rectangle();
}

function rectangle() {
  stroke(255);
  fill(255,255,255,100);
  rect(70,70,60,60,10);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  border-radius: 12px;
}</code>```

```

Do you want get something like that?
Via css i rounded the black canvas container.

Body:
function setup() {
  createCanvas(200,200);
}

function draw() {
  background(32);
  rectangle();
}

function rectangle() {
  stroke(255);
  fill(255,255,255,100);
  rect(70,70,60,60,10);
}

canvas {
  border-radius: 12px;
}

<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.js"></script>
</head>
<body>
</body>

Do you want get something like that?
Via css i rounded the black canvas container.


问:
How to avoid negative time between time difference?
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

```<code>@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}
</code>```

答:
If the time difference comes out negative, then add 24.

Simples!

(Obviously this will ignore overnight changes to daylight saving time, so your best bet really is to do this properly using time duration objects. That said though, you'll then need to know more about the dates associated with the two times.)

Body:
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}


问:
AngularJS - Control ng-show through custom directive
----UPDATE, see below for original question----

I'm isolating the problem, and right now something here is messing with the ng-show, I can't control it directly.

VIEW

```<code><div class="alert alert-danger" ng-show="vm.errorNoExistePDF" data-translate="webclientesApp.policy.terms.errorPDF">
    Ocurrio un problema al tratar de recuperar el archivo.
</div>
</code>```

CONTROLLER

```<code> function PolicyController(Principal, Policy, $locale, $rootScope) {

        var vm = this;
        vm.polizas = null;
        vm.errorNoExistePDF = false;
</code>```

DIRECTIVE

```<code>function tablaPolizas(Principal, $locale, $state, $rootScope, $http, $window, $stateParams) {
var directive = {

    templateUrl: 'app/components/tabla-polizas/tabla-polizas.html',
    link: linkFn,

    ...

function linkFn($scope, $element, $attrs) {

vm.errorNoExistePDF = true;

...

angular.element('#tabla-polizas').on('click', '#terms', function() {
                    var table = angular.element('#tabla-polizas').DataTable();

        $http.get('/webclientes/api/policies/getPlanFile/'+datos, {
                        responseType: 'blob'
                    })
                    .success(function(data, response) {

                        ...

                    })
                    .error (function(data){
                        console.log("ERROR");
                        vm.errorNoExistePDF = true;
                    });
            });
</code>```

----ORIGINAL QUESTION----

I'm trying to show an alert message with a ng-show that calls a scope in the controller whose value (boolean) changes through a custom directive.

VIEW

```<code><div class="alert alert-danger" ng-show="vm.errorNoExistePDF" data-translate="webclientesApp.policy.terms.errorPDF">
    Ocurrio un problema al tratar de recuperar el archivo.
</div>
</code>```

CONTROLLER

```<code> function PolicyController(Principal, Policy, $locale, $rootScope) {

        var vm = this;
        vm.polizas = null;
        vm.errorNoExistePDF = false;
</code>```

DIRECTIVE

```<code> function tablaPolizas(Principal, $locale, $state, $rootScope, $http, $window, $stateParams) {
    var directive = {

        templateUrl: 'app/components/tabla-polizas/tabla-polizas.html',
        link: linkFn,
       restrict: "E",
       controller: function(){
        var vm = this;
        vm.errorNoExistePDF = false;
        },
        controllerAs: 'vm'
    }

    return directive;

    function linkFn($scope, $element, $attrs) {

        var vm = this;
        var urlIdioma = null;
        var table = angular.element('#tabla-polizas');
        var dataRow = null;
        var id = null;
        var estaFila = null;
        vm.errorNoExistePDF = false;

        ...

        $http.get('/webclientes/api/policies/getPlanFile/'+datos, {
                            responseType: 'blob'
                        })
                        .success(function(data, response) {

                            var file = new Blob([data], {
                                type: 'application/pdf'
                            });
                            var fileURL = URL.createObjectURL(file);

                            if ($window.navigator && $window.navigator.msSaveOrOpenBlob) {
                                    $window.navigator.msSaveOrOpenBlob(file);
                            }else
                            $window.open(fileURL);
                        })
                        .error (function(data){
                            console.log("ERROR");
                            vm.errorNoExistePDF = true;
                        });
                });
</code>```

What should be happening here is that when user clicks into a Datatable button, if there's a bad response from server, ng-show (vm.errorNoExistePDF) should trigger and show the message, but I'm failing to understand the logic of linking directives and controllers.

Please help me understand this.

答:
I think the issue is related with the scope, if you use controllerAs syntax with a directive and you want to bind the outer scope to the directive's controller's scope you should use bindToController: true.

So you can try using this directive definition:

```<code>var directive = {
    templateUrl: 'app/components/tabla-polizas/tabla-polizas.html',
    link: linkFn,
    restrict: "E",
    scope: {
        errorNoExistePDF: '@'
    },
    bindToController: true,
    controller: function(){
        var vm = this;
        vm.errorNoExistePDF = false;
    },
    controllerAs: 'vm'
}
</code>```

Body:
----UPDATE, see below for original question----

I'm isolating the problem, and right now something here is messing with the ng-show, I can't control it directly.

VIEW

    Ocurrio un problema al tratar de recuperar el archivo.

CONTROLLER

 function PolicyController(Principal, Policy, $locale, $rootScope) {

        var vm = this;
        vm.polizas = null;
        vm.errorNoExistePDF = false;

DIRECTIVE

function tablaPolizas(Principal, $locale, $state, $rootScope, $http, $window, $stateParams) {
var directive = {

    templateUrl: 'app/components/tabla-polizas/tabla-polizas.html',
    link: linkFn,

    ...

function linkFn($scope, $element, $attrs) {

vm.errorNoExistePDF = true;

...

angular.element('#tabla-polizas').on('click', '#terms', function() {
                    var table = angular.element('#tabla-polizas').DataTable();

        $http.get('/webclientes/api/policies/getPlanFile/'+datos, {
                        responseType: 'blob'
                    })
                    .success(function(data, response) {

                        ...

                    })
                    .error (function(data){
                        console.log("ERROR");
                        vm.errorNoExistePDF = true;
                    });
            });

----ORIGINAL QUESTION----

I'm trying to show an alert message with a ng-show that calls a scope in the controller whose value (boolean) changes through a custom directive.

VIEW

    Ocurrio un problema al tratar de recuperar el archivo.

CONTROLLER

 function PolicyController(Principal, Policy, $locale, $rootScope) {

        var vm = this;
        vm.polizas = null;
        vm.errorNoExistePDF = false;

DIRECTIVE

 function tablaPolizas(Principal, $locale, $state, $rootScope, $http, $window, $stateParams) {
    var directive = {

        templateUrl: 'app/components/tabla-polizas/tabla-polizas.html',
        link: linkFn,
       restrict: "E",
       controller: function(){
        var vm = this;
        vm.errorNoExistePDF = false;
        },
        controllerAs: 'vm'
    }

    return directive;

    function linkFn($scope, $element, $attrs) {

        var vm = this;
        var urlIdioma = null;
        var table = angular.element('#tabla-polizas');
        var dataRow = null;
        var id = null;
        var estaFila = null;
        vm.errorNoExistePDF = false;

        ...

        $http.get('/webclientes/api/policies/getPlanFile/'+datos, {
                            responseType: 'blob'
                        })
                        .success(function(data, response) {

                            var file = new Blob([data], {
                                type: 'application/pdf'
                            });
                            var fileURL = URL.createObjectURL(file);

                            if ($window.navigator && $window.navigator.msSaveOrOpenBlob) {
                                    $window.navigator.msSaveOrOpenBlob(file);
                            }else
                            $window.open(fileURL);
                        })
                        .error (function(data){
                            console.log("ERROR");
                            vm.errorNoExistePDF = true;
                        });
                });

What should be happening here is that when user clicks into a Datatable button, if there's a bad response from server, ng-show (vm.errorNoExistePDF) should trigger and show the message, but I'm failing to understand the logic of linking directives and controllers.

Please help me understand this.

Body:
I think the issue is related with the scope, if you use controllerAs syntax with a directive and you want to bind the outer scope to the directive's controller's scope you should use bindToController: true.

So you can try using this directive definition:

var directive = {
    templateUrl: 'app/components/tabla-polizas/tabla-polizas.html',
    link: linkFn,
    restrict: "E",
    scope: {
        errorNoExistePDF: '@'
    },
    bindToController: true,
    controller: function(){
        var vm = this;
        vm.errorNoExistePDF = false;
    },
    controllerAs: 'vm'
}


问:
Two Material Circular Mesh - Gmsh
I have the following .geo for GMSH:

```<code>cl__1 = 1.125;
Point(1) = {0, 0, 0, cl__1};
Point(2) = {1, 0, 0, cl__1};
Point(3) = {1, 1, 0, cl__1};
Point(4) = {0, 1, 0, cl__1};
Point(5) = {0.350000,0.100000,cl__1};
Point(6) = {0.350000,0.350000,cl__1};
Point(7) = {0.100000,0.350000,cl__1};
Point(8) = {0.85,0.85,cl__1};
Line(1) = {1, 2};
Line(2) = {2, 3};
Line(3) = {3, 4};
Line(4) = {4, 1};
Circle(5) = {5,6,7};
Line(6) = {7,8};
Line(7) = {8,5};
Line Loop(1) = {1, 2, 3, 4};
Line Loop(2) = {5,6,7};
Plane Surface(1) = {1,2};
Plane Surface(2) = {2};
Circle {5} In Surface {2};
Line {6} In Surface {2};
Line {7} In Surface {2};
</code>```

I have drawn exactly the geometry I want to build but somehow Gmsh is only meshing inside Plane Surface 2.
Is there anything wrong in this code?

Title: Two Material Circular Mesh - Gmsh

Body:
I have the following .geo for GMSH:

cl__1 = 1.125;
Point(1) = {0, 0, 0, cl__1};
Point(2) = {1, 0, 0, cl__1};
Point(3) = {1, 1, 0, cl__1};
Point(4) = {0, 1, 0, cl__1};
Point(5) = {0.350000,0.100000,cl__1};
Point(6) = {0.350000,0.350000,cl__1};
Point(7) = {0.100000,0.350000,cl__1};
Point(8) = {0.85,0.85,cl__1};
Line(1) = {1, 2};
Line(2) = {2, 3};
Line(3) = {3, 4};
Line(4) = {4, 1};
Circle(5) = {5,6,7};
Line(6) = {7,8};
Line(7) = {8,5};
Line Loop(1) = {1, 2, 3, 4};
Line Loop(2) = {5,6,7};
Plane Surface(1) = {1,2};
Plane Surface(2) = {2};
Circle {5} In Surface {2};
Line {6} In Surface {2};
Line {7} In Surface {2};

I have drawn exactly the geometry I want to build but somehow Gmsh is only meshing inside Plane Surface 2.
Is there anything wrong in this code?

Body:
The point definition for points 5 - 8 are not in plane z = 0 they are in plane (z = cl_1). A suggestion, when you write this kind of files try to arrange things in the following way:

cl_1 = 1.125;
Point(1) = {0       , 0       , 0, cl_1};
Point(2) = {1       , 0       , 0, cl_1};
Point(3) = {1       , 1       , 0, cl_1};
Point(4) = {0       , 1       , 0, cl_1};
Point(5) = {0.350000, 0.100000, 0, cl_1};
Point(6) = {0.350000, 0.350000, 0, cl_1};
Point(7) = {0.100000, 0.350000, 0, cl_1};
Point(8) = {0.85    , 0.85    , 0, cl_1};
Line(1) = {1, 2};
Line(2) = {2, 3};
Line(3) = {3, 4};
Line(4) = {4, 1};
Circle(5) = {5,6,7};
Line(6) = {7,8};
Line(7) = {8,5};
Line Loop(1) = {1, 2, 3, 4};
Line Loop(2) = {5,6,7};
Plane Surface(8) = {1, 2};
Plane Surface(9) = {2};

you can save lot of time only by inspection.


问:
Mysql search 2 columns and order by more relevant
I am building a website with articles section, I am looking for a search functionality that will search the article title and the article content  for results that contain all search term, and then will return article result that contains the search term words such as the following example:
Search Term: "Facebook tweaks News Feed to clamp down on 'spammy' and misleading advertising".

It will be ideal to return all result that matches the exact term, then search by more relevant result such as "Facebook tweaks News Feed" etc.

The following is the code I did so far:

```<code>"p.Title,p.ID,p.Publish_Date, p.Sponsored, p.Featured, p.Seo_Link, p.Content,
                (SELECT GROUP_CONCAT(t.Tag_ID)
                FROM Tag_Post_Relationship t
                WHERE p.ID  =  t.Post_ID) AS Tags,
                MATCH (Title, Content) AGAINST ('".$search_term."'IN BOOLEAN MODE) AS Relevance FROM Posts p WHERE NOT Post_Type = 'p'   AND Publish_Date < '{$dateNow}'   AND Visibility = 'p' AND
                (MATCH (p.Title, p.Content) AGAINST ('".$search_term."' IN BOOLEAN MODE))

                ORDER BY Relevance DESC"
</code>```

答:
To do this effectively in an SQL database you need to implement a fuzzy text-comparison algorithm such as Levenshtein distance as a function or proc you can call. This will allow you to rank your articles based on how closely they match your search term. An example of Levenshtein distance in SQL is here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=66781.

You use the algorithm in a stored procedure which is executed when a search is requested. The stored proc would compare the search term to each title and article and order the results by the closest match, which would be 1 for an exact match.

Outside of SQL there are also numerous packages for advanced text analysis that can be used at the API level. I've used Python's Jellyfish and NLTK libraries with good results.

Another option is to use something like Apache Solr (http://lucene.apache.org/solr/features.html) or Elastic Search which provides a ready-to-go API for full text search across documents and data. This will add complexity to your architecture though.

Body:
I am building a website with articles section, I am looking for a search functionality that will search the article title and the article content  for results that contain all search term, and then will return article result that contains the search term words such as the following example:
Search Term: "Facebook tweaks News Feed to clamp down on 'spammy' and misleading advertising".

It will be ideal to return all result that matches the exact term, then search by more relevant result such as "Facebook tweaks News Feed" etc.

The following is the code I did so far:

"p.Title,p.ID,p.Publish_Date, p.Sponsored, p.Featured, p.Seo_Link, p.Content,
                (SELECT GROUP_CONCAT(t.Tag_ID)
                FROM Tag_Post_Relationship t
                WHERE p.ID  =  t.Post_ID) AS Tags,
                MATCH (Title, Content) AGAINST ('".$search_term."'IN BOOLEAN MODE) AS Relevance FROM Posts p WHERE NOT Post_Type = 'p'   AND Publish_Date < '{$dateNow}'   AND Visibility = 'p' AND
                (MATCH (p.Title, p.Content) AGAINST ('".$search_term."' IN BOOLEAN MODE))

                ORDER BY Relevance DESC"


问:
How to use Jackson to deserialize a JSON document with dynamic keys?
I have such a JSON formatted string and the key is a random number.

```<code>{
  "tasks": {
    "0": {
     "key1": "value1"
    },
    "100": {
      "key1": "value2"
    }
}
</code>```

How can I convert it to Java object by using Jackson?

How to define the Java class so that I can use Jackson like this?

```<code>ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(myStr, XXXX);
</code>```

答:
There are a couple of approaches you could use depending on your needs:

Using JsonNode

You could parse your JSON into the Jackson tree model. That is, into JsonNode from the com.fasterxml.jackson.databind package:

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);
```

<p>You also can use Jackson to parse a <code>JsonNode</code> into a POJO:</p>

<pre class="lang-java prettyprint-override"><code>MyBean bean = mapper.treeToValue(jsonNode, MyBean.class);
</code>```

Using Map<String, Object>

Depending on your requirements, you could use a Map<String, Object> instead of JsonNode:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsed = mapper.readValue(json,
                                 new TypeReference<Map<String, Object>>() {});
```

<p>To convert a map into a POJO, use:</p>

<pre class="lang-java prettyprint-override"><code>MyBean bean = mapper.convertValue(map, MyBean.class);
</code>```

Body:
I have such a JSON formatted string and the key is a random number.

{
  "tasks": {
    "0": {
     "key1": "value1"
    },
    "100": {
      "key1": "value2"
    }
}

How can I convert it to Java object by using Jackson?

How to define the Java class so that I can use Jackson like this?

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(myStr, XXXX);

Body:
There are a couple of approaches you could use depending on your needs:

Using JsonNode

You could parse your JSON into the Jackson tree model. That is, into JsonNode from the com.fasterxml.jackson.databind package:

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);

You also can use Jackson to parse a JsonNode into a POJO:

MyBean bean = mapper.treeToValue(jsonNode, MyBean.class);

Using Map<String, Object>

Depending on your requirements, you could use a Map<String, Object> instead of JsonNode:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsed = mapper.readValue(json,
                                 new TypeReference<Map<String, Object>>() {});

To convert a map into a POJO, use:

MyBean bean = mapper.convertValue(map, MyBean.class);


问:
No $on function on $scope in Angular.js unit tests, but is on $rootScope in test
I'm trying to run a simple unit test that just creates a controller (a colleague wrote it, so others could add their own unit tests), however changes I've made are stopping even this from passing. The colleague doesn't know why it's not working. Here is the simple test.

Test

```<code>describe("My Controller", function () {
    var $q, $controller, $scope, $rootScope;
    var createCtrl;
    beforeEach(function () {
        module('myModule');
    });
    beforeEach(inject(function (_$q_, _$rootScope_, _$controller_, _$httpBackend_) {
        $controller = _$controller_;
        $scope = _$rootScope_.$new();
        $scope.$parent = {
            dummyFn: function() {}
        };
        createCtrl = function createCtrl() {
            return $controller('MyController', {
                '$q': _$q_,
                '$scope': $scope
            });
        };
    }));
}));
describe("Controller stability", function() {
    it("should initialise the controller without error", function() {
        var controller = createCtrl();
    });
});
</code>```

As you can see the above test doesn't do anything but catch error's in creating the controller.

Here is a mock up of the code in the controller:

Code

```<code>(function() {
    "use strict";
     const {angular} = window;
     angular.module('myModule', [])
     .controller('MyController', MyController);
     MyController.$inject = ['$routeParams', '$scope'];
     function MyController($routeParams, $scope) {
         var vm = this;
         $scope.$on('event-name', function(event, eventData) {
             vm.eventData = eventData;
             updateData();
         })
     }
})();
</code>```

The error's I get depend on how I run karma, but are loosely related it seems.

If I run it form the command line with a gulp task, I get that:

```<code>TypeError: undefined is not an object (evaluating 'current.$$listenerCount[name]') in dist/app/vendor.js
$on@dist/app/vendor<line number>
</code>```

And the stack trace through angular and back to the test.

If I run it in Karma's debug window:

```<code>Uncaught TypeError: Cannot read property 'event-name' of undefined
at Scope.$get.Scope.$on (hostname.com:9876/base/dist/vendor.js:<line number>)
</code>```

And then down again though the stack trace.

Looking at the code for $on I can't see why it would fail in those two different ways.

Changing the controller code to use $rootScope.$on seems to mollify the tests, but I don't understand why the tests require that, and not the main app.

Why is $on not on $scope in the test, when it is in the main app?

答:
The issue comes from the fact that $on cares about the $parent.

It will check the parent and try and see if there's another listener there, but because the parent wasn't created 'properly' it can't find it and dies.

Instead, instantiate it with:

```<code>$scope.$parent = angular.extend(_$rootScope_.$new(), {
        dummyFn: function() {}
});
</code>```

That way it will have all the properties angularjs expects it to have, when $on is called.

Body:
I'm trying to run a simple unit test that just creates a controller (a colleague wrote it, so others could add their own unit tests), however changes I've made are stopping even this from passing. The colleague doesn't know why it's not working. Here is the simple test.

Test

describe("My Controller", function () {
    var $q, $controller, $scope, $rootScope;
    var createCtrl;
    beforeEach(function () {
        module('myModule');
    });
    beforeEach(inject(function (_$q_, _$rootScope_, _$controller_, _$httpBackend_) {
        $controller = _$controller_;
        $scope = _$rootScope_.$new();
        $scope.$parent = {
            dummyFn: function() {}
        };
        createCtrl = function createCtrl() {
            return $controller('MyController', {
                '$q': _$q_,
                '$scope': $scope
            });
        };
    }));
}));
describe("Controller stability", function() {
    it("should initialise the controller without error", function() {
        var controller = createCtrl();
    });
});

As you can see the above test doesn't do anything but catch error's in creating the controller.

Here is a mock up of the code in the controller:

Code

(function() {
    "use strict";
     const {angular} = window;
     angular.module('myModule', [])
     .controller('MyController', MyController);
     MyController.$inject = ['$routeParams', '$scope'];
     function MyController($routeParams, $scope) {
         var vm = this;
         $scope.$on('event-name', function(event, eventData) {
             vm.eventData = eventData;
             updateData();
         })
     }
})();

The error's I get depend on how I run karma, but are loosely related it seems.

If I run it form the command line with a gulp task, I get that:

TypeError: undefined is not an object (evaluating 'current.$$listenerCount[name]') in dist/app/vendor.js
$on@dist/app/vendor<line number>

And the stack trace through angular and back to the test.

If I run it in Karma's debug window:

Uncaught TypeError: Cannot read property 'event-name' of undefined
at Scope.$get.Scope.$on (hostname.com:9876/base/dist/vendor.js:<line number>)

And then down again though the stack trace.

Looking at the code for $on I can't see why it would fail in those two different ways.

Changing the controller code to use $rootScope.$on seems to mollify the tests, but I don't understand why the tests require that, and not the main app.

Why is $on not on $scope in the test, when it is in the main app?

Body:
The issue comes from the fact that $on cares about the $parent.

It will check the parent and try and see if there's another listener there, but because the parent wasn't created 'properly' it can't find it and dies.

Instead, instantiate it with:

$scope.$parent = angular.extend(_$rootScope_.$new(), {
        dummyFn: function() {}
});

That way it will have all the properties angularjs expects it to have, when $on is called.


问:
Unable to delete a list element in C++
I am working on a small game and came across a big problem with lists.

Here's my code:

```<code>void cCollisionManager::checkCollision(cPlayer * pPlayer, std::list<cAsteroid*> *asteroidList, std::list<cShot*> *ShotList)
{
    sf::FloatRect PlayerBox = pPlayer->getSprite()->getGlobalBounds();

    for (auto it : *asteroidList) {
        for (auto es : *ShotList) {
            sf::FloatRect asteroidboundingBox = it->getSprite()->getGlobalBounds();
            sf::FloatRect ShotBox = es->getSprite().getGlobalBounds();

            if (asteroidboundingBox.intersects(ShotBox)) {

                it = asteroidList->erase(it);

                *pPlayer->pPunkte += 1;
                std::cout << *pPlayer->pPunkte << std::endl;
            }

            if (asteroidboundingBox.intersects(PlayerBox)) {
                if (*pPlayer->phealth >= 0.f)
                    *pPlayer->phealth -= 0.5f;
            }
        }
    }
}
</code>```

I used SFML and basically everything works. But if I want to delete the colliding asteroid and the shot, the programs exits with an error. In the if loop I tried to erase the object, but the compiler also gives an error saying that the argument type is not the same as the object type I am giving to it.

EDIT
I had another look at the other question, you recommended to me, but still I haven't found out how to solve that problem. So  if I changed my code to a while loop, the game couldn't handle it, because the Collision Manager is actually called in every single Call of the SFML main loop. So it would just get stuck in my collision  loop. So I changed my code a bit, but still, things are not working.

答:
Don't modify sequences that are being enumerated with range-for. Use
  iterators and the appropriate result of an erase. – WhozCraig

This is actually the answer to it. I did the mistake - using a for loop and not a while loop and so I had some big issues and bad construction ideas for my code - luckily everything now works!
Here is my final code:

```<code>    auto it = asteroidList->begin();
auto es = ShotList->begin();

while (it != asteroidList->end()) {

    sf::FloatRect PlayerBox = pPlayer->getSprite()->getGlobalBounds();
    sf::FloatRect asteroidboundingBox = (*it)->getSprite()->getGlobalBounds();

    while (es != ShotList->end())
    {
        sf::FloatRect ShotBox = (*es)->getSprite().getGlobalBounds();

            if (asteroidboundingBox.intersects(ShotBox)) {
                it = asteroidList->erase(it);
                es = ShotList->erase(es);

                std::cout << "Asteroid destroyed" << std::endl;
                *pPlayer->pPunkte += 1;
                std::cout << *pPlayer->pPunkte << std::endl;
                }

        if (es != ShotList->end())
            es++;

    }
        if (asteroidboundingBox.intersects(PlayerBox))
        {
            if (*pPlayer->phealth > 3.f) {
                *pPlayer->phealth -= 5.f;
                it = asteroidList->erase(it);
            }
            else
                *pPlayer->pBStateAlive = false;
        }

    if (it != asteroidList->end()) {
        it++;
        es = ShotList->begin();

    }

}
</code>```

}

Title: Unable to delete a list element in C++

Body:
I am working on a small game and came across a big problem with lists.

Here's my code:

void cCollisionManager::checkCollision(cPlayer * pPlayer, std::list<cAsteroid*> *asteroidList, std::list<cShot*> *ShotList)
{
    sf::FloatRect PlayerBox = pPlayer->getSprite()->getGlobalBounds();

    for (auto it : *asteroidList) {
        for (auto es : *ShotList) {
            sf::FloatRect asteroidboundingBox = it->getSprite()->getGlobalBounds();
            sf::FloatRect ShotBox = es->getSprite().getGlobalBounds();

            if (asteroidboundingBox.intersects(ShotBox)) {

                it = asteroidList->erase(it);

                *pPlayer->pPunkte += 1;
                std::cout << *pPlayer->pPunkte << std::endl;
            }

            if (asteroidboundingBox.intersects(PlayerBox)) {
                if (*pPlayer->phealth >= 0.f)
                    *pPlayer->phealth -= 0.5f;
            }
        }
    }
}

I used SFML and basically everything works. But if I want to delete the colliding asteroid and the shot, the programs exits with an error. In the if loop I tried to erase the object, but the compiler also gives an error saying that the argument type is not the same as the object type I am giving to it.

EDIT
I had another look at the other question, you recommended to me, but still I haven't found out how to solve that problem. So  if I changed my code to a while loop, the game couldn't handle it, because the Collision Manager is actually called in every single Call of the SFML main loop. So it would just get stuck in my collision  loop. So I changed my code a bit, but still, things are not working.

Body:
Don't modify sequences that are being enumerated with range-for. Use
  iterators and the appropriate result of an erase. – WhozCraig

This is actually the answer to it. I did the mistake - using a for loop and not a while loop and so I had some big issues and bad construction ideas for my code - luckily everything now works!
Here is my final code:

    auto it = asteroidList->begin();
auto es = ShotList->begin();

while (it != asteroidList->end()) {

    sf::FloatRect PlayerBox = pPlayer->getSprite()->getGlobalBounds();
    sf::FloatRect asteroidboundingBox = (*it)->getSprite()->getGlobalBounds();

    while (es != ShotList->end())
    {
        sf::FloatRect ShotBox = (*es)->getSprite().getGlobalBounds();

            if (asteroidboundingBox.intersects(ShotBox)) {
                it = asteroidList->erase(it);
                es = ShotList->erase(es);

                std::cout << "Asteroid destroyed" << std::endl;
                *pPlayer->pPunkte += 1;
                std::cout << *pPlayer->pPunkte << std::endl;
                }

        if (es != ShotList->end())
            es++;

    }
        if (asteroidboundingBox.intersects(PlayerBox))
        {
            if (*pPlayer->phealth > 3.f) {
                *pPlayer->phealth -= 5.f;
                it = asteroidList->erase(it);
            }
            else
                *pPlayer->pBStateAlive = false;
        }

    if (it != asteroidList->end()) {
        it++;
        es = ShotList->begin();

    }

}

}


问:
httpClient.PostAsync returns "Method Not Allowed" (running in winform app)
I try to post to rest.

This is my code:

```<code>     string URL = "http://xxx.xxx.x.xx:8080/Name/NAME/";
     string urlParameters = "?key=T_PAPPS&value=sofsof";

     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(URL);

     client.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

     HttpResponseMessage response = client.PostAsync(URL, new StringContent(urlParameters)).Result;
</code>```

My app is WinForm application (not web).

What am I doing wrong?

Thanks for advance.

(restsharp returns same error (and there I also didn't success to change to application/x-www-form-urlencoded from application/json))

答:
If you're using querystring parameters (ie ?key=value) you do not need to post. Try replacing your last line with:

```<code>HttpResponseMessage response = client.GetAsync(URL + urlParameters).Result;
</code>```

You may also need to remove the final "/" in your URL string.

Body:
I try to post to rest.

This is my code:

     string URL = "http://xxx.xxx.x.xx:8080/Name/NAME/";
     string urlParameters = "?key=T_PAPPS&value=sofsof";

     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(URL);

     client.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

     HttpResponseMessage response = client.PostAsync(URL, new StringContent(urlParameters)).Result;

My app is WinForm application (not web).

What am I doing wrong?

Thanks for advance.

(restsharp returns same error (and there I also didn't success to change to application/x-www-form-urlencoded from application/json))

Body:
If you're using querystring parameters (ie ?key=value) you do not need to post. Try replacing your last line with:

HttpResponseMessage response = client.GetAsync(URL + urlParameters).Result;

You may also need to remove the final "/" in your URL string.


问:
Find missing number in sorted array
Whats wrong with this code ? Not able able to search missing number in a consecutive array using binary search.</p>

```<code>a = [1,2,3,4,5,7,8]

lent = len(a)
beg =0
end = lent-1

while beg < end:
    mid = (beg + end) / 2
    if (a[mid]-a[beg])==(mid - beg):
        beg = mid + 1
    else:
        end = mid -1
    if(beg == end):
        mid = (beg + end) / 2
        print "missing"
        print a[0]+ beg
</code>```

答:
Update #1: Yes, there was another one mistake. You're right. Here's updated version

Try this variant:

```<code>a = [1,2,3,4,5,7,8]

lent = len(a)
beg =0
end = lent-1

while beg < end:
    mid = (beg + end) / 2
    if (a[mid]-a[beg])==(mid - beg):
        beg = mid
    else:
        end = mid
    if abs(beg-end) <= 1:
        print "missing: %s" % (a[0] + max(beg, mid),)
</code>```

Result:

```<code>missing: 6
</code>```

Also, try use functions, so you could easily test and debug your code on different lists:

```<code>def find_missing(a):
    lent = len(a)
    beg =0
    end = lent-1

    while beg < end:
        mid = (beg + end) / 2
        if (a[mid]-a[beg])==(mid - beg):
            beg = mid
        else:
            end = mid
        if abs(beg-end) <= 1:
            return a[0] + max(beg, mid)

a = [1,2,3,4,5,7,8]
print find_missing(a)

a = [1,3,4,5,6]
print find_missing(a)

a = [1,2,3,4,5,7,8,9,10]
print find_missing(a)
</code>```

Result:

```<code>6
2
6
</code>```

Title: Find missing number in sorted array

Body:
Whats wrong with this code ? Not able able to search missing number in a consecutive array using binary search.

a = [1,2,3,4,5,7,8]

lent = len(a)
beg =0
end = lent-1

while beg < end:
    mid = (beg + end) / 2
    if (a[mid]-a[beg])==(mid - beg):
        beg = mid + 1
    else:
        end = mid -1
    if(beg == end):
        mid = (beg + end) / 2
        print "missing"
        print a[0]+ beg

Body:
Update #1: Yes, there was another one mistake. You're right. Here's updated version

Try this variant:

a = [1,2,3,4,5,7,8]

lent = len(a)
beg =0
end = lent-1

while beg < end:
    mid = (beg + end) / 2
    if (a[mid]-a[beg])==(mid - beg):
        beg = mid
    else:
        end = mid
    if abs(beg-end) <= 1:
        print "missing: %s" % (a[0] + max(beg, mid),)

Result:

missing: 6

Also, try use functions, so you could easily test and debug your code on different lists:

def find_missing(a):
    lent = len(a)
    beg =0
    end = lent-1

    while beg < end:
        mid = (beg + end) / 2
        if (a[mid]-a[beg])==(mid - beg):
            beg = mid
        else:
            end = mid
        if abs(beg-end) <= 1:
            return a[0] + max(beg, mid)

a = [1,2,3,4,5,7,8]
print find_missing(a)

a = [1,3,4,5,6]
print find_missing(a)

a = [1,2,3,4,5,7,8,9,10]
print find_missing(a)

Result:

6
2
6


问:
how to remove all class from child node using pure javascript?
[![enter image description here][1]][1]

it have ul li structure menu.

i want remove all menushow class from submenu_1.

i have multiple submenu_1 class.

demo example :

```<code><ul class="submenu_1 menushow">
<li class="sub">
    <ul class="submenu_2 menushow">
        <li>
            <ul class="submenu_2 menushow">
                <li>
                    <ul class="submenu_2 menushow">
                        <li></li>
                    </ul>
                </li>
            </ul>
        </li>
        <li></li>
    </ul>
</li></ul>
</code>```

答:
To remove all class .menushow from elements from ul.submenu_1.menushow you can use el.classList.remove('menushow'):

document
  .querySelectorAll('ul.submenu_1.menushow, ul.submenu_1 .menushow')
  .forEach(function(el) {
    el.classList.remove('menushow');
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="submenu_1 menushow">
  <li class="sub">
      <ul class="submenu_2 menushow">
          <li>
              <ul class="submenu_2 menushow">
                  <li>
                      <ul class="submenu_2 menushow">
                          <li></li>
                      </ul>
                  </li>
              </ul>
          </li>
          <li></li>
      </ul>
  </li>
</ul></code>```

Body:
To remove all class .menushow from elements from ul.submenu_1.menushow you can use el.classList.remove('menushow'):

document
  .querySelectorAll('ul.submenu_1.menushow, ul.submenu_1 .menushow')
  .forEach(function(el) {
    el.classList.remove('menushow');
  })

<ul class="submenu_1 menushow">
  <li class="sub">
      <ul class="submenu_2 menushow">
          <li>
              <ul class="submenu_2 menushow">
                  <li>
                      <ul class="submenu_2 menushow">
                          <li></li>
                      </ul>
                  </li>
              </ul>
          </li>
          <li></li>
      </ul>
  </li>
</ul>


问:
Get New File Name
I have a commit where a file is renamed. Is there any possibility to get the new file name from the old file name and the commit key?

Example: file.php is renamed to filex.php at commit 5119afae52e5ae08ca8e378e00895d824a179f03.

I'm searching for something that returns filex.php from the information about 5119afae52e5ae08ca8e378e00895d824a179f03 and file.php.

答:
The following bash script will do the job:

Usage:

```<code>new_name_of_renamed_file <oldname> <commitid>
</code>```

new_name_of_renamed_file:

```<code>#!/usr/bin/env bash

if [ $# -ne 2 ]
then
    echo "Usage: new_name_of_renamed_file <oldname> <commitid>"
    exit 1
fi

pattern="^rename from ${1/./\\.}\$"
git diff -M100% "$2"^.."$2"|grep -A1 "$pattern"|tail -n1|sed 's/^rename to //'
</code>```

Notes

The script detects only exact renames. If you are interested in renames where some modifications were made to the renamed file you can pass a corresponding similarity threshold to the git diff -M command.

If the file oldname doesn't exist in the parent of commitid or was not renamed in that commit, then nothing is output.

Title: Get New File Name

Body:
The following bash script will do the job:

Usage:

new_name_of_renamed_file <oldname> <commitid>

new_name_of_renamed_file:

#!/usr/bin/env bash

if [ $# -ne 2 ]
then
    echo "Usage: new_name_of_renamed_file <oldname> <commitid>"
    exit 1
fi

pattern="^rename from ${1/./\\.}\$"
git diff -M100% "$2"^.."$2"|grep -A1 "$pattern"|tail -n1|sed 's/^rename to //'

Notes

The script detects only exact renames. If you are interested in renames where some modifications were made to the renamed file you can pass a corresponding similarity threshold to the git diff -M command.

If the file oldname doesn't exist in the parent of commitid or was not renamed in that commit, then nothing is output.


问:
taking multiple inputs in a specific format as a single input in java
I have been using the scanner so far for taking inputs in java but what i need for this particular task is setting values for 4 variables with a single line input i.e.  07:05:45PM

The C equivalent solution for this particular solution is as follows:

```<code>scanf("%d:%d:%d%s", &hh, &mm, &ss, t12) ;
</code>```

I am looking for the java equivalent of this code.

答:
You could use a Scanner instance by setting to it a delimiter such as "\\s*:\\s*".

It could give this code :

```<code>Scanner s = new Scanner("07:05:45PM").useDelimiter("\\s*:\\s*");

int hours = s.nextInt();
int minutes = s.nextInt();
String secondAndMeridiem = s.next();
int seconds = Integer.valueOf(secondAndMeridiem.substring(0, 2));
String meridiem = secondAndMeridiem.substring(2, 4);
</code>```

Body:
I have been using the scanner so far for taking inputs in java but what i need for this particular task is setting values for 4 variables with a single line input i.e.  07:05:45PM

The C equivalent solution for this particular solution is as follows:

scanf("%d:%d:%d%s", &hh, &mm, &ss, t12) ;

I am looking for the java equivalent of this code.

Body:
You could use a Scanner instance by setting to it a delimiter such as "\\s*:\\s*".

It could give this code :

Scanner s = new Scanner("07:05:45PM").useDelimiter("\\s*:\\s*");

int hours = s.nextInt();
int minutes = s.nextInt();
String secondAndMeridiem = s.next();
int seconds = Integer.valueOf(secondAndMeridiem.substring(0, 2));
String meridiem = secondAndMeridiem.substring(2, 4);


问:
Laravel 5.4 one to many relationship
I have two tables in my model:
- Groups (id, name, category_id)
- Categories (id, name)

I would need to show in my view a list with every group name and its corresponding category. Could you please show me how to populate the Eloquent method and also what do I need in the view side?

This is what I have so far but of course is not working

-- GroupController

```<code>`       public function index()
{
    $groups = Category::find(1);

    return view('groups.groups',compact('groups'));
}
</code>```

-- Group

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

-- CategoryController

```<code>`       public function groups()
{
    return $this->hasMany('App\Group');
}`
</code>```

-- Category

```<code>`       public function groups()
{
    return $this->hasMany('App\Group');
}`
</code>```

-- view

@foreach($groups as $group)
{{$group->category}}
{{$group->category->name}}
@endforeach

thanks!!

答:
I finally got it.
In the GroupsController added this

```<code>´
    $groups = Group::with('category')->get();

    return view('groups.groups',compact('groups'));
</code>```

´
and in the view:
@foreach($groups as $group)  {{$group->category->name}}

thanks for your help

Title: Laravel 5.4 one to many relationship

Body:
I have two tables in my model:
- Groups (id, name, category_id)
- Categories (id, name)

I would need to show in my view a list with every group name and its corresponding category. Could you please show me how to populate the Eloquent method and also what do I need in the view side?

This is what I have so far but of course is not working

-- GroupController

`       public function index()
{
    $groups = Category::find(1);

    return view('groups.groups',compact('groups'));
}

-- Group

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

-- CategoryController

`       public function groups()
{
    return $this->hasMany('App\Group');
}`

-- Category

`       public function groups()
{
    return $this->hasMany('App\Group');
}`

-- view

@foreach($groups as $group)
{{$group->category}}
{{$group->category->name}}
@endforeach

thanks!!

Body:
I finally got it.
In the GroupsController added this

´
    $groups = Group::with('category')->get();

    return view('groups.groups',compact('groups'));

´
and in the view:
@foreach($groups as $group)  {{$group->category->name}}

thanks for your help


问:
using awk to match a PATH starting with /root/ and ending before character "
i have a command that produces a random output with a path in it
And i need to extract this path using awk.
The path always starts with the same pattern (lets assume it always starts with /root) but the rest can change

for example :

```<code>error reason  05/30/2017 12:18:37 [74575:45687]: "/root/this/is/my/path/" random text random text random text random text random text random    text
</code>```

to extract /root/this/is/my/path/ : I have tryed using grep + awk in the following way :

```<code>command.sh | grep error  |awk '/root/{mypath=$6}'.
</code>```

But i then figured out my path was not always located at the same place. more over, i don't want to extract the double quotes.

```<code>i need to have /root/this/is/my/path/ not "/root/this/is/my/path/"
</code>```

Anyone can help please?

答:
A simple method you may adopt:

```<code>command.sh | awk -F\" '/^error/{ print $2}'
</code>```

Output:

```<code>/root/this/is/my/path/
</code>```

Body:
i have a command that produces a random output with a path in it
And i need to extract this path using awk.
The path always starts with the same pattern (lets assume it always starts with /root) but the rest can change

for example :

error reason  05/30/2017 12:18:37 [74575:45687]: "/root/this/is/my/path/" random text random text random text random text random text random    text

to extract /root/this/is/my/path/ : I have tryed using grep + awk in the following way :

command.sh | grep error  |awk '/root/{mypath=$6}'.

But i then figured out my path was not always located at the same place. more over, i don't want to extract the double quotes.

i need to have /root/this/is/my/path/ not "/root/this/is/my/path/"

Anyone can help please?

Body:
A simple method you may adopt:

command.sh | awk -F\" '/^error/{ print $2}'

Output:

/root/this/is/my/path/


问:
What might be the consequences of adding a file to the bin directory of a c# web application?
I work with a live asp.net web application. I would like to copy a .dll file into its bin folder on the server where it is deployed (not add it to the application solution in VS). This .dll file would not be used/referenced by any part of the live asp.net application (i.e. the namespace of the class library that this .dll contains is not used by any part of the existing application, nor would it be invoked by reflection).

It is a requirement that this .dll be located in the bin directory with all the other .dlls that the asp.net application requires.

It can be garenteed that the .dll does not share the same name as an existing .dll in the bin directory nor will it ever so there should be no risk of overwriting an existing file.

My understanding is that copying this .dll (or any other file type for that matter) into the bin folder would do nothing and come with no consequences, it would just sit there causing no harm and not interfering in any way with the existing application. Is this an entirely safe thing to do (assuming no naming conflicts) or are there any risks that I may have overlooked that could in any way harm the existing application or affect its working temporarily or otherwise?

答:
The answer here should be split into what's possible and what's likely.

Likely

Your application will, during its runtime, try to find the DLLs it expects to find. This means that the application is only concerned with the DLL files it knows about.

You can add as many other files to that folder as you want. Barring any name conflicts (which you already guarantee to not occur), the additional files do not matter to the application as it will never try to look up any of these files.

Possible

The above is simply default behavior. It is possible that the application actually looks inside the bin folder and iterates over its files (maybe only DLL files, maybe all files).

An example for why this would ever be done:

When you develop a mod for a game (depending on the game), you create a library. In some cases, your mod will include a DLL file (most often when it changes core game logic). Your mod is then installed in a specific directory. The base game will always look for any existing file in that directory (the mod you added), and try to incorporate it into its runtime.

It's not impossible that your application does something similar, e.g. looks for custom extensions at runtime and incorporates them using reflection.

However, it would be a bad (but again, not impossible) practice to expect these extensions to be put into the bin folder, as opposed to a custom folder.

So my answer is a combination of replies; ordered by desirability

I would advise against using the bin folder for unrelated DLL files. I can't think of a good reason why it should ever be done. This smells of a blind company rule that foregoes any common sense or good practice.

Since you seemingly cannot avoid putting the DLL in there, can you at least put it in a subfolder to segregate the DLL from the application DLLs? It's a matter of keeping things neatly ordered.

For most applications, adding the DLL directly to the bin folder shouldn't matter on a technical level. It's a messy solution, but not inherently a problem by itself.

If the application looks into its own bin folder at runtime, you can run into problems by adding the DLL and should clearly avoid it. However, I would expect such an application to document this feature. If it is never mentioned that the application does this, it seems fair to assume that it doesn't happen. Of course, that very much depends on your company's documentation quality and common coding practices.

TL;DR

It's a horrible solution. Depending on the application, it might create conflicts. It won't conflict for most standard applications that do not use reflection. It's still a horrible solution.


问:
Setup CI for Angular library with Gitlab
I have an Angular library using the angular-librarian. Now whenever I change something, I need to rebuild the project and push the content (including the dist-folder) to our repository.

I would like to setup a CI for this to run automated. We have several CIs running, but for this the output of the build-process needs to be pushed back into the repository, which would lead to an infinite loop of builds and also another unnecessary push to the repository.

Is there any way to handle this with gitlabs-ci or is building it and pushing the build from my local machine the best option?

答:
You can use [skip ci] or [ci skip] in your commit message to prevent the loop you mention.

Have a look at the Gitlab CI docs.

ContentLicense: CC BY-SA 4.0


问:
Arduino stops responding after writing to I2C
I'm currently experimenting with writing to EEPROMs over I2C. Reading goes fine and I get excellent throughput. However when I try to write to the device, the Arduino stops responding, and I have to reset it in order to get it to work again.

The I2C write also doesn't show up in my I2C debugger.

```<code>void i2cWrite(unsigned char device, unsigned char memory, const char *wrBuf, unsigned short len) {
  int i = 0;
  ushort bytesWritten = 0;
  ushort _memstart = memory;
  ushort blockSize = 4;
  #ifdef DEBUG_MSGS
  char serialBuf[255] = { '\0'};
  Serial.print("Writing To i2c: ");
  sprintf(serialBuf, "%p", wrBuf);
  Serial.println(serialBuf);
  #endif //DEBUG_MSGS
  while (bytesWritten < len) {
    Wire.beginTransmission((int)device);
    Wire.write((unsigned char)_memstart);
    for (int j = 0; i < blockSize; j++) {
      Wire.write(wrBuf[bytesWritten + j]);
    }
    Wire.endTransmission();
    bytesWritten += blockSize;
    _memstart += blockSize;
    delay(25);
  }
  #ifdef DEBUG_MSGS
  Serial.println("\mDone writing.");
  #endif //DEBUG_MSGS
}
</code>```

I'm quite unsure as to what I'm doing wrong. I'm getting the following output over the serial connection:

Write Request Received: Andy

Writing To i2c: 0xa800fd98

"Writing to i2c" always gives the same value, and it always seems to crash straight after.

答:
the error seemed to be located in the loop as the output is

```<code>Write Request Received: Andy
Writing To i2c: 0xa800fd98

I'm working here
I wrote the memory adress
I wrote a byte of data
I wrote a byte of data
I wrote a byte of data
I wrote a byte of data
I wrote a byte of data
....
</code>```

this seems to go on ad infinitum.

After adding a few more debug statements and changing the points Some programmer dude noticed

```<code>{
    Wire.beginTransmission((int)device);
    Serial.println("I'm working here");
    Wire.write((unsigned char)_memstart);
    Serial.println("I wrote the memory adress");
    for (int j = 0; j < blockSize; j++) {
        Wire.write(wrBuf[bytesWritten + j]);
        Serial.println("I wrote a byte of data");
        //Serial.write(wrBuf[bytesWritten + j]);
    }
    Wire.endTransmission();
    Serial.println("I ended the transmission");
    bytesWritten += blockSize;
    _memstart += blockSize;
    delay(25);
}
</code>```

i noticed that i was checking for I < blocksize (copied from the reading part,) now i'm running into some other (small) issues but this solved the problem i was having.

Body:
I'm currently experimenting with writing to EEPROMs over I2C. Reading goes fine and I get excellent throughput. However when I try to write to the device, the Arduino stops responding, and I have to reset it in order to get it to work again.

The I2C write also doesn't show up in my I2C debugger.

void i2cWrite(unsigned char device, unsigned char memory, const char *wrBuf, unsigned short len) {
  int i = 0;
  ushort bytesWritten = 0;
  ushort _memstart = memory;
  ushort blockSize = 4;
  #ifdef DEBUG_MSGS
  char serialBuf[255] = { '\0'};
  Serial.print("Writing To i2c: ");
  sprintf(serialBuf, "%p", wrBuf);
  Serial.println(serialBuf);
  #endif //DEBUG_MSGS
  while (bytesWritten < len) {
    Wire.beginTransmission((int)device);
    Wire.write((unsigned char)_memstart);
    for (int j = 0; i < blockSize; j++) {
      Wire.write(wrBuf[bytesWritten + j]);
    }
    Wire.endTransmission();
    bytesWritten += blockSize;
    _memstart += blockSize;
    delay(25);
  }
  #ifdef DEBUG_MSGS
  Serial.println("\mDone writing.");
  #endif //DEBUG_MSGS
}

I'm quite unsure as to what I'm doing wrong. I'm getting the following output over the serial connection:

Write Request Received: Andy

Writing To i2c: 0xa800fd98

"Writing to i2c" always gives the same value, and it always seems to crash straight after.

Body:
the error seemed to be located in the loop as the output is

Write Request Received: Andy
Writing To i2c: 0xa800fd98

I'm working here
I wrote the memory adress
I wrote a byte of data
I wrote a byte of data
I wrote a byte of data
I wrote a byte of data
I wrote a byte of data
....

this seems to go on ad infinitum.

After adding a few more debug statements and changing the points Some programmer dude noticed

{
    Wire.beginTransmission((int)device);
    Serial.println("I'm working here");
    Wire.write((unsigned char)_memstart);
    Serial.println("I wrote the memory adress");
    for (int j = 0; j < blockSize; j++) {
        Wire.write(wrBuf[bytesWritten + j]);
        Serial.println("I wrote a byte of data");
        //Serial.write(wrBuf[bytesWritten + j]);
    }
    Wire.endTransmission();
    Serial.println("I ended the transmission");
    bytesWritten += blockSize;
    _memstart += blockSize;
    delay(25);
}

i noticed that i was checking for I < blocksize (copied from the reading part,) now i'm running into some other (small) issues but this solved the problem i was having.


问:
Best way to communicate between forms?
I almost never used (advanced, or at all) graphical interfaces, or one simple form with simple controls... but this time I've got something a little more complex, and I don't have much experience with GUI.
I have one main form (and possibly more in the future) from which other sub-forms open (and they might have sub-forms of themselves) and I wonder what is, in your opinion, the best way to communicate between them?

I thought of passing the main form as a parameter to the constructors of the sub-forms, but it doesn't seem like a good way, especially if I'm going to need to communicate between other, distinct, sub-forms, not to mention I have to double check the input, or make a few methods, but it seems more like functional programming than object oriented programming...

Perhaps I can:

Create a static class (or Properties.Settings) for global settings. Cons: every change of data is needed to be copied to the class, I'm looking for something a bit more comfortable and elegant.

Use the ugly way of accessing the controls from Application.OpenForms - fixes the problem of passing the main form as parameter. Cons: not very stable.

Do something else I haven't thought of. Suggestions? Cons: don't know what it is yet.

答:
You can use the built in Tag property of the form which is an "object" class.

public Form1()
{
   (ComplicatedDataStructure)Tag = new ComplicatedDataStracture();
}
.
.
form1 = new Form1();
.
.
form2 = new Form2();
.
.
form2.Tag = form1.Tag;

so form2.Tag is equals to "ComplicatedDataStracture" object;

Title: Best way to communicate between forms?

ContentLicense: CC BY-SA 2.5


问:
Android: Scenario where onPause is called but not onStop?
I'm trying to understand the difference between onPause and onStop.

I've read all the different forums but I still am not clear about the difference. I've created a simple app to try and test when which method gets called. For that I've simply placed loggers in each method.

From my trials -

Popups do not call either method

Switching to another activity calls both methods

Pulling down the notification bar calls neither method

I've only seen either both methods being called in quick succession or neither getting called at all.
I'm trying to find scenarios where onPause gets called but onStop doesn't.

The purpose is to understand whether defining onPause is even required. If the scenarios in which only onPause gets called are so rare, it doesn't even make sense to write separate code for onPause. Shouldn't writing onStop be sufficient?

```<code>public class LifecycleActivity extends ActionBarActivity {

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Rachit", "In Destroy Method");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle);
        Log.d("Rachit", "In Create Method");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Rachit", "In Start Method");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Rachit", "In Resume Method");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Rachit", "In Pause Method");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Rachit", "In Restart Method");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Rachit", "In Stop Method");
    }
}
</code>```

答:
When we start dialog activity from current Activity at that time only onPause() will be called.
Ex: Let's say we have activity A and B. Now Activity B is dialog activity and activity A is normal Activity. when we start activity B from activity A, then activity A's onPause() will be called and activity B'sonCreate(),onStart() and onResume() will be called.Please check below url for sample code
sample code

Body:
I'm trying to understand the difference between onPause and onStop.

I've read all the different forums but I still am not clear about the difference. I've created a simple app to try and test when which method gets called. For that I've simply placed loggers in each method.

From my trials -

Popups do not call either method

Switching to another activity calls both methods

Pulling down the notification bar calls neither method

I've only seen either both methods being called in quick succession or neither getting called at all.
I'm trying to find scenarios where onPause gets called but onStop doesn't.

The purpose is to understand whether defining onPause is even required. If the scenarios in which only onPause gets called are so rare, it doesn't even make sense to write separate code for onPause. Shouldn't writing onStop be sufficient?

public class LifecycleActivity extends ActionBarActivity {

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Rachit", "In Destroy Method");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle);
        Log.d("Rachit", "In Create Method");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Rachit", "In Start Method");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Rachit", "In Resume Method");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Rachit", "In Pause Method");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Rachit", "In Restart Method");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Rachit", "In Stop Method");
    }
}


问:
Array formula on Excel for Mac
I need to call LINEST in Excel 2011 for Mac, I would say - this was a detective story. My laziness, my curiosity, all was here!
I had a homework from university course to use LINEST.

I even stopped trying to do so on MAC, because after googling I could not find any solution how to do it. (I have tried EACH AND EVERY combination of Fn Ctrl Alt Cmd Return!)

Finally, I found a solution here on stack overflow!  I want to mention it again, as it was a long time I spent looking for the solution. I have spent 4 days outside of home, to use just windows PC where it is easy as a pie - F2, CTRL+SHIFT+ENTER.

If you want to check if I tell truth - go to HELP in Excel for Mac, type array formula, find LINEST and look at the solution combination!

The solution: select the range, press CONTROL+U and then press ⌘+RETURN.

Here is the link to the original post:
Excel formulas giving #VALUE! error when ported to Mac

答:
Select the desired range of cells

Press Fn + F2 or CONTROL + U

Paste in your array value

Press COMMAND (⌘) + SHIFT + RETURN

Title: Array formula on Excel for Mac


问:
Managing PHP Errors
I have been searching all over the net to try and find a way to catch all errors thrown by PHP (5.3)

I have been reading through the documentation and it looks like set_error_handler is what I need but it doesn't get fatal/parse errors. I'm not sure if this is possible...

Here is my source: https://github.com/tarnfeld/PHP-Error-Handler
Feel free to fork/commit if you know better solutions to all of this.

Thanks in advanced!

Updated!

Using the answers below I finished writing an error handler, it takes care of E_ERROR|E_PARSE|E_WARNING|E_NOTICE and will kill the script when it is fatal! :-)

答: You may keep an eye on error_log. In Ubuntu this is located in /var/log/apache2/error_log

Title: Managing PHP Errors


问:
Swift upload file to PHP server
So I'm uploading a file from swift to a PHP server, the POST request arrives as expected with headers and all but I'm unable to get anything out of $_FILES. It's just an empty array.

I'm clearly doing something wrong on the Swift side, this is my code:

```<code>func testUpload(){
    let bundle = NSBundle.mainBundle()
    let path = bundle.pathForResource("someTestFile", ofType: "zip")!
    var data: NSData = NSData(contentsOfFile: path)!

    var request = NSMutableURLRequest(URL: NSURL(string: "http://testsite.com/upload")!)
    request.HTTPMethod = "POST"

    let boundary = "----------ds2Gry67efddagdfsfhsHF"
    let contentType = "multipart/form-data; boundary=\(boundary)"
    request.setValue(contentType, forHTTPHeaderField:"Content-Type")
    request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
    self.uploadFiles(request, data: data)
}

func uploadFiles(request: NSURLRequest, data: NSData) {
    var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
    var task = session.uploadTaskWithRequest(request, fromData: data)
    task.resume()
}
</code>```

I'm pretty sure I'm missing something, I just can't figure out what it is...

答: POST method ,you need add header application/x-www-form-urlencoded</p>

Title: Swift upload file to PHP server

Body:
So I'm uploading a file from swift to a PHP server, the POST request arrives as expected with headers and all but I'm unable to get anything out of $_FILES. It's just an empty array.

I'm clearly doing something wrong on the Swift side, this is my code:

func testUpload(){
    let bundle = NSBundle.mainBundle()
    let path = bundle.pathForResource("someTestFile", ofType: "zip")!
    var data: NSData = NSData(contentsOfFile: path)!

    var request = NSMutableURLRequest(URL: NSURL(string: "http://testsite.com/upload")!)
    request.HTTPMethod = "POST"

    let boundary = "----------ds2Gry67efddagdfsfhsHF"
    let contentType = "multipart/form-data; boundary=\(boundary)"
    request.setValue(contentType, forHTTPHeaderField:"Content-Type")
    request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
    self.uploadFiles(request, data: data)
}

func uploadFiles(request: NSURLRequest, data: NSData) {
    var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
    var task = session.uploadTaskWithRequest(request, fromData: data)
    task.resume()
}

I'm pretty sure I'm missing something, I just can't figure out what it is...


答:
Following up on my comments, what you want is the following:

Models + relations:

Group model

```<code>public function category()
{
    return $this->belongsTo(Category::class);
}
</code>```

Category model

```<code>public function groups()
{
    return $this->hasMany(Group::class);
}
</code>```

Then in your Group controller:

```<code>public function index()
{
    // consider using paginate() instead of get()
    // using with('category') to eagerload the category (1 extra query) instead of querying for the category in the views foreach loop.
    $groups = Group::with('category')->get();

    return view('groups.groups',compact('groups'));
}
</code>```

And in your view you can now list the groups and their category:

```<code>@foreach ($groups as $group)
    {{-- Assuming group and category have a name and category is always set --}}
    {{ $group->name }} : {{ $group->category->name }}
@endforeach
</code>```

Title: Laravel 5.4 one to many relationship

Body:
Following up on my comments, what you want is the following:

Models + relations:

Group model

public function category()
{
    return $this->belongsTo(Category::class);
}

Category model

public function groups()
{
    return $this->hasMany(Group::class);
}

Then in your Group controller:

public function index()
{
    // consider using paginate() instead of get()
    // using with('category') to eagerload the category (1 extra query) instead of querying for the category in the views foreach loop.
    $groups = Group::with('category')->get();

    return view('groups.groups',compact('groups'));
}

And in your view you can now list the groups and their category:

@foreach ($groups as $group)
    {{-- Assuming group and category have a name and category is always set --}}
    {{ $group->name }} : {{ $group->category->name }}
@endforeach


问:
Laravel DomPdf Add Custom Font
I am trying to use OLD English font in Dompdf with Laravel.,
I have inserted the font in laravel view. But it seems when generating the pdf It is not working.I tried editing dompdf >vendor >.../dompdf_font_family_cache.dist.php File.But no luck,

Can anyone Suggest a Solution?

Thanks In Advance.

答:
I was trying to include custom fonts too.
I included the font in the view (using @font-face declaration), but when I tried to generate the pdf, it gave me an ErrorException in AdobeFontMetrics.php.
I resolved by creating a fonts folder in the storage folder of your laravel project.
So now I have:

```<code>> storage
    > app
    > fonts
    > framework
    > logs
</code>```

I hope it will help

Title: Laravel DomPdf Add Custom Font

Body:
I was trying to include custom fonts too.
I included the font in the view (using @font-face declaration), but when I tried to generate the pdf, it gave me an ErrorException in AdobeFontMetrics.php.
I resolved by creating a fonts folder in the storage folder of your laravel project.
So now I have:

> storage
    > app
    > fonts
    > framework
    > logs

I hope it will help


问:
FPGA efficient (a)synchronous resets
I remember reading a while ago that either asynchronous or synchronous resets are more efficiently implemented in FPGAs since the flip flops already have one, but the other would require additional logic.

Does anyone know which way round this is? Is this the same for Xilinx, Altera, Other..

When learning, I used to add an asynchronous clear and a synchronous reset to every FSM, just in case. Is there any benefit at all to this?

Thanks for any feedback!

答:
To directly answer the question - most FPGAs can do either sync or async resets in their flipflops these days.  In terms of adding an async clear and sync rest, I'm not sure what you acheieved by this - add the signals which are required for the function of your design (possibly including no reset at all for some flops...)

Some further advice... If you use an asynchronous reset, be very careful when you deassert it.  If there's much skew on this "slow" net across your device, you may find some flops coming our of reset on a different clock cycle to others.  Chaos ensues!

To avoid this, I favour creating a toplevel block which takes in your external (and presumably very asynchronous) reset signal, synchronises it to the clock and feeds it as a synchronous reset to all the flops you want resetting (in that clock domain - you may need more than one).  Then the timing analyser will tell you if the skew is too much the device, and you'll ensure everything comes out of reset at once.

Xilinx have a whitepaper on this subject, but it applies equally to other FPGAs also.

For some applications you may need an asynchronously asserted reset on the IOs to ensure that certain external devices work the way you need - but still deassert it synchronously.

(PS. as you mention FPGAs, if you're not aware, there's a stackexchange proposal related to programmable logic which you may find of interest http://area51.stackexchange.com/proposals/20632/)

Title: FPGA efficient (a)synchronous resets


问:
how to push sub array object into an a array in javascript
hi all i am using javascript i am trying to push object values into one array here i attached my code

```<code>var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }
</code>```

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this

答:
There are a lot of correct answers already present however you can use ES6 Arrow function to achieve this with minimum syntax.

```<code>var MainInfo = data.map( x=>{ return {
        "BuildingID" : x.BuildingID,
        "FloorId" : x.FloorId,
        "one" : x.volume[0]["one"],
        "two" : x.volume[0]["two"],
        "three" : x.volume[0]["three"],
    }})
</code>```

More about arrow functions here

Body:
hi all i am using javascript i am trying to push object values into one array here i attached my code

var data = [{
            BuildingID: "56", FloorId: "65", volume: [{

                one: 12,
                two: 15,
                three: 12
            }]
        }]

var MainInfo=[];
            for (i = 0; i < data.length; i++) {

                var obj = {}
                obj.BuildingID = data[i].BuildingID;
                obj.FloorId = data[i].FloorId;
                obj.volume = data[i].volume[0];
                MainInfo.push(obj);

            }

it's working but not fully applicable here i mentioned the excepted output what should i need

Current output

Expected output

Note:in data volume is dynamic help how to do this

Body:
There are a lot of correct answers already present however you can use ES6 Arrow function to achieve this with minimum syntax.

var MainInfo = data.map( x=>{ return {
        "BuildingID" : x.BuildingID,
        "FloorId" : x.FloorId,
        "one" : x.volume[0]["one"],
        "two" : x.volume[0]["two"],
        "three" : x.volume[0]["three"],
    }})

More about arrow functions here