问:
How to return class reference with generic in typescript
I'm writing a type factory to spit out different type base on the string identifier, for example:

```<code>export class InputComponent<T> {
    constructor(public value: T) {
    }
}

export const getComponentClass = (identifier: string) => {
    switch (identifier) {
        case 'textarea':
            return Textarea;
        case 'input:number':
            // here to return InputComponent<number>
        case 'input:binary':
            return Radio;
        case 'input:string':
        default:
            // here I want to return something like InputComponent<string>
    }
}
</code>```

Then I'll use it like (very simple example to illustrate how I would like things to happen, in the real project we use ComponentFactoryResolver to create dynamic component)

```<code>const classdef = getComponentClass('input:text');
const input = new classdef('hello, world');
</code>```

Is there a way to actually do that? Or do I have to go the subclass way to have a designated class for each type?

Thanks.

答:
Why even have the getComponentClass function when you can just make a new instance of the class with the proper type.</p>

```<code>const input = new InputComponent<string>("hello world");
</code>```

Body:
I'm writing a type factory to spit out different type base on the string identifier, for example:

export class InputComponent<T> {
    constructor(public value: T) {
    }
}

export const getComponentClass = (identifier: string) => {
    switch (identifier) {
        case 'textarea':
            return Textarea;
        case 'input:number':
            // here to return InputComponent<number>
        case 'input:binary':
            return Radio;
        case 'input:string':
        default:
            // here I want to return something like InputComponent<string>
    }
}

Then I'll use it like (very simple example to illustrate how I would like things to happen, in the real project we use ComponentFactoryResolver to create dynamic component)

const classdef = getComponentClass('input:text');
const input = new classdef('hello, world');

Is there a way to actually do that? Or do I have to go the subclass way to have a designated class for each type?

Thanks.

Body:
Why even have the getComponentClass function when you can just make a new instance of the class with the proper type.

const input = new InputComponent<string>("hello world");


来源: stackexchange

问:
What is cooks-kim algorithm
I was reading about sorting of presorted list in which few numbers are unsorted, someone said that cooks-kim algorithm is best for such cases, I googled about it but no relevant links.

Please let me know if anyone knows about it

Thank you

答:
Kurtis R Cook, Do Jin Kim, the paper you want is called "Best sorting algorithm for nearly sorted list", can be found in Communications of the ACM,
23:620–624, 1980.

Can't find anywhere to download it from, the publisher keeps vigilant, $15 from ACM themselves.

To answer your question, it's a combination of an insertion sort and a quick sort, optimised for reordering mostly ordered data.  ie. bringing a previously sorted list back in to a sorted form after some alterations.

ContentLicense: CC BY-SA 2.5

Title: What is cooks-kim algorithm


问:
Close opened infowindows - google maps api
I'm trying that when the user clicks on a marker, it opens and close all the previous opened markers. I'm trying with this code with no luck, any idea how to do it?

updated with the full script I'm using and based on the possible solutions on the answers:

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

    /*
    *  new_map
    *
    *  This function will render a Google Map onto the selected jQuery element
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 4.3.0
    *
    *  @param $el (jQuery element)
    *  @return  n/a
    */

    function new_map( $el ) {

      // var
      var $markers = $el.find('.marker');

      // vars
      var args = {
        scrollwheel: false,
        zoom    : 5,
        center    : new google.maps.LatLng(0, 0),
        mapTypeId : google.maps.MapTypeId.ROADMAP
      };

      // create map
      var map = new google.maps.Map( $el[0], args);

      // add a markers reference
      map.markers = [];

      // add markers
      $markers.each(function(){

          add_marker( $(this), map );

      });

      // center map
      center_map( map );

      // return
      return map;

    }

    /*
    *  add_marker
    *
    *  This function will add a marker to the selected Google Map
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 4.3.0
    *
    *  @param $marker (jQuery element)
    *  @param map (Google Map object)
    *  @return  n/a
    */

    function add_marker( $marker, map ) {

      // var
      var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );

      // create marker
      var marker = new google.maps.Marker({
        position  : latlng,
        map     : map,
        icon: '<?php echo get_template_directory_uri(); ?>/assets/img/google-map-marker.png',
      });

      // add to array
      map.markers.push( marker );

      if( $marker.html() ){
         var infoWindows = [];
        // show info window when marker is clicked
        google.maps.event.addListener(marker, 'click', function() {

           // Need to clear up old info windows before adding new ones
          for (var i = 0; i < infoWindows.length; i++) {
            infoWindows[i].setMap(null);
          }

        // create info window
          var infoWindow = new google.maps.InfoWindow({
            content   : $marker.html()
          });

          infoWindow.open( map, marker );
          infoWindows.push(infoWindow);
        });
      }

    }

    /*
    *  center_map
    *
    *  This function will center the map, showing all markers attached to this map
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 4.3.0
    *
    *  @param map (Google Map object)
    *  @return  n/a
    */

    function center_map( map ) {

      // vars
      var bounds = new google.maps.LatLngBounds();

      // loop through all markers and create bounds
      $.each( map.markers, function( i, marker ){

        var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );

        bounds.extend( latlng );

      });

      // only 1 marker?
      if( map.markers.length == 1 )
      {
        // set center of map
          map.setCenter( bounds.getCenter() );
          map.setZoom( 16 );
      }
      else
      {
        // fit to bounds
        map.fitBounds( bounds );
      }

    }

    /*
    *  document ready
    *
    *  This function will render each map when the document is ready (page has loaded)
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 5.0.0
    *
    *  @param n/a
    *  @return  n/a
    */
    // global var
    var map = null;

    $(document).ready(function(){

      $('.acf-map').each(function(){

        // create map
        map = new_map( $(this) );

      });

    });

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

答:
I changed a little in your code.

```<code>var infoWindows = [];
if( $marker.html() ){

    // Need to clear up old info windows before adding new ones
    for (var i = 0; i < infoWindows.length; i++) {
      infoWindows[i].setMap(null);
    }
  // show info window when marker is clicked
  google.maps.event.addListener(marker, 'click', function() {

  // create info window
    var infoWindow = new google.maps.InfoWindow({
      content   : $marker.html()
    });

    infoWindow.open( map, marker );
    infoWindows.push(infoWindow);
  });
}
</code>```

I hope it will work. If not, let me know more detail about your code.
Thanks

ContentLicense: CC BY-SA 3.0

Body:
I'm trying that when the user clicks on a marker, it opens and close all the previous opened markers. I'm trying with this code with no luck, any idea how to do it?

updated with the full script I'm using and based on the possible solutions on the answers:

    (function($) {

    /*
    *  new_map
    *
    *  This function will render a Google Map onto the selected jQuery element
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 4.3.0
    *
    *  @param $el (jQuery element)
    *  @return  n/a
    */

    function new_map( $el ) {

      // var
      var $markers = $el.find('.marker');

      // vars
      var args = {
        scrollwheel: false,
        zoom    : 5,
        center    : new google.maps.LatLng(0, 0),
        mapTypeId : google.maps.MapTypeId.ROADMAP
      };

      // create map
      var map = new google.maps.Map( $el[0], args);

      // add a markers reference
      map.markers = [];

      // add markers
      $markers.each(function(){

          add_marker( $(this), map );

      });

      // center map
      center_map( map );

      // return
      return map;

    }

    /*
    *  add_marker
    *
    *  This function will add a marker to the selected Google Map
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 4.3.0
    *
    *  @param $marker (jQuery element)
    *  @param map (Google Map object)
    *  @return  n/a
    */

    function add_marker( $marker, map ) {

      // var
      var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );

      // create marker
      var marker = new google.maps.Marker({
        position  : latlng,
        map     : map,
        icon: '<?php echo get_template_directory_uri(); ?>/assets/img/google-map-marker.png',
      });

      // add to array
      map.markers.push( marker );

      if( $marker.html() ){
         var infoWindows = [];
        // show info window when marker is clicked
        google.maps.event.addListener(marker, 'click', function() {

           // Need to clear up old info windows before adding new ones
          for (var i = 0; i < infoWindows.length; i++) {
            infoWindows[i].setMap(null);
          }

        // create info window
          var infoWindow = new google.maps.InfoWindow({
            content   : $marker.html()
          });

          infoWindow.open( map, marker );
          infoWindows.push(infoWindow);
        });
      }

    }

    /*
    *  center_map
    *
    *  This function will center the map, showing all markers attached to this map
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 4.3.0
    *
    *  @param map (Google Map object)
    *  @return  n/a
    */

    function center_map( map ) {

      // vars
      var bounds = new google.maps.LatLngBounds();

      // loop through all markers and create bounds
      $.each( map.markers, function( i, marker ){

        var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );

        bounds.extend( latlng );

      });

      // only 1 marker?
      if( map.markers.length == 1 )
      {
        // set center of map
          map.setCenter( bounds.getCenter() );
          map.setZoom( 16 );
      }
      else
      {
        // fit to bounds
        map.fitBounds( bounds );
      }

    }

    /*
    *  document ready
    *
    *  This function will render each map when the document is ready (page has loaded)
    *
    *  @type  function
    *  @date  8/11/2013
    *  @since 5.0.0
    *
    *  @param n/a
    *  @return  n/a
    */
    // global var
    var map = null;

    $(document).ready(function(){

      $('.acf-map').each(function(){

        // create map
        map = new_map( $(this) );

      });

    });

    })(jQuery);

Body:
I changed a little in your code.

var infoWindows = [];
if( $marker.html() ){

    // Need to clear up old info windows before adding new ones
    for (var i = 0; i < infoWindows.length; i++) {
      infoWindows[i].setMap(null);
    }
  // show info window when marker is clicked
  google.maps.event.addListener(marker, 'click', function() {

  // create info window
    var infoWindow = new google.maps.InfoWindow({
      content   : $marker.html()
    });

    infoWindow.open( map, marker );
    infoWindows.push(infoWindow);
  });
}

I hope it will work. If not, let me know more detail about your code.
Thanks


问:
Parsing Robots.txt in python
I want to parse robots.txt file in python.
I have explored robotParser and robotExclusionParser but nothing really satisfy my criteria. I want to fetch all the diallowedUrls and allowedUrls in a single shot rather then manually checking for each url if it is allowed or not. Is there any library to do this?</p>

答:
You can use curl command to read the robots.txt file into a single string split it with new line check for allow and disallow urls.

```<code>import os
result = os.popen("curl https://fortune.com/robots.txt").read()
result_data_set = {"Disallowed":[], "Allowed":[]}

for line in result.split("\n"):
    if line.startswith('Allow'):    # this is for allowed url
        result_data_set["Allowed"].append(line.split(': ')[1].split(' ')[0])    # to neglect the comments or other junk info
    elif line.startswith('Disallow'):    # this is for disallowed url
        result_data_set["Disallowed"].append(line.split(': ')[1].split(' ')[0])    # to neglect the comments or other junk info

print (result_data_set)
</code>```

Title: Parsing Robots.txt in python

Body:
You can use curl command to read the robots.txt file into a single string split it with new line check for allow and disallow urls.

import os
result = os.popen("curl https://fortune.com/robots.txt").read()
result_data_set = {"Disallowed":[], "Allowed":[]}

for line in result.split("\n"):
    if line.startswith('Allow'):    # this is for allowed url
        result_data_set["Allowed"].append(line.split(': ')[1].split(' ')[0])    # to neglect the comments or other junk info
    elif line.startswith('Disallow'):    # this is for disallowed url
        result_data_set["Disallowed"].append(line.split(': ')[1].split(' ')[0])    # to neglect the comments or other junk info

print (result_data_set)


问:
AWS Lambda - Inject Spring Bean in Spring Boot Handler
I have uploaded a simple Spring Boot project to Amazon Lambda and I am currently trying to test it.
It works 100% but I get a null pointer when I try to inject a Spring Bean
Here is my code for the LambdaHandler

```<code>package com.test.services.lambda;

import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.test.services.MyServices;

public class MyLambdaFunctionHandler implements RequestHandler<String, String> {

    public MyLambdaFunctionHandler() {
    }

    @Autowired
    private ApplicationContext springContext;
    private MyServices myServices;

    public String handleRequest(String input, Context lambdaContext) {
        this.myServices = springContext.getBean(MyServices.class);
        lambdaContext.getLogger().log("AWS Request ID: " + lambdaContext.getAwsRequestId());
        lambdaContext.getLogger().log("Input: " + input + " at " + Calendar.getInstance().getTimeInMillis());
        myServices.sendGoodMessage("Message sent from Lambda");
        return "Hello World";
    }
}
</code>```

I set the handler in Amazon  Lambda to be the following

```<code>com.test.services.lambda.MyLambdaFunctionHandler::handleRequest
</code>```

However when I test this function - I get this error message

```<code>{
  "errorMessage": "java.lang.NullPointerException",
  "errorType": "java.lang.NullPointerException",
  "stackTrace": [
    "com.test.services.lambda.MyLambdaFunctionHandler.handleRequest(SlackLambdaFunctionHandler.java:23)",
    "com.test.services.lambda.MyLambdaFunctionHandler.handleRequest(SlackLambdaFunctionHandler.java:12)"
  ]
}
</code>```

It is failing where I inject the Spring Bean
Can anyone offer any advice on how I can go about injecting a spring bean into my AWS Lambda Handler?

Any assistance with this would be greatly appreciated

Thanks
Damien

答:
There are a few ways to inject ApplicationContext.

Yours should work as long as spring manage your beans. Did you declare MyLambdaFunctionHandler in some @Configuration file as a @Bean?

Did you use new MyLambdaFunctionHandler() somewhere to initialize it outside spring @Configuration? (this means spring is not managing your bean).

If spring does not manage your bean it cannot inject beans into it.

If not, it should be annotated with @Component and scanned by some @ComponentScan.

If it is declared, you should use spring ApplicationContextAware to set your ApplicationContext. Spring got a lot of those utility interfaces to inject some of its core classes to your beans.

example:

```<code>public class MyLambdaFunctionHandler implements RequestHandler<String, String>, ApplicationContextAware {

    public MyLambdaFunctionHandler() {
    }

    private ApplicationContext springContext;
    private MyServices myServices;

    public String handleRequest(String input, Context lambdaContext) {
        this.myServices = springContext.getBean(MyServices.class);
        lambdaContext.getLogger().log("AWS Request ID: " + lambdaContext.getAwsRequestId());
        lambdaContext.getLogger().log("Input: " + input + " at " + Calendar.getInstance().getTimeInMillis());
        myServices.sendGoodMessage("Message sent from Lambda");
        return "Hello World";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.springContext = applicationContext;
    }
}
</code>```

Body:
I have uploaded a simple Spring Boot project to Amazon Lambda and I am currently trying to test it.
It works 100% but I get a null pointer when I try to inject a Spring Bean
Here is my code for the LambdaHandler

package com.test.services.lambda;

import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.test.services.MyServices;

public class MyLambdaFunctionHandler implements RequestHandler<String, String> {

    public MyLambdaFunctionHandler() {
    }

    @Autowired
    private ApplicationContext springContext;
    private MyServices myServices;

    public String handleRequest(String input, Context lambdaContext) {
        this.myServices = springContext.getBean(MyServices.class);
        lambdaContext.getLogger().log("AWS Request ID: " + lambdaContext.getAwsRequestId());
        lambdaContext.getLogger().log("Input: " + input + " at " + Calendar.getInstance().getTimeInMillis());
        myServices.sendGoodMessage("Message sent from Lambda");
        return "Hello World";
    }
}

I set the handler in Amazon  Lambda to be the following

com.test.services.lambda.MyLambdaFunctionHandler::handleRequest

However when I test this function - I get this error message

{
  "errorMessage": "java.lang.NullPointerException",
  "errorType": "java.lang.NullPointerException",
  "stackTrace": [
    "com.test.services.lambda.MyLambdaFunctionHandler.handleRequest(SlackLambdaFunctionHandler.java:23)",
    "com.test.services.lambda.MyLambdaFunctionHandler.handleRequest(SlackLambdaFunctionHandler.java:12)"
  ]
}

It is failing where I inject the Spring Bean
Can anyone offer any advice on how I can go about injecting a spring bean into my AWS Lambda Handler?

Any assistance with this would be greatly appreciated

Thanks
Damien

Body:
There are a few ways to inject ApplicationContext.

Yours should work as long as spring manage your beans. Did you declare MyLambdaFunctionHandler in some @Configuration file as a @Bean?

Did you use new MyLambdaFunctionHandler() somewhere to initialize it outside spring @Configuration? (this means spring is not managing your bean).

If spring does not manage your bean it cannot inject beans into it.

If not, it should be annotated with @Component and scanned by some @ComponentScan.

If it is declared, you should use spring ApplicationContextAware to set your ApplicationContext. Spring got a lot of those utility interfaces to inject some of its core classes to your beans.

example:

public class MyLambdaFunctionHandler implements RequestHandler<String, String>, ApplicationContextAware {

    public MyLambdaFunctionHandler() {
    }

    private ApplicationContext springContext;
    private MyServices myServices;

    public String handleRequest(String input, Context lambdaContext) {
        this.myServices = springContext.getBean(MyServices.class);
        lambdaContext.getLogger().log("AWS Request ID: " + lambdaContext.getAwsRequestId());
        lambdaContext.getLogger().log("Input: " + input + " at " + Calendar.getInstance().getTimeInMillis());
        myServices.sendGoodMessage("Message sent from Lambda");
        return "Hello World";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.springContext = applicationContext;
    }
}


问:
How to convert a PDF into JPG with command line in Linux?
What are fast and reliable ways for converting a PDF into a (single) JPEG using the command line on Linux?</p>

答:
Convert from imagemagick seems to do a good job:

```<code>convert file.pdf test.jpg
</code>```

and in case there were multiple files generated:

```<code>convert test-0.jpg -append test-1.jpg ... -append one.jpg
</code>```

to generate a single file, where all pages are concatenated.

ContentLicense: CC BY-SA 4.0

Body:
Convert from imagemagick seems to do a good job:

convert file.pdf test.jpg

and in case there were multiple files generated:

convert test-0.jpg -append test-1.jpg ... -append one.jpg

to generate a single file, where all pages are concatenated.


答:
Here.
Write in A1 and pull to the right:</p>

```<code>=SUMPRODUCT(SUMIFS($D$7:$D$100;$E$7:$E$100;INDEX(COLUMN($A$1:A$1);;);$I$7:$I$100;">" & INDEX(COLUMN(A1)-COLUMN($A$1:A$1);;)))
</code>```

Title: How to write this formula on an easier way?

Body:
I need to write that on each cell:

A1: =SUMIFS($D$7:$D$100;$E$7:$E$100;"1";$I$7:$I$100;">0")

B1: =SUMIFS($D$7:$D$100;$E$7:$E$100;"1";$I$7:$I$100;">1") + SUMIFS($D$7:$D$100;$E$7:$E$100;"2";$I$7:$I$100;">0")

C1: =SUMIFS($D$7:$D$100;$E$7:$E$100;"1";$I$7:$I$100;">2") + SUMIFS($D$7:$D$100;$E$7:$E$100;"2";$I$7:$I$100;">1") + SUMIFS($D$7:$D$100;$E$7:$E$100;"3";$I$7:$I$100;">0")

D1: =SUMIFS($D$7:$D$100;$E$7:$E$100;"1";$I$7:$I$100;">3") + SUMIFS($D$7:$D$100;$E$7:$E$100;"2";$I$7:$I$100;">2") + SUMIFS($D$7:$D$100;$E$7:$E$100;"3";$I$7:$I$100;">1") + SUMIFS($D$7:$D$100;$E$7:$E$100;"4";$I$7:$I$100;">0")

And so on....

How can I make this easier to do?

Body:
Here.
Write in A1 and pull to the right:

=SUMPRODUCT(SUMIFS($D$7:$D$100;$E$7:$E$100;INDEX(COLUMN($A$1:A$1);;);$I$7:$I$100;">" & INDEX(COLUMN(A1)-COLUMN($A$1:A$1);;)))


问:
SED expression for turning Yeseva+One into --font-yeseva-one: "Yeseva One";
I have a series of font values like this (Command separated one line):

```<code>Yeseva+One, Yrsa, ...
</code>```

I'm looking for a SED (Or other bash tool expression) for turn each value into line statements like this:

```<code>--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";
</code>```

Thoughts?

Update

Just wanted to say thanks for all the great help with this and if anyone needs google fonts as CSS variables / properties they are all available here (MIT License):
https://github.com/superfly-css/superfly-css-variables-fonts/blob/master/src/main/css/index.css

I'll also be providing utilities for using google fonts here:
https://github.com/superfly-css/superfly-css-utilities-fonts

答:
awk approach:

```<code>s="Yeseva+One, Yrsa, Courier+New, Alegreya+Sans+SC"
awk -F", " '{for(i=1;i<=NF;i++){k=gensub("+","-","g",$i);
     v=gensub("+"," ","g",$i);printf "--font-%s: \"%s\";\n",tolower(k),v;}}' <<< $s
</code>```

The output:

```<code>--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";
--font-courier-new: "Courier New";
--font-alegreya-sans-sc: "Alegreya Sans SC";
</code>```

-F", " - field separator

(i=1;i<=NF;i++) - iterating through all the fields

k=gensub("+","-","g",$i); - replacing all + with - (for font key attribute)

v=gensub("+"," ","g",$i); - replacing all + with  (for font value)

Body:
I have a series of font values like this (Command separated one line):

Yeseva+One, Yrsa, ...

I'm looking for a SED (Or other bash tool expression) for turn each value into line statements like this:

--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";

Thoughts?

Update

Just wanted to say thanks for all the great help with this and if anyone needs google fonts as CSS variables / properties they are all available here (MIT License):
https://github.com/superfly-css/superfly-css-variables-fonts/blob/master/src/main/css/index.css

I'll also be providing utilities for using google fonts here:
https://github.com/superfly-css/superfly-css-utilities-fonts

Body:
awk approach:

s="Yeseva+One, Yrsa, Courier+New, Alegreya+Sans+SC"
awk -F", " '{for(i=1;i<=NF;i++){k=gensub("+","-","g",$i);
     v=gensub("+"," ","g",$i);printf "--font-%s: \"%s\";\n",tolower(k),v;}}' <<< $s

The output:

--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";
--font-courier-new: "Courier New";
--font-alegreya-sans-sc: "Alegreya Sans SC";

-F", " - field separator

(i=1;i<=NF;i++) - iterating through all the fields

k=gensub("+","-","g",$i); - replacing all + with - (for font key attribute)

v=gensub("+"," ","g",$i); - replacing all + with  (for font value)


问:
how can i refresh a page on particular time in php?
```<code><?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>
</code>```

<p>// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time   </p>

答:
You should make your code something like:</p>

```<code><?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
<script type="text/javascript">
    setInterval(function() {
        window.location.href = '<?php echo $page?>';
    },<?php echo (int)$sec ?> * 1000);
</script>
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>
</code>```

Body:
<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '
';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>

    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">

    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>

// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time

Body:
You should make your code something like:

<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
<script type="text/javascript">
    setInterval(function() {
        window.location.href = '<?php echo $page?>';
    },<?php echo (int)$sec ?> * 1000);
</script>
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>


问:
FB Marketing API V2.7 deprecation
When exactly is the FB marketing API deprecation?
On FB's developer site they say it's till April. This is the first version in which they don't mention the accurate date - but a month's scope.
Is it deprecated on the 1st of April? at the end of April?

https://developers.facebook.com/docs/marketing-api/changelog

答:
Ok. looks like FB updated their API versioning page.
The deprecation of v2.7 is on the 25th of April.
Thank you guys for your help.</p>

Title: FB Marketing API V2.7 deprecation


问:
Play Framework Compile Error: '(' expected but ')' found
When I attempting to compile my Play Framework 2. project, I receive this error: '(' expected but ')' found.
What I'm trying to do is : 'After a failed login attempt, user should get feedback. If the login attempt fails server side, show error messages on page after the failed request. Could someone please help me out.

I added the string that I want to display on the form after a failed login attempt as below:

```<code>if (response.hasErrors()) {
return ok(create.render(createViewModelForm, "invalid username or password"));
</code>```

And on the create.scala.html

```<code>@if (!@errorMessage.isEmpty()) {
  <div>@errorMessage</div>
  }
</code>```

This is the SessionsController.java   > ui\controllers\SessionsController

```<code>package femr.ui.controllers;

import com.google.inject.Inject;
import femr.business.services.core.ISessionService;
import femr.business.services.core.IUserService;
import femr.common.dtos.CurrentUser;
import femr.common.dtos.ServiceResponse;
import femr.data.models.core.IUser;
import femr.ui.models.sessions.CreateViewModel;
import femr.ui.views.html.sessions.create;
import femr.ui.views.html.sessions.editPassword;
import femr.util.calculations.dateUtils;
import femr.util.stringhelpers.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.ArrayList;
import java.util.regex.Pattern;

public class SessionsController extends Controller {

    private final FormFactory formFactory;
    private final ISessionService sessionsService;
    private final IUserService userService;

    @Inject
    public SessionsController(FormFactory formFactory, ISessionService sessionsService, IUserService userService) {

        this.formFactory = formFactory;
        this.sessionsService = sessionsService;
        this.userService = userService;
    }

    public Result createGet() {
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        if (currentUser != null) {
            return redirect(routes.HomeController.index());
        }

        return ok(create.render(createViewModelForm));
    }

    public Result createPost() {

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        ServiceResponse<CurrentUser> response = sessionsService.createSession(viewModel.getEmail(), viewModel.getPassword(), request().remoteAddress());

        if (response.hasErrors()) {
            return ok(create.render(createViewModelForm));
        }else{
            IUser user = userService.retrieveById(response.getResponseObject().getId());
            user.setLastLogin(dateUtils.getCurrentDateTime());
            ServiceResponse<IUser> userResponse = userService.update(user, false);
            if (userResponse.hasErrors()){
                throw new RuntimeException();
            }

            DateTime start = new DateTime(user.getPasswordCreatedDate());
            DateTime stop = new DateTime(DateTime.now());
            int daysBetween = Days.daysBetween(start, stop).getDays();

            if(daysBetween > 60){
                user.setPasswordReset(true);
            }

            if (user.getPasswordReset() == true){
                return editPasswordGet(user);
            }
        }

        return redirect(routes.HomeController.index());

    }

    public Result editPasswordGet(IUser user){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, new ArrayList<String>()));
    }

    public Result editPasswordPost(){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();
        IUser user = userService.retrieveById(currentUser.getId());
        Boolean isNewPassword = false;

        Pattern hasUppercase = Pattern.compile("[A-Z]");
        Pattern hasNumber = Pattern.compile("\\d");
        ArrayList<String> messages = new ArrayList<>();
        if (StringUtils.isNullOrWhiteSpace(viewModel.getNewPassword()))
            messages.add("password is a required field");
        else
        {
            if(viewModel.getNewPassword().length() < 6)        //AJ Saclayan Password Constraints
                messages.add("password is less than 6 characters");
            if (!hasUppercase.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have an uppercase");
            if (!hasNumber.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have a number");
            if(!viewModel.getNewPassword().equals(viewModel.getNewPasswordVerify()))
                messages.add("passwords do not match");
            //check if new password is equal to the old password
            if(userService.checkOldPassword(viewModel.getNewPassword(),userService.retrieveById(currentUser.getId()).getPassword()))
                messages.add("password must not be the same one used before reset");

        }

        if(!messages.isEmpty())
            return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, messages));
        else
        {
            user.setPassword(viewModel.getNewPassword());
            user.setPasswordCreatedDate(DateTime.now());
            user.setPasswordReset(false);
            isNewPassword = true;
        }

        ServiceResponse<IUser> userResponse = userService.update(user, isNewPassword);
        if (userResponse.hasErrors()){
            throw new RuntimeException();
        }
        return redirect(routes.HomeController.index());
    }

    public Result delete() {
        sessionsService.invalidateCurrentUserSession();

        return redirect(routes.HomeController.index());
    }
}
</code>```

This is the createForm in ui\views\sessions

```<code>@(gcreateForm: Form[femr.ui.models.sessions.CreateViewModel], errorMessage: java.lang.String)

@import femr.ui.views.html.layouts.main
@import femr.ui.controllers.routes.SessionsController
    @styles = {
        <link rel="stylesheet" href="@routes.Assets.versioned("css/login.css")">
    }
@main("Login", styles = styles) {

    @helper.form(action = SessionsController.createPost(), 'class -> "form-signin") {
        <div id="login">
            <h1>Please sign in</h1>
            @if (!@errorMessage.isEmpty()) {
                <div>@errorMessage</div>
            }
            <input type="text" name="email" placeholder="Email" />
            <input type="password" name="password" placeholder="Password" />
            <input type="submit" value="Log in" />
            <img src="@routes.Assets.versioned("img/logo_color_sm.png")" />
        </div>
    }
}
</code>```

HomeController.java

```<code>package femr.ui.controllers;

import com.google.inject.Inject;
import femr.common.dtos.CurrentUser;
import femr.business.services.core.ISessionService;
import femr.ui.views.html.home.index;
import femr.ui.views.html.sessions.create;
import play.mvc.Controller;
import play.mvc.Result;

public class HomeController extends Controller {

    private ISessionService sessionService;

    @Inject
    public HomeController(ISessionService sessionService) {
        this.sessionService = sessionService;
    }

    public Result index() {
        CurrentUser currentUser = sessionService.retrieveCurrentUserSession();

        if (null != currentUser) {
            return ok(index.render(currentUser));
        }
        return ok(create.render(null));
    }

}
</code>```

答:
Try using: @if(!errorMessage.isEmpty()) {

Corresponding twirl doc here.

Body:
When I attempting to compile my Play Framework 2. project, I receive this error: '(' expected but ')' found.
What I'm trying to do is : 'After a failed login attempt, user should get feedback. If the login attempt fails server side, show error messages on page after the failed request. Could someone please help me out.

I added the string that I want to display on the form after a failed login attempt as below:

if (response.hasErrors()) {
return ok(create.render(createViewModelForm, "invalid username or password"));

And on the create.scala.html

@if (!@errorMessage.isEmpty()) {

@errorMessage

  }

This is the SessionsController.java   > ui\controllers\SessionsController

package femr.ui.controllers;

import com.google.inject.Inject;
import femr.business.services.core.ISessionService;
import femr.business.services.core.IUserService;
import femr.common.dtos.CurrentUser;
import femr.common.dtos.ServiceResponse;
import femr.data.models.core.IUser;
import femr.ui.models.sessions.CreateViewModel;
import femr.ui.views.html.sessions.create;
import femr.ui.views.html.sessions.editPassword;
import femr.util.calculations.dateUtils;
import femr.util.stringhelpers.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.ArrayList;
import java.util.regex.Pattern;

public class SessionsController extends Controller {

    private final FormFactory formFactory;
    private final ISessionService sessionsService;
    private final IUserService userService;

    @Inject
    public SessionsController(FormFactory formFactory, ISessionService sessionsService, IUserService userService) {

        this.formFactory = formFactory;
        this.sessionsService = sessionsService;
        this.userService = userService;
    }

    public Result createGet() {
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        if (currentUser != null) {
            return redirect(routes.HomeController.index());
        }

        return ok(create.render(createViewModelForm));
    }

    public Result createPost() {

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        ServiceResponse<CurrentUser> response = sessionsService.createSession(viewModel.getEmail(), viewModel.getPassword(), request().remoteAddress());

        if (response.hasErrors()) {
            return ok(create.render(createViewModelForm));
        }else{
            IUser user = userService.retrieveById(response.getResponseObject().getId());
            user.setLastLogin(dateUtils.getCurrentDateTime());
            ServiceResponse<IUser> userResponse = userService.update(user, false);
            if (userResponse.hasErrors()){
                throw new RuntimeException();
            }

            DateTime start = new DateTime(user.getPasswordCreatedDate());
            DateTime stop = new DateTime(DateTime.now());
            int daysBetween = Days.daysBetween(start, stop).getDays();

            if(daysBetween > 60){
                user.setPasswordReset(true);
            }

            if (user.getPasswordReset() == true){
                return editPasswordGet(user);
            }
        }

        return redirect(routes.HomeController.index());

    }

    public Result editPasswordGet(IUser user){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, new ArrayList<String>()));
    }

    public Result editPasswordPost(){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();
        IUser user = userService.retrieveById(currentUser.getId());
        Boolean isNewPassword = false;

        Pattern hasUppercase = Pattern.compile("[A-Z]");
        Pattern hasNumber = Pattern.compile("\\d");
        ArrayList<String> messages = new ArrayList<>();
        if (StringUtils.isNullOrWhiteSpace(viewModel.getNewPassword()))
            messages.add("password is a required field");
        else
        {
            if(viewModel.getNewPassword().length() < 6)        //AJ Saclayan Password Constraints
                messages.add("password is less than 6 characters");
            if (!hasUppercase.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have an uppercase");
            if (!hasNumber.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have a number");
            if(!viewModel.getNewPassword().equals(viewModel.getNewPasswordVerify()))
                messages.add("passwords do not match");
            //check if new password is equal to the old password
            if(userService.checkOldPassword(viewModel.getNewPassword(),userService.retrieveById(currentUser.getId()).getPassword()))
                messages.add("password must not be the same one used before reset");

        }

        if(!messages.isEmpty())
            return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, messages));
        else
        {
            user.setPassword(viewModel.getNewPassword());
            user.setPasswordCreatedDate(DateTime.now());
            user.setPasswordReset(false);
            isNewPassword = true;
        }

        ServiceResponse<IUser> userResponse = userService.update(user, isNewPassword);
        if (userResponse.hasErrors()){
            throw new RuntimeException();
        }
        return redirect(routes.HomeController.index());
    }

    public Result delete() {
        sessionsService.invalidateCurrentUserSession();

        return redirect(routes.HomeController.index());
    }
}

This is the createForm in ui\views\sessions

@(gcreateForm: Form[femr.ui.models.sessions.CreateViewModel], errorMessage: java.lang.String)

@import femr.ui.views.html.layouts.main
@import femr.ui.controllers.routes.SessionsController
    @styles = {
        <link rel="stylesheet" href="@routes.Assets.versioned("css/login.css")">
    }
@main("Login", styles = styles) {

    @helper.form(action = SessionsController.createPost(), 'class -> "form-signin") {

Please sign in

            @if (!@errorMessage.isEmpty()) {

@errorMessage

            }
            <input type="text" name="email" placeholder="Email" />
            <input type="password" name="password" placeholder="Password" />
            <input type="submit" value="Log in" />

    }
}

HomeController.java

package femr.ui.controllers;

import com.google.inject.Inject;
import femr.common.dtos.CurrentUser;
import femr.business.services.core.ISessionService;
import femr.ui.views.html.home.index;
import femr.ui.views.html.sessions.create;
import play.mvc.Controller;
import play.mvc.Result;

public class HomeController extends Controller {

    private ISessionService sessionService;

    @Inject
    public HomeController(ISessionService sessionService) {
        this.sessionService = sessionService;
    }

    public Result index() {
        CurrentUser currentUser = sessionService.retrieveCurrentUserSession();

        if (null != currentUser) {
            return ok(index.render(currentUser));
        }
        return ok(create.render(null));
    }

}


问:
How to ask for permissions in MiUi pre - Marshmallow?
```<code>int permissionCheck = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.RECEIVE_SMS);

ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.READ_CONTACTS},
            PERMISSION_REQUEST_CODE);

Log.d(TAG, permissionCheck + "");
</code>```

The permission check always returns PERMISSION_GRANTED but in the OS (MiUi) the app doesn't have permissions.

Test Device : Redmi Note 3 Pro (MIUI 8)

答:
For below API 23, we usually assume that our app will have all permissions declared in the Manifest, Xiaomi being one of the exceptions.

What you could do is place your code in a try catch block and see if you can identify the scenario using the exception thrown.

I don't have such a device so cannot test this. My guess is it will throw a SecurityException.

For receive SMS permission though, i don't think you can do this. Instead, inform the user on installation to not to disable permissions. Or you could ask user to make it the default sms app.

Do try it out and let us know!

Body:
int permissionCheck = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.RECEIVE_SMS);

ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.READ_CONTACTS},
            PERMISSION_REQUEST_CODE);

Log.d(TAG, permissionCheck + "");

The permission check always returns PERMISSION_GRANTED but in the OS (MiUi) the app doesn't have permissions.

Test Device : Redmi Note 3 Pro (MIUI 8)


问:
Table structure and validation
I have a table employee and wanted suggestion for defining the primary key/table. Initially I wanted to keep EMP ID field as primary key but then I also want to keep track of all changes- TL Name for an employee. This table should allow only one unique active EMP ID, however can allow multiple inactive EMP ID. Please suggest.

Below is sample structure of table.

```<code>+----+--------+----------+---------+-----------+
| ID | EMP ID | EMP Name | TL Name | Is Active |
+----+--------+----------+---------+-----------+
| 1  | Z001   | Raj      | Vik     | No        |
+----+--------+----------+---------+-----------+
| 2  | Z002   | Ajay     | Peter   | No        |
+----+--------+----------+---------+-----------+
| 3  | Z001   | Raj      | Ashish  | No        |
+----+--------+----------+---------+-----------+
| 4  | Z003   | Soni     | Suresh  | Yes       |
+----+--------+----------+---------+-----------+
| 5  | Z001   | Raj      | Vinod   | Yes       |
+----+--------+----------+---------+-----------+
</code>```

答:
i) If you hv IsActive rule in table then EmpID can't be primary key.you hv to make it via code.

ii) If you remove IsAcTive rule,then I think EmpID is generated via code then in same code you can put one filter.so no point in making it as primary key.

Better make it CI.
iii) Make ID as PK.

iv) Many of them follow same desing pattern.If that table will grow into million of records and is very frequently use in search and join then this is definetly bad design.

If this is the case then keep seperate change table and removoe thos audit columns.

v) Even if your table is small then it is bad design.you hv to pay the price of writing isAtive='YES' in all the query.

vi) Though keeping seperate table require little more code and maintenance,it is worth doing.

Title: Table structure and validation

Body:
I have a table employee and wanted suggestion for defining the primary key/table. Initially I wanted to keep EMP ID field as primary key but then I also want to keep track of all changes- TL Name for an employee. This table should allow only one unique active EMP ID, however can allow multiple inactive EMP ID. Please suggest.

Below is sample structure of table.

+----+--------+----------+---------+-----------+
| ID | EMP ID | EMP Name | TL Name | Is Active |
+----+--------+----------+---------+-----------+
| 1  | Z001   | Raj      | Vik     | No        |
+----+--------+----------+---------+-----------+
| 2  | Z002   | Ajay     | Peter   | No        |
+----+--------+----------+---------+-----------+
| 3  | Z001   | Raj      | Ashish  | No        |
+----+--------+----------+---------+-----------+
| 4  | Z003   | Soni     | Suresh  | Yes       |
+----+--------+----------+---------+-----------+
| 5  | Z001   | Raj      | Vinod   | Yes       |
+----+--------+----------+---------+-----------+


问:
How to define file type using c1541 -write command (VICE)
I'm trying to copy foo.txt file to disk.64 image using c1541 utility.

I've tried to write:

```<code>c1541 disk.d64 -write foo.txt foo
</code>```

The file is copied but as foo.prg

How can save it using SEQ or USR types? I've tried:

```<code>c1541 disk.d64 -write foo.txt foo.seq
</code>```

only to find that the file is copied as foo.seq.prg.

答: Try c1541 disk.d64 -write foo.txt "foo,s" for SEQ-files and c1541 disk.d64 -write foo.txt "foo,u" for USR-files.

Body:
I'm trying to copy foo.txt file to disk.64 image using c1541 utility.

I've tried to write:

c1541 disk.d64 -write foo.txt foo

The file is copied but as foo.prg

How can save it using SEQ or USR types? I've tried:

c1541 disk.d64 -write foo.txt foo.seq

only to find that the file is copied as foo.seq.prg.


问:
Find a string in python files using Python
I very new to python. I am trying to find all python files that hav the string "DATASOURCE" inside them and to print the path name of the files. I'm using this code:

```<code>import os,glob

os.chdir(r"G:\PROJECTS\menofim_3_5\gis")
for file in glob.glob('*.py'):
    with open(file) as f:
        contents = f.read()
    if 'DATASOURCE' in contents:
        print file
</code>```

I only get this result:

```<code>>>>
findAndReplaceWorkspacePaths-dwg.py
Remove FGB by dataSource excluding specific mxd.py
SelectLayerByLocation2.py
SelectLayerByLocation3.py
>>>
</code>```

I have succeeded in printing the file name, but I don't know how to print the path name of the files.

答:
Use os.path.join to connect the dirname to the filename:

```<code>import os, glob

dirname = r"G:\PROJECTS\menofim_3_5\gis"
os.chdir(dirname)
for filename in glob.glob('*.py'):
    with open(filename) as f:
        contents = f.read()
    if 'DATASOURCE' in contents:
        print os.path.join(dirname, filename)
        print file
</code>```

Body:
I very new to python. I am trying to find all python files that hav the string "DATASOURCE" inside them and to print the path name of the files. I'm using this code:

import os,glob

os.chdir(r"G:\PROJECTS\menofim_3_5\gis")
for file in glob.glob('*.py'):
    with open(file) as f:
        contents = f.read()
    if 'DATASOURCE' in contents:
        print file

I only get this result:

>>>
findAndReplaceWorkspacePaths-dwg.py
Remove FGB by dataSource excluding specific mxd.py
SelectLayerByLocation2.py
SelectLayerByLocation3.py
>>>

I have succeeded in printing the file name, but I don't know how to print the path name of the files.

Body:
Use os.path.join to connect the dirname to the filename:

import os, glob

dirname = r"G:\PROJECTS\menofim_3_5\gis"
os.chdir(dirname)
for filename in glob.glob('*.py'):
    with open(filename) as f:
        contents = f.read()
    if 'DATASOURCE' in contents:
        print os.path.join(dirname, filename)
        print file


问:
Unresolved java.lang.UnsatisfiedLinkError for FaceRecognizer class
Good morning!

I'm working on a project of face recognition using java but I got this error on FaceRecognizer class:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1()J
    at com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1(Native Method)
    at com.compa.opencv.nativec.FisherFaceRecognizerID.<init>(FisherFaceRecognizerID.java:15)
    at com.compa.opencv.PlayMain.createRecognizer(PlayMain.java:128)
    at com.compa.opencv.PlayMain.cameraRecognize(PlayMain.java:88)
    at com.compa.opencv.PlayMain.main(PlayMain.java:33)
</code>```

I have tried the solutions in these below links but it didn't work :s

Getting 'java.lang.UnsatisfiedLinkError': no lwjgl in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError: no openalprjni in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError"

Here is the part of the code which contains the error:

```<code>package com.compa.opencv.nativec;

import org.opencv.contrib.FaceRecognizer;

public class FisherFaceRecognizerID extends FaceRecognizer{

    private static native long createFisherFaceRecognizer_1();

    private static native long createFisherFaceRecognizer_1(int num_components);

    private static native long createFisherFaceRecognizer_2(int num_components,
            double threshold);

    public FisherFaceRecognizerID() {
        super(createFisherFaceRecognizer_1());
    }

    public FisherFaceRecognizerID(int num_components) {
        super(createFisherFaceRecognizer_1(num_components));
    }

    public FisherFaceRecognizerID(int num_components, double threshold) {
        super(createFisherFaceRecognizer_2(num_components, threshold));
    }

}
</code>```

Full code here: https://www.dropbox.com/s/pa415f6lz3zbco7/DemoFaceRecognize-master%20%282%29.zip?dl=0

I would be grateful with any kind of help.

答:
Looks to me like you are using a third party face recognition library that depends on a native binary.

You have to add those native binaries in your class path e.g. (*.dll files in windows, or *.so in unix or linux)

UnsatisfiedLinkError - usually means a Java Native Interface (JNI) call where it fails to locate the native binary files.

Here is a screenshot on eclipse where you can see a Native Library in the source and you can click Edit and select the folder where your DLL or so files are.

Body:
Good morning!

I'm working on a project of face recognition using java but I got this error on FaceRecognizer class:

Exception in thread "main" java.lang.UnsatisfiedLinkError: com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1()J
    at com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1(Native Method)
    at com.compa.opencv.nativec.FisherFaceRecognizerID.<init>(FisherFaceRecognizerID.java:15)
    at com.compa.opencv.PlayMain.createRecognizer(PlayMain.java:128)
    at com.compa.opencv.PlayMain.cameraRecognize(PlayMain.java:88)
    at com.compa.opencv.PlayMain.main(PlayMain.java:33)

I have tried the solutions in these below links but it didn't work :s

Getting 'java.lang.UnsatisfiedLinkError': no lwjgl in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError: no openalprjni in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError"

Here is the part of the code which contains the error:

package com.compa.opencv.nativec;

import org.opencv.contrib.FaceRecognizer;

public class FisherFaceRecognizerID extends FaceRecognizer{

    private static native long createFisherFaceRecognizer_1();

    private static native long createFisherFaceRecognizer_1(int num_components);

    private static native long createFisherFaceRecognizer_2(int num_components,
            double threshold);

    public FisherFaceRecognizerID() {
        super(createFisherFaceRecognizer_1());
    }

    public FisherFaceRecognizerID(int num_components) {
        super(createFisherFaceRecognizer_1(num_components));
    }

    public FisherFaceRecognizerID(int num_components, double threshold) {
        super(createFisherFaceRecognizer_2(num_components, threshold));
    }

}

Full code here: https://www.dropbox.com/s/pa415f6lz3zbco7/DemoFaceRecognize-master%20%282%29.zip?dl=0

I would be grateful with any kind of help.


问:
Angular way to capture Id if child being clicked
I'm new to Angular 1.0 and I'm coming from jQuery backgroud.

Let's say I have following HTML :

```<code><div id="filters">
    <div id="filter1">Filter 1</div>
    <div id="filter2">Filter 2</div>
    <div id="filter3">Filter 3</div>
    <div id="filter4">Filter 4</div>
</div>
</code>```

Now I want to have a function which will return id of child element being clicked.
What could be the Angular way to best implement the following jQuery code :

```<code>$('#filters div').on('click', function() {
  alert($(this).attr("id"));
});
</code>```

答:
In angular, when you click on an element, you get an event object.

This object has a toElement property that gives you the element that received the event. You can then simply use toElement.id to display the id:

function MyController() {
  this.getId = function(event) {
    console.log(event.toElement.id);
  }
}

angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MyController as ctrl">
    <div id="filters" ng-click="ctrl.getId($event)">
        <div id="filter1">Filter 1</div>
        <div id="filter2">Filter 2</div>
        <div id="filter3">Filter 3</div>
        <div id="filter4">Filter 4</div>
    </div>
  </div>
</div></code>```

Body:
I'm new to Angular 1.0 and I'm coming from jQuery backgroud.

Let's say I have following HTML :

Filter 1

Filter 2

Filter 3

Filter 4

Now I want to have a function which will return id of child element being clicked.
What could be the Angular way to best implement the following jQuery code :

$('#filters div').on('click', function() {
  alert($(this).attr("id"));
});

Body:
In angular, when you click on an element, you get an event object.

This object has a toElement property that gives you the element that received the event. You can then simply use toElement.id to display the id:

function MyController() {
  this.getId = function(event) {
    console.log(event.toElement.id);
  }
}

angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MyController as ctrl">
    <div id="filters" ng-click="ctrl.getId($event)">
        <div id="filter1">Filter 1</div>
        <div id="filter2">Filter 2</div>
        <div id="filter3">Filter 3</div>
        <div id="filter4">Filter 4</div>
    </div>
  </div>
</div>


问:
Data fetched from server is not getting diplayed in ReactJS

import React, { Component } from 'react';
    import { TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
    import classnames from 'classnames';
    let _ = require('lodash');

    import {Doughnut} from 'react-chartjs-2';

    import {bindActionCreators} from "redux";
    import {connect} from 'react-redux';

    import {fetchedBeacons} from '../../actions/';

    // const beacon = {
    //     _id: 'jslg',
    //     name: 'beacon 1',
    //     description: 'something goes here',
    //     status: 'ACTIVE',
    //     manufacturer: 'EDDY',
    //     floor: '1st floor',
    //     location: 'entrance'
    // };

    // const advanceBeacon = {
    //   uuid: '452-457-854-521-125',
    //     major: '7458-458-56',
    //     minor: '7458-665',
    //     beaconType: 'bluetooth'
    // };

    const ChartData = {
      labels: ['wednesday', 'yesterday', 'today'],
      datasets: [
        {
          label: 'My First dataset',
          borderColor: 'rgba(255,255,255,.55)',
          data: [ 856, 785, 785],
          backgroundColor: [
      '#063e70',
      '#107bb5',
      '#666666'
      ]
        }
      ],
    };

    // TODO - come up with a decent name

    class InfoRow extends Component {
        render() {
            return (

                    {this.props.beacon}
                    {this.props.beacon}

            )
        }
    }

    class InfoRows extends Component {
      render() {
        return (

                    {this.props.beacon.major}:
                    {this.props.beacon.minor}
                    {this.props.beacon._id}

        )

      }
    }

    class BeaconChartAnalysis extends Component {
        render() {
            return (

                    <Doughnut data={ChartData}/>

            )
        }
    }

    class BeaconDetails extends Component {

        constructor(props) {
        super(props);

        this.toggle = this.toggle.bind(this);
        this.state = {
          activeTab: '1'
        };
      }

      toggle(tab) {
        if (this.state.activeTab !== tab) {
          this.setState({
            activeTab: tab
          });
        }
      }

        render() {

            const rows = [];
            let a = this.props.bcn;

            Object.keys(a).map(function(keyName, keyIndex){
              let b = a[keyName];
              console.log(b);
              return rows.push(<InfoRow beacon={keyName} key={keyIndex}/>)
            })

            const row = [];

            // this.props.bcn.map( item => {
            //     return row.push(<InfoRows beacon={item}/>)
            // });

            return (

                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '1' })}
                      onClick={() => { this.toggle('1'); }}
                    >
                      Beacon Details
                    </NavLink>
                  </NavItem>
                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '2' })}
                      onClick={() => { this.toggle('2'); }}
                    >
                      Advanced Details
                    </NavLink>
                  </NavItem>

                <TabContent activeTab={this.state.activeTab}>
                  <TabPane tabId="1">

                          {rows}

    .
                  </TabPane>

                  <TabPane tabId="2">

                          {row}

                  </TabPane>

                </TabContent>

            )

        }

    }

    class BeaconDetailComponent extends Component {

      componentWillMount = () => {
            this.props.fetchedBeacons(this.props.location.query.id);
        };

      render() {

        return (

Beacon Information {this.props.location.query.id}

                    { this.props.bcn != null?

                    <BeaconDetails bcn={this.props.bcn}/>
                    <BeaconChartAnalysis />

 :

...Loading

                }

        )
      }
    }

    function mapStateToProps(state) {
        return {
            bcn: state.beacons
        }

    }

    function matchDispatchToProps(dispatch){
        return bindActionCreators({fetchedBeacons: fetchedBeacons}, dispatch);
    }

    export default connect(mapStateToProps, matchDispatchToProps)(BeaconDetailComponent);```

i had provided the code snippet
what i wanted is to show the details fetched from the server
i also provided the screenshot that in console data is getting displayed but on the screen it is not
Image you can see the object being fetched from the server and its details being displayed in the console but it is not showing on the screen

答:
In your beaconDetails compoenent you need to pass the value to the InfoRow compoent along with the key and also perform a check for null. Also you don't need a return statement in the map function since you are pushing object to the row array

```<code> const rows = [];
        let a = this.props.bcn;
        // console.log(a);
        if(a != undefined) {
            Object.keys(a).map(function(value, keyIndex){
                 console.log(a[value]);
                 rows.push(<InfoRow beaconKey={value} beaconValue={a[value]} key={keyIndex}/>)
             })
        }
</code>```

and in your InfoRow compoent you can display this value

```<code>class InfoRow extends Component {
    render() {
        return (
            <tr>
                <td>{this.props.beacon}</td>
                <td>{this.props.beaconValue}</td>
            </tr>
        )
    }
}
</code>```

You can also change the beaconsDetail component to be like

```<code>class BeaconDetails extends Component {

        constructor(props) {
        super(props);

        this.toggle = this.toggle.bind(this);
        this.state = {
          activeTab: '1'
        };
      }

      toggle(tab) {
        if (this.state.activeTab !== tab) {
          this.setState({
            activeTab: tab
          });
        }
      }

        render() {

            const row = [];

            // this.props.bcn.map( item => {
            //     return row.push(<InfoRows beacon={item}/>)
            // });

            return (

                <div className="col-md-6 mb-2">
                <Nav tabs>
                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '1' })}
                      onClick={() => { this.toggle('1'); }}
                    >
                      Beacon Details
                    </NavLink>
                  </NavItem>
                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '2' })}
                      onClick={() => { this.toggle('2'); }}
                    >
                      Advanced Details
                    </NavLink>
                  </NavItem>
                </Nav>
                <TabContent activeTab={this.state.activeTab}>
                  <TabPane tabId="1">

                    <div className="col-lg-6">

                      <table className="table table-clear">
                        <tbody>
                          {this.props.bcn &&
                            Object.keys(this.props.bcn).map(function(keyName, keyIndex){

                                return <InfoRow beacon={keyName} beaconValue={a[keyName]}key={keyIndex}/>
                             })}
                        </tbody>
                      </table>
                     </div>
    .
                  </TabPane>

                  <TabPane tabId="2">

                    <div className="col-lg-6">
                      <table className="table table-clear">
                        <tbody>
                          {row}
                        </tbody>
                      </table>
                     </div>

                  </TabPane>

                </TabContent>
              </div>

            )

        }

    }
</code>```

Body:
import React, { Component } from 'react';
    import { TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
    import classnames from 'classnames';
    let _ = require('lodash');

    import {Doughnut} from 'react-chartjs-2';

    import {bindActionCreators} from "redux";
    import {connect} from 'react-redux';

    import {fetchedBeacons} from '../../actions/';

    // const beacon = {
    //     _id: 'jslg',
    //     name: 'beacon 1',
    //     description: 'something goes here',
    //     status: 'ACTIVE',
    //     manufacturer: 'EDDY',
    //     floor: '1st floor',
    //     location: 'entrance'
    // };

    // const advanceBeacon = {
    //   uuid: '452-457-854-521-125',
    //     major: '7458-458-56',
    //     minor: '7458-665',
    //     beaconType: 'bluetooth'
    // };

    const ChartData = {
      labels: ['wednesday', 'yesterday', 'today'],
      datasets: [
        {
          label: 'My First dataset',
          borderColor: 'rgba(255,255,255,.55)',
          data: [ 856, 785, 785],
          backgroundColor: [
      '#063e70',
      '#107bb5',
      '#666666'
      ]
        }
      ],
    };

    // TODO - come up with a decent name

    class InfoRow extends Component {
        render() {
            return (

                    {this.props.beacon}
                    {this.props.beacon}

            )
        }
    }

    class InfoRows extends Component {
      render() {
        return (

                    {this.props.beacon.major}:
                    {this.props.beacon.minor}
                    {this.props.beacon._id}

        )

      }
    }

    class BeaconChartAnalysis extends Component {
        render() {
            return (

                    <Doughnut data={ChartData}/>

            )
        }
    }

    class BeaconDetails extends Component {

        constructor(props) {
        super(props);

        this.toggle = this.toggle.bind(this);
        this.state = {
          activeTab: '1'
        };
      }

      toggle(tab) {
        if (this.state.activeTab !== tab) {
          this.setState({
            activeTab: tab
          });
        }
      }

        render() {

            const rows = [];
            let a = this.props.bcn;

            Object.keys(a).map(function(keyName, keyIndex){
              let b = a[keyName];
              console.log(b);
              return rows.push(<InfoRow beacon={keyName} key={keyIndex}/>)
            })

            const row = [];

            // this.props.bcn.map( item => {
            //     return row.push(<InfoRows beacon={item}/>)
            // });

            return (

                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '1' })}
                      onClick={() => { this.toggle('1'); }}
                    >
                      Beacon Details
                    </NavLink>
                  </NavItem>
                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '2' })}
                      onClick={() => { this.toggle('2'); }}
                    >
                      Advanced Details
                    </NavLink>
                  </NavItem>

                <TabContent activeTab={this.state.activeTab}>
                  <TabPane tabId="1">

                          {rows}

    .
                  </TabPane>

                  <TabPane tabId="2">

                          {row}

                  </TabPane>

                </TabContent>

            )

        }

    }

    class BeaconDetailComponent extends Component {

      componentWillMount = () => {
            this.props.fetchedBeacons(this.props.location.query.id);
        };

      render() {

        return (

Beacon Information {this.props.location.query.id}

                    { this.props.bcn != null?

                    <BeaconDetails bcn={this.props.bcn}/>
                    <BeaconChartAnalysis />

 :

...Loading

                }

        )
      }
    }

    function mapStateToProps(state) {
        return {
            bcn: state.beacons
        }

    }

    function matchDispatchToProps(dispatch){
        return bindActionCreators({fetchedBeacons: fetchedBeacons}, dispatch);
    }

    export default connect(mapStateToProps, matchDispatchToProps)(BeaconDetailComponent);

i had provided the code snippet
what i wanted is to show the details fetched from the server
i also provided the screenshot that in console data is getting displayed but on the screen it is not
Image you can see the object being fetched from the server and its details being displayed in the console but it is not showing on the screen

Body:
In your beaconDetails compoenent you need to pass the value to the InfoRow compoent along with the key and also perform a check for null. Also you don't need a return statement in the map function since you are pushing object to the row array

 const rows = [];
        let a = this.props.bcn;
        // console.log(a);
        if(a != undefined) {
            Object.keys(a).map(function(value, keyIndex){
                 console.log(a[value]);
                 rows.push(<InfoRow beaconKey={value} beaconValue={a[value]} key={keyIndex}/>)
             })
        }

and in your InfoRow compoent you can display this value

class InfoRow extends Component {
    render() {
        return (
            <tr>
                <td>{this.props.beacon}</td>
                <td>{this.props.beaconValue}</td>
            </tr>
        )
    }
}

You can also change the beaconsDetail component to be like

class BeaconDetails extends Component {

        constructor(props) {
        super(props);

        this.toggle = this.toggle.bind(this);
        this.state = {
          activeTab: '1'
        };
      }

      toggle(tab) {
        if (this.state.activeTab !== tab) {
          this.setState({
            activeTab: tab
          });
        }
      }

        render() {

            const row = [];

            // this.props.bcn.map( item => {
            //     return row.push(<InfoRows beacon={item}/>)
            // });

            return (

                <div className="col-md-6 mb-2">
                <Nav tabs>
                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '1' })}
                      onClick={() => { this.toggle('1'); }}
                    >
                      Beacon Details
                    </NavLink>
                  </NavItem>
                  <NavItem>
                    <NavLink
                      className={classnames({ active: this.state.activeTab === '2' })}
                      onClick={() => { this.toggle('2'); }}
                    >
                      Advanced Details
                    </NavLink>
                  </NavItem>
                </Nav>
                <TabContent activeTab={this.state.activeTab}>
                  <TabPane tabId="1">

                    <div className="col-lg-6">

                      <table className="table table-clear">
                        <tbody>
                          {this.props.bcn &&
                            Object.keys(this.props.bcn).map(function(keyName, keyIndex){

                                return <InfoRow beacon={keyName} beaconValue={a[keyName]}key={keyIndex}/>
                             })}
                        </tbody>
                      </table>
                     </div>
    .
                  </TabPane>

                  <TabPane tabId="2">

                    <div className="col-lg-6">
                      <table className="table table-clear">
                        <tbody>
                          {row}
                        </tbody>
                      </table>
                     </div>

                  </TabPane>

                </TabContent>
              </div>

            )

        }

    }


问:
File removed with option removing references and deleted from finder directly now showing the warning XCode 8
How can I remove the warning that is showing in XCode?

Warning:

file:///Users/harjotsingh/Desktop/CoreDataOBJC/CoreDataOBJC/ViewController.m:

warning: Missing file: /Users/harjotsingh/Desktop/CoreDataOBJC/CoreDataOBJC/ViewController.m is missing from working copy

Actually, I have tried all the methods cleaning the project and deleting the installed app from simulator and also deleting the build from library.

Certainly, there is a way to suppress the warning by hiding it. I don't want to hide the warnings. I want to remove them. Could someone suggest me the good way because I am trying this from months and not getting the solution to remove them.

Edited: I have selected remove references for ViewController.m and then deleted the file from finder and it is then showing me the warning.

答:
Xcode > Preferences > Source control and uncheck "Enable source control"

This worked for me.


问:
Redux-form access form's values from inside the form's instance
From my understanding from the docs if i access props.values from inside a component instance, I should get an object describing the values in each field of the form.

values : Object

The current values of all the fields in the form.

In my case, I need to access a value, in order to redirect to something like

signup?email=theemailvalue

upon form submission.

However when I access the props.value I get an empty object.

What am I doing wrong here?

答: As redux-form documentation, proper way to access form values is by formValueSelector</p>


问:
Minimising interpolation error between two data sets
In the top of the diagrams below we can see some value (y-axis) changing over time (x-axis).

As this happens we are sampling the value at different and unpredictable times, also we are alternating the sampling between two data sets, indicated by red and blue.

When computing the value at any time, we expect that both red and blue data sets will return similar values. However as shown in the three smaller boxes this is not the case. Viewed over time the values from each data set (red and blue) will appear to diverge and then converge about the original value.

Initially I used linear interpolation to obtain a value, next I tried using Catmull-Rom interpolation. The former results in a values come close together and then drift apart between each data point; the latter results in values which remain closer, but where the average error is greater.

Can anyone suggest another strategy or interpolation method which will provide greater smoothing (perhaps by using a greater number of sample points from each data set)?

答:
I believe what you ask is a question that does not have a straight answer without further knowledge on the underlying sampled process. By its nature, the value of the function between samples can be merely anything, so I think there is no way to assure the convergence of the interpolations of two sample arrays.

That said, if you have a prior knowledge of the underlying process, then you can choose among several interpolation methods to minimize the errors. For example, if you measure the drag force as a function of the wing velocity, you know the relation is square (a*V^2). Then you can choose polynomial fitting of the 2nd order and have pretty good match between the interpolations of the two serieses.


问:
plot a graph with its x-label is month and date
I have a dataframe like this

```<code>    2015max  2015min  idxmax  idxmin
01-05    242.0    -54.0   241.0  -127.0
01-26    245.0    -45.0   238.0  -134.0
04-02    298.0    -23.0   280.0   -59.0
04-04    288.0     72.0   283.0   -86.0
04-17    281.0     29.0   278.0   -47.0
</code>```

I want to overlay a scatter of the data for any points with its x-lable is a year like "01-01,01-02,01-03..."
I have tried to use

```<code>idxmin.index = pd.to_datetime(idxmin.index, format='%m-%d',errors='ignore')
</code>```

but it always remind me of the error:

ValueError: could not convert string to float

Is there someone has a good idea to solve the problem?

Body:
I have a dataframe like this

    2015max  2015min  idxmax  idxmin
01-05    242.0    -54.0   241.0  -127.0
01-26    245.0    -45.0   238.0  -134.0
04-02    298.0    -23.0   280.0   -59.0
04-04    288.0     72.0   283.0   -86.0
04-17    281.0     29.0   278.0   -47.0

I want to overlay a scatter of the data for any points with its x-lable is a year like "01-01,01-02,01-03..."
I have tried to use

idxmin.index = pd.to_datetime(idxmin.index, format='%m-%d',errors='ignore')

but it always remind me of the error:

ValueError: could not convert string to float

Is there someone has a good idea to solve the problem?

Body:
It seems in your data are some bad values, so need parameter error='coerce' for replace them to NaT and then replace NaT to some value:

print (idxmin)
       2015max  2015min  idxmax  idxmin
01-05    242.0    -54.0   241.0  -127.0
01-26    245.0    -45.0   238.0  -134.0
04-02    298.0    -23.0   280.0   -59.0
04-04    288.0     72.0   283.0   -86.0
04-35    281.0     29.0   278.0   -47.0 <- change last value to bad for testing

idxmin.index = pd.to_datetime(idxmin.index, format='%m-%d',errors='coerce')
print (idxmin)
            2015max  2015min  idxmax  idxmin
1900-01-05    242.0    -54.0   241.0  -127.0
1900-01-26    245.0    -45.0   238.0  -134.0
1900-04-02    298.0    -23.0   280.0   -59.0
1900-04-04    288.0     72.0   283.0   -86.0
NaT           281.0     29.0   278.0   -47.0

idxmin.index = idxmin.index.fillna(pd.to_datetime('01-01-2000'))
print (idxmin)
            2015max  2015min  idxmax  idxmin
1900-01-05    242.0    -54.0   241.0  -127.0
1900-01-26    245.0    -45.0   238.0  -134.0
1900-04-02    298.0    -23.0   280.0   -59.0
1900-04-04    288.0     72.0   283.0   -86.0
2000-01-01    281.0     29.0   278.0   -47.0

You can also check all bad values:

print (idxmin.index[pd.isnull(pd.to_datetime(idxmin.index, format='%m-%d',errors='coerce'))])
Index(['04-35'], dtype='object')


问:
Is it possible to redirect links to Pages instead of Projects in the Wordpress Power Builder plug-in?
https://ld-wp.template-help.com/wordpress_62222_default/home-modern/?ld&top_panel_visibility=1

Below the landing page, links to Projects are organised in a grid using the Power Builder plugin, is there anyway to redirect these to Pages instead of Projects?

Alternatively is there a plug-in which performs a similar function for Pages?

答:
This plug-in allows you to change where links go: https://wordpress.org/plugins/page-links-to/

:^]


问:
TFS Migration from 2012 & 2017 to 2017
We have to upgrade TFS version from 2012 to 2017. The problem we are facing is we have some team projects in TFS 2017 lower environment and some team projects are in 2012 production instance. We want to migrate 2012 team projects and 2017 team projects to a new TFS 2017 production instance under one team project collection. We need some help in defining the upgrade/migration strategy keeping this scenario in consideration.  Please let us know if someone can lend help. </p>

答: I'd suggest that you do the migration from TFS2012 to TFS2017 just as described by Microsoft here and after your new TFS2017 is up and running, move the Team Project Collections from your current TFS2017 to the new one which is described here</p>

Title: TFS Migration from 2012 & 2017 to 2017


问:
mongodb aggregate function implementation in java driver
How to implement this aggregate query in java i have no idea what to do?</p>

```<code>db.History.aggregate([
    { "$match" : {"thId":"001"}},
    { "$group" : {
              "_id" : {"Id":"$Id","controller" : "$controller","mod" : "$mod","variable" : "$variable"}
              ,"variable" : {"$first": "$$ROOT"}
              ,"data" : {"$push":{"value":"$value","updatedDateTime":"$updatedTime"}}
            }
    }
    ])
</code>```

答:
Refer Mongo Java Driver Documentation ,</p>

```<code>        MongoClient mongoClient = new MongoClient("localhost",27017);
        MongoDatabase database = mongoClient.getDatabase("Test");
        MongoCollection<Document> collection = database.getCollection("History");
        Document doc = new Document();
        doc.append("$match",new Document("thId","001"));
        Document group = new Document();

        group.append("$group", new Document("_id",new Document().append("Id", "$Id").append("controller", "$controller").append("mod" , "$mod").append("variable" , "$variable"))
        .append("variable" , new Document("$first", "$$ROOT"))
        .append("data",new Document().append("$push", new Document().append("value", "$value").append("updatedDateTime","$updatedTime"))));
        ArrayList<Document> docList = new ArrayList<Document>();
        docList.add(doc);
        docList.add(group);

        List<Document> results =collection.aggregate(docList).into(new ArrayList<Document>());
        for(Document res: results){
            System.out.println(res.toJson());
        }
</code>```

Body:
How to implement this aggregate query in java i have no idea what to do?

db.History.aggregate([
    { "$match" : {"thId":"001"}},
    { "$group" : {
              "_id" : {"Id":"$Id","controller" : "$controller","mod" : "$mod","variable" : "$variable"}
              ,"variable" : {"$first": "$$ROOT"}
              ,"data" : {"$push":{"value":"$value","updatedDateTime":"$updatedTime"}}
            }
    }
    ])

Body:
Refer Mongo Java Driver Documentation ,

        MongoClient mongoClient = new MongoClient("localhost",27017);
        MongoDatabase database = mongoClient.getDatabase("Test");
        MongoCollection<Document> collection = database.getCollection("History");
        Document doc = new Document();
        doc.append("$match",new Document("thId","001"));
        Document group = new Document();

        group.append("$group", new Document("_id",new Document().append("Id", "$Id").append("controller", "$controller").append("mod" , "$mod").append("variable" , "$variable"))
        .append("variable" , new Document("$first", "$$ROOT"))
        .append("data",new Document().append("$push", new Document().append("value", "$value").append("updatedDateTime","$updatedTime"))));
        ArrayList<Document> docList = new ArrayList<Document>();
        docList.add(doc);
        docList.add(group);

        List<Document> results =collection.aggregate(docList).into(new ArrayList<Document>());
        for(Document res: results){
            System.out.println(res.toJson());
        }


问:
Go importing vendor dependencies issue when building a Go 1.7 project using govendor, dh-make-golang
I've been looking into building a go project into a debian package.

I've looked into dh-make-golang and I have a nice and shiny debian folder set up in my repository. When I try to use gbp buildpackage --git-pbuilder though it errors out due to all of my dependencies not being found. It seems that dh-make-golang ignores the vendor folder when it copies everything from my project's git repository, and I use govendor so all of my dependencies are in there.

How can I resolve this dependency issue and build the project as a .deb package properly? For reference, the error I am getting is:

src/github.com/project/project/project.go:15:2: cannot find package "google.golang.org/grpc/grpclog" in any of:
    /usr/lib/go-1.7/src/google.golang.org/grpc/grpclog (from $GOROOT)
    /tmp/project/obj-x86_64-linux-gnu/src/google.golang.org/grpc/grpclog (from $GOPATH)

答:
Take a look at goxc - it can do this for you!

You simply need to add a .goxc.json to the root of your directory, that looks like this

```<code>{
    "AppName": "my_app",
    "ArtifactsDest": "downloads",
    "Tasks": [
        "interpolate-source"
        "deb",
    ],
    "BuildConstraints": "linux,amd64 windows,amd64 darwin,amd64 linux,arm",
    "ResourcesInclude": "INSTALL*,README*,LICENSE*,config/*,static/*,templates/*",
    "PackageVersion": "0.9.3",
    "TaskSettings": {
        "deb": {
            "metadata": {
                "description": "my app",
                "maintainer": "me",
                "maintainer-email": "me@example.com"
            },
            "metadata-deb": {
                "Homepage": "https://example.com"
            },
            "other-mapped-files": {
                "/": "debian/",
                "/usr/share/something/static": "static/",
                "/usr/share/something/templates": "templates/"
            }
        }
    },
    "ConfigVersion": "0.9"
}
</code>```

Then run goxc and it'll do all the work for you.

Body:
Take a look at goxc - it can do this for you!

You simply need to add a .goxc.json to the root of your directory, that looks like this

{
    "AppName": "my_app",
    "ArtifactsDest": "downloads",
    "Tasks": [
        "interpolate-source"
        "deb",
    ],
    "BuildConstraints": "linux,amd64 windows,amd64 darwin,amd64 linux,arm",
    "ResourcesInclude": "INSTALL*,README*,LICENSE*,config/*,static/*,templates/*",
    "PackageVersion": "0.9.3",
    "TaskSettings": {
        "deb": {
            "metadata": {
                "description": "my app",
                "maintainer": "me",
                "maintainer-email": "me@example.com"
            },
            "metadata-deb": {
                "Homepage": "https://example.com"
            },
            "other-mapped-files": {
                "/": "debian/",
                "/usr/share/something/static": "static/",
                "/usr/share/something/templates": "templates/"
            }
        }
    },
    "ConfigVersion": "0.9"
}

Then run goxc and it'll do all the work for you.


问:
resizing html/css to fit different devices
I've created a website and when viewing it on an iPad or iPhone (example), it doesn't resize to fit the screen. It puts my text box (with name and social media buttons) to the left and my background image to the right (with whitespace in between these two elements). I'd like the site to work when viewed in portrait and landscape, as well as on desktop browsers (resizing with browser window)

How do I implement this into my code?

HTML:

```<code> <head>
   <meta charset="UTF-8">
   <title>My site!</title>
   <link href="background.css" rel="stylesheet" type="text/css">
 </head>

 <body>
   <section class="background">
    <div class="foreground">
     <div class="name-tag">MY SITE!
     </div>
      <ul class="social-media-list">
        <li class="social-media-link">
          <a href="https://twitter.com/" target=_blank"><img src="https://cdn3.iconfinder.com/data/icons/capsocial-round/500/twitter-128.png"></a>
    </li>
    <li class="social-media-link">
      <a href="https://www.youtube.com/"><img src="https://cdn4.iconfinder.com/data/icons/social-media-icons-the-circle-set/48/youtube_circle-128.png"></a>
    </li>
    <li class="social-media-link">
      <a href="https://www.linkedin.com/in/" target=_blank"><img src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/linkedin_circle_color-512.png"></a>
    </li>
    <li class="social-media-link">
      <a href="https://www.instagram.com/" target=_blank"><img src="https://cdn2.iconfinder.com/data/icons/black-white-social-media/32/instagram_online_social_media-128.png"></a>
    </li>
  </ul>
</div>
  </section>
 </body>

 </html>
</code>```

CSS:

```<code>   /* Body Margin*/

body {
  margin: 0;
 }

 /*  Font family avenir-light*/

 @font-face {
   font-family: 'avenir-light';
  src: url('fonts/avenir-light.eot') format('eot'), url('fonts/avenir-light.woff') format('woff'), url('fonts/avenir-light.ttf') format('ttf');
}

 /* Background Div*/

.background {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
}

 /* Background Div: after*/

.background:after {
   position: absolute;
   width: 100vw;
   height: 100vh;
   content: '';
   background-image: url("bkgd.jpg");
   background-repeat: no-repeat;
   background-size: cover;
   -webkit-animation: fadein 3s;
   /* Safari, Chrome and Opera > 12.1 */
    -moz-animation: fadein 3s;
    /* Firefox < 16 */
    -ms-animation: fadein 3s;
   /* Internet Explorer */
   -o-animation: fadein 3s;
   /* Opera < 12.1 */
   animation: fadein 3s;
   /*Fade In Animation*/
 }

 /* Fade in animations */

 @keyframes fadein {
   from {
     opacity: 0.2;
   }
   to {
     opacity: 1;
   }
}

 /* Firefox < 16 */

 @-moz-keyframes fadein {
   from {
    opacity: 0.2;
   }
   to {
     opacity: 1;
   }
 }

  /* Safari, Chrome and Opera > 12.1 */

  @-webkit-keyframes fadein {
    from {
     opacity: 0.2;
       }
    to {
     opacity: 1;
   }
 }

 /* Internet Explorer */

 @-ms-keyframes fadein {
   from {
     opacity: 0.2;
   }
   to {
     opacity: 1;
   }
 }

 /* Opera < 12.1 */

 @-o-keyframes fadein {
   opacity: 0.2;
 }

 to {
   opacity: 1;
 }

 /* Foreground div */

 .foreground {
   margin-top: 20px;
   position: relative;
   width: 400px;
   height: 100px;
    background-color: #eaeaea;
    padding: 20px;
    border: 1px solid #555;
     border-radius: 10px;
   /*Fade In Animation*/
   -webkit-animation: fadein 5s;
   /* Safari, Chrome and Opera > 12.1 */
  -moz-animation: fadein 5s;
   /* Firefox < 16 */
   -ms-animation: fadein 5s;
   /* Internet Explorer */
   -o-animation: fadein 5s;
   /* Opera < 12.1 */
   animation: fadein 5s;
    z-index: 1;
   }

 /* Name Tag */

  .name-tag {
   font-family: 'avenir-light';
   text-align: center;
    font-size: 24px;
  }

 /* Social Media List*/

 .social-media-list {
   list-style: none;
    display: flex;
    justify-content: space-around;
     padding: 0;
    }

  /* Social Media Item*/

  .social-media-link img {
   height: 50px;
   width: 50px;
  transition:all 0.5s ease;
  }

 .social-media-link img:hover {
  -ms-transform: scale(1.2);
  /* IE 9 */
  -webkit-transform: scale(1.2);
   /* Safari */
   transform: scale(1.2);
  /* Standard syntax */
 }
</code>```

答: You can use Bootstrap for this purpose. Bootstrap divides the screen into 12 columns. for different screen size different classes are there like for medium size you can use col-md-3 or for small size devices col-sm-3 and so on.</p>

Body:
I've created a website and when viewing it on an iPad or iPhone (example), it doesn't resize to fit the screen. It puts my text box (with name and social media buttons) to the left and my background image to the right (with whitespace in between these two elements). I'd like the site to work when viewed in portrait and landscape, as well as on desktop browsers (resizing with browser window)

How do I implement this into my code?

HTML:

   <meta charset="UTF-8">
   <title>My site!</title>
   <link href="background.css" rel="stylesheet" type="text/css">

MY SITE!

CSS:

   /* Body Margin*/

body {
  margin: 0;
 }

 /*  Font family avenir-light*/

 @font-face {
   font-family: 'avenir-light';
  src: url('fonts/avenir-light.eot') format('eot'), url('fonts/avenir-light.woff') format('woff'), url('fonts/avenir-light.ttf') format('ttf');
}

 /* Background Div*/

.background {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
}

 /* Background Div: after*/

.background:after {
   position: absolute;
   width: 100vw;
   height: 100vh;
   content: '';
   background-image: url("bkgd.jpg");
   background-repeat: no-repeat;
   background-size: cover;
   -webkit-animation: fadein 3s;
   /* Safari, Chrome and Opera > 12.1 */
    -moz-animation: fadein 3s;
    /* Firefox < 16 */
    -ms-animation: fadein 3s;
   /* Internet Explorer */
   -o-animation: fadein 3s;
   /* Opera < 12.1 */
   animation: fadein 3s;
   /*Fade In Animation*/
 }

 /* Fade in animations */

 @keyframes fadein {
   from {
     opacity: 0.2;
   }
   to {
     opacity: 1;
   }
}

 /* Firefox < 16 */

 @-moz-keyframes fadein {
   from {
    opacity: 0.2;
   }
   to {
     opacity: 1;
   }
 }

  /* Safari, Chrome and Opera > 12.1 */

  @-webkit-keyframes fadein {
    from {
     opacity: 0.2;
       }
    to {
     opacity: 1;
   }
 }

 /* Internet Explorer */

 @-ms-keyframes fadein {
   from {
     opacity: 0.2;
   }
   to {
     opacity: 1;
   }
 }

 /* Opera < 12.1 */

 @-o-keyframes fadein {
   opacity: 0.2;
 }

 to {
   opacity: 1;
 }

 /* Foreground div */

 .foreground {
   margin-top: 20px;
   position: relative;
   width: 400px;
   height: 100px;
    background-color: #eaeaea;
    padding: 20px;
    border: 1px solid #555;
     border-radius: 10px;
   /*Fade In Animation*/
   -webkit-animation: fadein 5s;
   /* Safari, Chrome and Opera > 12.1 */
  -moz-animation: fadein 5s;
   /* Firefox < 16 */
   -ms-animation: fadein 5s;
   /* Internet Explorer */
   -o-animation: fadein 5s;
   /* Opera < 12.1 */
   animation: fadein 5s;
    z-index: 1;
   }

 /* Name Tag */

  .name-tag {
   font-family: 'avenir-light';
   text-align: center;
    font-size: 24px;
  }

 /* Social Media List*/

 .social-media-list {
   list-style: none;
    display: flex;
    justify-content: space-around;
     padding: 0;
    }

  /* Social Media Item*/

  .social-media-link img {
   height: 50px;
   width: 50px;
  transition:all 0.5s ease;
  }

 .social-media-link img:hover {
  -ms-transform: scale(1.2);
  /* IE 9 */
  -webkit-transform: scale(1.2);
   /* Safari */
   transform: scale(1.2);
  /* Standard syntax */
 }


问:
Print output not showing the correct format
I have written the python code as below:

```<code>magicNumber = 25

for n in range(100):
    if n is magicNumber:
        print(n, " is the magic number")
        break
    else:
        print(n)
</code>```

The last line of output is showing in the format as below:

```<code>(25, ' is the magic number')
</code>```

Please let me know what can i do to have the last line of the output as:

```<code>25 is the magic number
</code>```

答:
for python 2.x  - print acts as a command
just remove the brackets and it will work as expected.

print n, " is the magic number"

for python 3.x - print acts as a function; so below is fine.

print(n, " is the magic number")

There are some other methods also as suggested by the user abccd.

Body:
I have written the python code as below:

magicNumber = 25

for n in range(100):
    if n is magicNumber:
        print(n, " is the magic number")
        break
    else:
        print(n)

The last line of output is showing in the format as below:

(25, ' is the magic number')

Please let me know what can i do to have the last line of the output as:

25 is the magic number


答:
Here's a minimal approach in which the ID is directly passed from the HTML template. This way, you can keep your controller as clean as possible and you don't need to create any additional directives.

Filter 1

Filter 2

Filter 3

Filter 4

```

Title: Angular way to capture Id if child being clicked

Body:
Here's a minimal approach in which the ID is directly passed from the HTML template. This way, you can keep your controller as clean as possible and you don't need to create any additional directives.

<div ng-app="app">
  <div ng-controller="MainCtrl as $ctrl">
    <div id="filters">
      <div id="filter1" ng-click="$ctrl.showId($event.target.id)">Filter 1</div>
      <div id="filter2" ng-click="$ctrl.showId($event.target.id)">Filter 2</div>
      <div id="filter3" ng-click="$ctrl.showId($event.target.id)">Filter 3</div>
      <div id="filter4" ng-click="$ctrl.showId($event.target.id)">Filter 4</div>
    </div>
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<script>
  angular
    .module('app', [])
    .controller('MainCtrl', function() {
      this.showId = function(id) {
        console.log(id);
      }
    });
</script>