问:
The remote endpoint could not be called alexa
I'm trying to develop an alexa skill, whichs communicates with my own webservice (tomcat). To set up the project i followed the amazon guides (https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/deploying-a-sample-skill-as-a-web-service).

Now I still can't connect to the webservice and only get the message "The remote endpoint could not be called, or the response it returned was invalid".

The Service is hosted on https://ec2-54-159-167-123.compute-1.amazonaws.com/PiaServer and is reachable with https. I used a self-signed certificate. I did everything as described in the documentation, but still can't connect. There are no tomcat logs at all.

My endpoint is a speechletServlet from amazon java-skill-kit.

When I do the request via Postman (Chrome Addon), I get a perfect JSON-Response (see below):

```<code>{ "version": "1.0", "response": { "outputSpeech": {"type":"PlainText", "text": "text" }, "card": { "type": "Simple", "title":`enter code here`"Tank", "content": "text" }, "shouldEndSession": true } }
</code>```

Do you have any Ideas how to solve this?

EDIT: I hosted the service on Amazon EC2.

答:
I had also faced the same issue. I was able to solve by modifying the slot values.
For example slot part in the request is given as below, </p>

```<code>   "slots": {"<intent-slot-name>": {
      "name": "<intent-slot-name>",
      "value": "<value>"
    }}
</code>```

Body:
I'm trying to develop an alexa skill, whichs communicates with my own webservice (tomcat). To set up the project i followed the amazon guides (https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/deploying-a-sample-skill-as-a-web-service).

Now I still can't connect to the webservice and only get the message "The remote endpoint could not be called, or the response it returned was invalid".

The Service is hosted on https://ec2-54-159-167-123.compute-1.amazonaws.com/PiaServer and is reachable with https. I used a self-signed certificate. I did everything as described in the documentation, but still can't connect. There are no tomcat logs at all.

My endpoint is a speechletServlet from amazon java-skill-kit.

When I do the request via Postman (Chrome Addon), I get a perfect JSON-Response (see below):

{ "version": "1.0", "response": { "outputSpeech": {"type":"PlainText", "text": "text" }, "card": { "type": "Simple", "title":`enter code here`"Tank", "content": "text" }, "shouldEndSession": true } }

Do you have any Ideas how to solve this?

EDIT: I hosted the service on Amazon EC2.

Body:
I had also faced the same issue. I was able to solve by modifying the slot values.
For example slot part in the request is given as below,

   "slots": {"<intent-slot-name>": {
      "name": "<intent-slot-name>",
      "value": "<value>"
    }}


来源: stackexchange

问:
Google cloud storage PHP
Hi I am getting a strange error when I run the following script. It is returning this error message

```<code>Parse error: syntax error, unexpected 'new' (T_NEW) in /home/apipetfindr/public_html/sys/v1/google_cloud_storeage_upload.php on line 9
</code>```

I am wondering why this part of my code is not working:

```<code>private $storage = new StorageClient
</code>```

I know I need to call the new function I have tried public instead of private with no success. if anyone can point me in the right direction that would be great.

```<code><?php
# Includes the autoloader for libraries installed with composer
require '../vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;

class googleupload{

  private $storage = new StorageClient([
      'projectId' => 'xxxxxxxxxx'
  ]);

  private $bucket = $storage->bucket('BUCKET_NAME');

  // Upload a file to the bucket.
  //$bucket->upload(
  //    fopen('/data/file.txt', 'r')
  //);

  public function uploads($_FILE, $uid){
        $obj = new Google_Service_Storage_StorageObject();
        $obj->setName($file_name);

        $resp = $storage->objects->insert(
            "bucketname",
            $obj,
            array('name' => $file_name, 'data' => file_get_contents("300mb-file.zip"), 'uploadType' => 'media')
        );

  }
}
/*
// Download and store an object from the bucket locally.
$object = $bucket->object('file_backup.txt');
$object->downloadToFile('/data/file_backup.txt');
*/
?>
</code>```

答:
You are not allowed to use something like new Object(x, y, [z]) as a default value for a class property. If you want to have always the same property-value, e.g. your object with projectId xxxx, you can put something like this within your constructor:

```<code>public function __construct(){
  $this->storage = new StorageClient(['projectId' => 'xxxxxxxx']);
  $this->bucket = $this->storage->bucket('BUCKET_NAME');
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Google cloud storage PHP

Body:
Hi I am getting a strange error when I run the following script. It is returning this error message

Parse error: syntax error, unexpected 'new' (T_NEW) in /home/apipetfindr/public_html/sys/v1/google_cloud_storeage_upload.php on line 9

I am wondering why this part of my code is not working:

private $storage = new StorageClient

I know I need to call the new function I have tried public instead of private with no success. if anyone can point me in the right direction that would be great.

<?php
# Includes the autoloader for libraries installed with composer
require '../vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;

class googleupload{

  private $storage = new StorageClient([
      'projectId' => 'xxxxxxxxxx'
  ]);

  private $bucket = $storage->bucket('BUCKET_NAME');

  // Upload a file to the bucket.
  //$bucket->upload(
  //    fopen('/data/file.txt', 'r')
  //);

  public function uploads($_FILE, $uid){
        $obj = new Google_Service_Storage_StorageObject();
        $obj->setName($file_name);

        $resp = $storage->objects->insert(
            "bucketname",
            $obj,
            array('name' => $file_name, 'data' => file_get_contents("300mb-file.zip"), 'uploadType' => 'media')
        );

  }
}
/*
// Download and store an object from the bucket locally.
$object = $bucket->object('file_backup.txt');
$object->downloadToFile('/data/file_backup.txt');
*/
?>

Body:
You are not allowed to use something like new Object(x, y, [z]) as a default value for a class property. If you want to have always the same property-value, e.g. your object with projectId xxxx, you can put something like this within your constructor:

public function __construct(){
  $this->storage = new StorageClient(['projectId' => 'xxxxxxxx']);
  $this->bucket = $this->storage->bucket('BUCKET_NAME');
}


问:
SELECT data based on given pairs
I have little experience using SQL, and I am now using JDBC to connect to my database.
I am using sqlite, my schema looks as follows:

```<code>id1, id2, value1, value2
</code>```

I want to extract rows based on a list of given pairs of id1 and id2.
I know Postgresql can do

```<code>SELECT  *
FROM    table
WHERE   ("id1", "id2") IN (('1', '2'), ('3', '4'));
</code>```

But what about sqlite?

Title: SELECT data based on given pairs

Body:
I have little experience using SQL, and I am now using JDBC to connect to my database.
I am using sqlite, my schema looks as follows:

id1, id2, value1, value2

I want to extract rows based on a list of given pairs of id1 and id2.
I know Postgresql can do

SELECT  *
FROM    table
WHERE   ("id1", "id2") IN (('1', '2'), ('3', '4'));

But what about sqlite?

Body:
if you have a long list you can do this

SELECT  *
FROM    table
WHERE   (id1 in('1','11','111') and id2 in ('22','2','222')) OR
        (id1 in('333','33','3') and id2 in('444,'44','4')')


问:
Passing data dynamically to directive's transcluded controller
I have a directive for a single popup element. Depending on which of many hundreds of elements that are clicked on, I need to pass different data to the popup when it is displayed. Using a service to store/fetch the data seems like a side-band hack. Storing the data in my top-level controller and allowing the popup controller to inherit seems like poor encapsulation. I'd like to have an isolate scope in the directive and have the popup controller inherit from that. This doesn't seem to work. Any thoughts? Is $broadcast my only option?</p>

答:
I assume that you are working with AngularJS 1.x.  I think directive Transclusion is what you are looking for.  Transclusion provides a way to include markup that is bound to the parent controller inside the content area of a directive.

Check out this Plunker which is taken from the AngularJS documentation.

```<code> .directive('pane', function() {
    return {
      restrict: 'E',
      transclude: {
        'title': '?paneTitle',
        'body': 'paneBody',
        'footer': '?paneFooter'
      },
      template: '<div style="border: 1px solid black;">' +
                  '<div class="title" ng-transclude="title">Fallback Title</div>' +
                  '<div **ng-transclude="body"**></div>' +
                  '<div class="footer" **ng-transclude="footer"**>Fallback Footer</div>' +
                '</div>'
    };

<div ng-controller="ExampleController">
  <input ng-model="title" aria-label="title"> <br/>
  <textarea ng-model="text" aria-label="text"></textarea> <br/>
  <pane>
    <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
    <pane-body><p>{{text}}</p></pane-body>
  </pane>
</div>
</code>```

Pane is the directive.  Note that the content contained in pane-title and pane-body are being compiled against the parent controller, but are displayed in the ng-transclude portions of the directive mark-up.

You should be able to use this to get your custom data into your popup without the need of a service or $broadcast.

Body:
I assume that you are working with AngularJS 1.x.  I think directive Transclusion is what you are looking for.  Transclusion provides a way to include markup that is bound to the parent controller inside the content area of a directive.

Check out this Plunker which is taken from the AngularJS documentation.

 .directive('pane', function() {
    return {
      restrict: 'E',
      transclude: {
        'title': '?paneTitle',
        'body': 'paneBody',
        'footer': '?paneFooter'
      },
      template: '<div style="border: 1px solid black;">' +
                  '<div class="title" ng-transclude="title">Fallback Title</div>' +
                  '<div **ng-transclude="body"**></div>' +
                  '<div class="footer" **ng-transclude="footer"**>Fallback Footer</div>' +
                '</div>'
    };

<div ng-controller="ExampleController">
  <input ng-model="title" aria-label="title"> <br/>
  <textarea ng-model="text" aria-label="text"></textarea> <br/>
  <pane>
    <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
    <pane-body><p>{{text}}</p></pane-body>
  </pane>
</div>

Pane is the directive.  Note that the content contained in pane-title and pane-body are being compiled against the parent controller, but are displayed in the ng-transclude portions of the directive mark-up.

You should be able to use this to get your custom data into your popup without the need of a service or $broadcast.


问:
How do you generate a random number in C#?
I would like to generate a random floating point number between 2 values.  What is the best way to do this in C#?</p>

答:
```<code>System.Random r = new System.Random();

double rnd( double a, double b )
{
   return a + r.NextDouble()*(b-a);
}
</code>```

OwnerDisplayName: Lane

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: MrValdez

OwnerDisplayName: Eric


问:
How to store a list in a db column
I would like to store an object FOO in a database.
Lets say FOO contains three integers and a list of "Fruits".

The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table.

Can I store the fruit list in a column?

答: You can, but it will likely treated as text, making searching in this column difficult and slow. You're better of using a related table.</p>

OwnerDisplayName: Stumproot

Title: How to store a list in a db column

OwnerDisplayName: Diodeus


问:
Large Scale VHDL modularization techniques
I'm thinking about implimenting a 16 bit CPU in VHDL.
A simplish CPU.
ADD, MULS, NEG, BitShift, JUMP, Relitive Jump, BREQ, Relitive BREQ, i don't know somethign along these lines>
Probably all only working with 16bit operands.
I might even cut it down and use only a single operand and a accumulator.
With Some status regitsters, Carry, Zero, Neg (unless i use a Accumlator),

I know how to design all the parts from logic gates, and plan to build them up from first priciples,
So for my ALU I'll need to 'build' a ADDer, proably a Carry Look ahead, group adder,
this adder it self is make up oa a couple of parts, wich are themselves made up of a couple of parts.

Anyway, my problem is not the CPU design, or the VHDL (i know the language, more or less).
It's how i should keep things organised.
How should I use packages,
How should I name my processes and port maps? (i've never seen the benifit of naming the port maps, or processes)

答:
Whatever you do, be sure to read Jiri Gaisler's master work on structured VHDL design method.

http://www.gaisler.com/doc/vhdl2proc.pdf
http://www.gaisler.com/doc/structdes.pdf

You'll be very glad you did.


问:
Python Django mysqldb select with unicode value
When I use this clause, everything is right. find in here is モンキー・D・ルフィ

```<code>   sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in ('%s');" % find.encode('utf-8')
   self.db.execute(sql_fmt)
</code>```

But when I use this clause, error happened. find in here is (モンキー・D・ルフィ) or ('モンキー・D・ルフィ')

```<code>sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in %s;"
self.db.execute(sql_fmt, find)
</code>```

Error:

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''(\'\xe3\x83\xa2\xe3\x83\xb3\xe3\x82\xad\xe3\x83\xbc\xe3\x83\xbbD\xe3\x83\xbb\xe3\x83\xab\xe3\x83\x95\xe3\x82\xa3\')'' at line 1")
  And for this clause, error happened. find here is モンキー・D・ルフィ.

```<code>sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in ('%s');"
self.db.execute(sql_fmt, find)
</code>```

And for this clause, everything goes well. find here is モンキー・D・ルフィ.

```<code>sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in (%s);"
self.db.execute(sql_fmt, find)
</code>```

Note :

I use in means it is a set of strings, but not just a single string.

答:
May be you missing "" in the query

```<code># it should be:
select * from characters where name = "some string"
#OR
select * from characters where name in "some string"
# In your case:
sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in "%s";"
</code>```

Or may be some kind of this, i don't use it.

You should use:

```<code>res = Models.Objects.filter(name__in = yourlist)
# Django help you all the way to convert it to Query
</code>```

Body:
When I use this clause, everything is right. find in here is モンキー・D・ルフィ

   sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in ('%s');" % find.encode('utf-8')
   self.db.execute(sql_fmt)

But when I use this clause, error happened. find in here is (モンキー・D・ルフィ) or ('モンキー・D・ルフィ')

sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in %s;"
self.db.execute(sql_fmt, find)

Error:

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''(\'\xe3\x83\xa2\xe3\x83\xb3\xe3\x82\xad\xe3\x83\xbc\xe3\x83\xbbD\xe3\x83\xbb\xe3\x83\xab\xe3\x83\x95\xe3\x82\xa3\')'' at line 1")
  And for this clause, error happened. find here is モンキー・D・ルフィ.

sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in ('%s');"
self.db.execute(sql_fmt, find)

And for this clause, everything goes well. find here is モンキー・D・ルフィ.

sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in (%s);"
self.db.execute(sql_fmt, find)

Note :

I use in means it is a set of strings, but not just a single string.

Body:
May be you missing "" in the query

# it should be:
select * from characters where name = "some string"
#OR
select * from characters where name in "some string"
# In your case:
sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in "%s";"

Or may be some kind of this, i don't use it.

You should use:

res = Models.Objects.filter(name__in = yourlist)
# Django help you all the way to convert it to Query


问:
IntPredicate Lambda Java8
The functionality of the following method is to try to traverse a list from 3 to 999 by adding the multiples of two numbers, where multiplosDe.get(0) could be 4 and multiplosDe.get(1) could be 7.

This function works if I only send a list with two Integer objects. What I want is to be able to send a list of n objects and do not have to have the need to add  || multiplosDe.get(2) to predicate.

```<code>public long sumaDeMultiplos(List<Integer> multiplosDe) {
    int suma = 0;
    IntPredicate predicate  = s -> (s%multiplosDe.get(0)==0 || s%multiplosDe.get(1)==0);

        suma = IntStream.range(3, 1000).filter(predicate).sum();

    return suma;
}
</code>```

答:
```<code>IntPredicate predicate  = s -> multiplosDe.stream().anyMatch(i -> s % i == 0);
</code>```

Title: IntPredicate Lambda Java8

Body:
The functionality of the following method is to try to traverse a list from 3 to 999 by adding the multiples of two numbers, where multiplosDe.get(0) could be 4 and multiplosDe.get(1) could be 7.

This function works if I only send a list with two Integer objects. What I want is to be able to send a list of n objects and do not have to have the need to add  || multiplosDe.get(2) to predicate.

public long sumaDeMultiplos(List<Integer> multiplosDe) {
    int suma = 0;
    IntPredicate predicate  = s -> (s%multiplosDe.get(0)==0 || s%multiplosDe.get(1)==0);

        suma = IntStream.range(3, 1000).filter(predicate).sum();

    return suma;
}


问:
Multiple definition when compiling
I have these files:

```<code>main.cpp
headers.h
calculator.h
calculator.cpp
Supported_operators.h
Supported_operators.c
My_Operations.h
My_Operations.cpp
</code>```

My headers.h file has (apart from std libs): #include "Supported_operators.h" and finally my Supported_operators.h has the following:

```<code>#ifndef CALCULATOR_SUPPORTED_OPERATORS_H
#define CALCULATOR_SUPPORTED_OPERATORS_H

#include "headers.h"
//using directives
class Supported_operator {
//stuff
};

list<Supported_operator> supportedOps = {
                                        Supported_operator('+', 2, 'l'),
                                        Supported_operator('-', 2, 'l'),
                                        Supported_operator('*', 3, 'l'),
                                        Supported_operator('/', 3, 'l'),
                                        Supported_operator('^', 4, 'r')
                                        };

#endif //CALCULATOR_SUPPORTED_OPERATORS_H
</code>```

When I try to compile the program, the compilator says multiple definition of supportedOps[abi:cxx11] at my main().

How do I solve this problem?

Context: I'm trying to make a calculator. Have to split string input into tokens. If token is an operator, do certain operations depending on that operator. So I have to create a container of SupportedOperators and then check if tokened operator is supported and what are its properties.

EDIT 2: My headers.h file now includes const list<Supported_operator> supportedOps; and my Supported_operators.cpp now has list<Supported_operator> supportedOps = { }; but then the headers.h triggers error list does not name a type.

EDIT 3: Changing the declaration in headers.h to extern const std::list<> supportedOps; now results in a new set of errors - Supported_operator was not declared in that scope. I thought I had this covered with #include "Supported_operators.h where Supported_operator is declared. Am I assuming correctly the compilers doesn't know of class Supported_operator yet? How do I work around this?

答:
If you don't need to change supportedOps, you can also add const directly in front of the variable.

```<code>const list<Supported_operator> supportedOps = { }
</code>```

This will pass ODR check, since the variable in all translate units are guaranteed to be the same.

Title: Multiple definition when compiling

Body:
I have these files:

main.cpp
headers.h
calculator.h
calculator.cpp
Supported_operators.h
Supported_operators.c
My_Operations.h
My_Operations.cpp

My headers.h file has (apart from std libs): #include "Supported_operators.h" and finally my Supported_operators.h has the following:

#ifndef CALCULATOR_SUPPORTED_OPERATORS_H
#define CALCULATOR_SUPPORTED_OPERATORS_H

#include "headers.h"
//using directives
class Supported_operator {
//stuff
};

list<Supported_operator> supportedOps = {
                                        Supported_operator('+', 2, 'l'),
                                        Supported_operator('-', 2, 'l'),
                                        Supported_operator('*', 3, 'l'),
                                        Supported_operator('/', 3, 'l'),
                                        Supported_operator('^', 4, 'r')
                                        };

#endif //CALCULATOR_SUPPORTED_OPERATORS_H

When I try to compile the program, the compilator says multiple definition of supportedOps[abi:cxx11] at my main().

How do I solve this problem?

Context: I'm trying to make a calculator. Have to split string input into tokens. If token is an operator, do certain operations depending on that operator. So I have to create a container of SupportedOperators and then check if tokened operator is supported and what are its properties.

EDIT 2: My headers.h file now includes const list<Supported_operator> supportedOps; and my Supported_operators.cpp now has list<Supported_operator> supportedOps = { }; but then the headers.h triggers error list does not name a type.

EDIT 3: Changing the declaration in headers.h to extern const std::list<> supportedOps; now results in a new set of errors - Supported_operator was not declared in that scope. I thought I had this covered with #include "Supported_operators.h where Supported_operator is declared. Am I assuming correctly the compilers doesn't know of class Supported_operator yet? How do I work around this?

Body:
If you don't need to change supportedOps, you can also add const directly in front of the variable.

const list<Supported_operator> supportedOps = { }

This will pass ODR check, since the variable in all translate units are guaranteed to be the same.


问:
What exactly is stdin?
I am a bit confused regarding the implementation of stdin. What exactly is it? Is it a pointer? I tried to print the size of stdin using sizeof on a 64 bit machine and got 8. I even de-referenced it using *stdin in the %s specifier and got the not used characters in the input stream( all of them). But if I compare its de referenced value inside if I get an error. I know its an input stream. But how is it implemented?

Here is a sample:

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

int main(){

    char a[10];

    fgets(a,10,stdin);

    printf("a: %s",a);

    printf("\nstdin: %s",*stdin);

//if(*stdin=="foo"){
//    printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help

    printf("\nSize of stdin: %d\n",sizeof(stdin));

    if(stdin!=NULL){
        printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
    }

if(!feof(stdin)){
    printf("\nThis statement is also always reached");
}
}
</code>```

When I input

foobar1234567890

I get the result:

a: foobar123

stdin: 4567890

Size of stdin: 8

This statement is always reached

This statement is also always reached

And when I input

foobar

I get the output

a: foobar

stdin:

Size of stdin: 4

This statement is always reached

This statement is also always reached

I understand that stdin is kind of a FILE pointer, but I don't clearly get it. Could anyone explain the above outputs?

答:
```<code>typedef struct _IO_FILE FILE;
extern struct _IO_FILE *stdin;
</code>```

So it is a pointer to FILE.

The Standard says:

7.21 Input/output

```<code>stderr
stdin
stdout
which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects
associated, respectively, with the standard error, input, and output streams.
</code>```

Title: What exactly is stdin?

Body:
I am a bit confused regarding the implementation of stdin. What exactly is it? Is it a pointer? I tried to print the size of stdin using sizeof on a 64 bit machine and got 8. I even de-referenced it using *stdin in the %s specifier and got the not used characters in the input stream( all of them). But if I compare its de referenced value inside if I get an error. I know its an input stream. But how is it implemented?

Here is a sample:

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

int main(){

    char a[10];

    fgets(a,10,stdin);

    printf("a: %s",a);

    printf("\nstdin: %s",*stdin);

//if(*stdin=="foo"){
//    printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help

    printf("\nSize of stdin: %d\n",sizeof(stdin));

    if(stdin!=NULL){
        printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
    }

if(!feof(stdin)){
    printf("\nThis statement is also always reached");
}
}

When I input

foobar1234567890

I get the result:

a: foobar123

stdin: 4567890

Size of stdin: 8

This statement is always reached

This statement is also always reached

And when I input

foobar

I get the output

a: foobar

stdin:

Size of stdin: 4

This statement is always reached

This statement is also always reached

I understand that stdin is kind of a FILE pointer, but I don't clearly get it. Could anyone explain the above outputs?

Body:
typedef struct _IO_FILE FILE;
extern struct _IO_FILE *stdin;

So it is a pointer to FILE.

The Standard says:

7.21 Input/output

stderr
stdin
stdout
which are expressions of type ‘‘pointer to FILE’’ that point to the FILE objects
associated, respectively, with the standard error, input, and output streams.


问:
Create simple xlsx (excel file ) from javascript or Jquery
This is the fiddle https://jsfiddle.net/ym4egje0/

I have two things to ask

this is creating a xls , how to create a xlsx file and it does not work in IE , only works in google chrome , how to make it work in IE ?

I want to put  ColumnHead column header text and message1 and message2 should be consecutive rows .

Have to take as the index of (.) to cut into rows  .

HTML

```<code><input id="btnExport" type="button" value = "Generate File" />
</code>```

JS/Jquery

```<code>$("#btnExport").click(function (e) {

var ColumnHead = "Column Header Text";
var Messages = "\n message1.\n message2.";
   window.open('data:application/vnd.ms-excel,' + Messages);
    e.preventDefault();

});
</code>```

答:
Check out this fiddle to solve your problem . it will create file for both Google chrome and IE

https://jsfiddle.net/shaswatatripathy/fo4ugmLp/1/

HTML

```<code><input type="button" id="test" onClick="fnExcelReport();" value="download" />

<div id='MessageHolder'></div>

<a href="#" id="testAnchor"></a>
</code>```

JS

```<code>var tab_text;
var data_type = 'data:application/vnd.ms-excel';

function CreateHiddenTable(ListOfMessages)
{
var ColumnHead = "Column Header Text";
var TableMarkUp='<table id="myModifiedTable" class="visibilityHide"><thead><tr><td><b>'+ColumnHead+'</b></td>  </tr></thead><tbody>';

for(i=0; i<ListOfMessages.length; i++){
    TableMarkUp += '<tr><td>' + ListOfMessages[i] +'</td></tr>';
}
TableMarkUp += "</tbody></table>";
$('#MessageHolder').append(TableMarkUp);
}

function fnExcelReport() {
var Messages = "\n message1.\n message2.";
var ListOfMessages = Messages.split(".");

CreateHiddenTable(ListOfMessages);

    tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
    tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';

    tab_text = tab_text + '<x:Name>Error Messages</x:Name>';

    tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
    tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';

    tab_text = tab_text + "<table border='1px'>";
    tab_text = tab_text + $('#myModifiedTable').html();;
    tab_text = tab_text + '</table></body></html>';

    data_type = 'data:application/vnd.ms-excel';

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        if (window.navigator.msSaveBlob) {
            var blob = new Blob([tab_text], {
                type: "application/csv;charset=utf-8;"
            });
            navigator.msSaveBlob(blob, 'Test file.xls');
        }
    } else {
    console.log(data_type);
console.log(tab_text);
      $('#testAnchor')[0].click()
    }
$('#MessageHolder').html("");
}
$($("#testAnchor")[0]).click(function(){
console.log(data_type);
console.log(tab_text);
  $('#testAnchor').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
        $('#testAnchor').attr('download', 'Test file.xls');
});
</code>```

CSS

```<code>.visibilityHide
{
  visibility:hidden;
}
</code>```

Body:
This is the fiddle https://jsfiddle.net/ym4egje0/

I have two things to ask

this is creating a xls , how to create a xlsx file and it does not work in IE , only works in google chrome , how to make it work in IE ?

I want to put  ColumnHead column header text and message1 and message2 should be consecutive rows .

Have to take as the index of (.) to cut into rows  .

HTML

<input id="btnExport" type="button" value = "Generate File" />

JS/Jquery

$("#btnExport").click(function (e) {

var ColumnHead = "Column Header Text";
var Messages = "\n message1.\n message2.";
   window.open('data:application/vnd.ms-excel,' + Messages);
    e.preventDefault();

});

Body:
Check out this fiddle to solve your problem . it will create file for both Google chrome and IE

https://jsfiddle.net/shaswatatripathy/fo4ugmLp/1/

HTML

<input type="button" id="test" onClick="fnExcelReport();" value="download" />

<div id='MessageHolder'></div>

<a href="#" id="testAnchor"></a>

JS

var tab_text;
var data_type = 'data:application/vnd.ms-excel';

function CreateHiddenTable(ListOfMessages)
{
var ColumnHead = "Column Header Text";
var TableMarkUp='<table id="myModifiedTable" class="visibilityHide"><thead><tr><td><b>'+ColumnHead+'</b></td>  </tr></thead><tbody>';

for(i=0; i<ListOfMessages.length; i++){
    TableMarkUp += '<tr><td>' + ListOfMessages[i] +'</td></tr>';
}
TableMarkUp += "</tbody></table>";
$('#MessageHolder').append(TableMarkUp);
}

function fnExcelReport() {
var Messages = "\n message1.\n message2.";
var ListOfMessages = Messages.split(".");

CreateHiddenTable(ListOfMessages);

    tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
    tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';

    tab_text = tab_text + '<x:Name>Error Messages</x:Name>';

    tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
    tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';

    tab_text = tab_text + "<table border='1px'>";
    tab_text = tab_text + $('#myModifiedTable').html();;
    tab_text = tab_text + '</table></body></html>';

    data_type = 'data:application/vnd.ms-excel';

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        if (window.navigator.msSaveBlob) {
            var blob = new Blob([tab_text], {
                type: "application/csv;charset=utf-8;"
            });
            navigator.msSaveBlob(blob, 'Test file.xls');
        }
    } else {
    console.log(data_type);
console.log(tab_text);
      $('#testAnchor')[0].click()
    }
$('#MessageHolder').html("");
}
$($("#testAnchor")[0]).click(function(){
console.log(data_type);
console.log(tab_text);
  $('#testAnchor').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
        $('#testAnchor').attr('download', 'Test file.xls');
});

CSS

.visibilityHide
{
  visibility:hidden;
}


问:
How can I navigate to next form in Visual studio when I'm using metro framework for c#?
I have designed two separate forms in my software as Login form and Main form.
Anyone please suggest me a way to navigate between them.I just want to open the Main form when the user enters the correct username and password. Also

```<code>Form main = new Form();
this.Close();
main.Show();
</code>```

is not working in metro framework.

Thank you!

答:
1) If you know about DATABASE then you have to create a database for username and password put queries in forms and your next form should be opened

2) If not then use if else statements for user name and password and when conditions are true make it open

Body:
I have designed two separate forms in my software as Login form and Main form.
Anyone please suggest me a way to navigate between them.I just want to open the Main form when the user enters the correct username and password. Also

Form main = new Form();
this.Close();
main.Show();

is not working in metro framework.

Thank you!


问:
Scaling a Java based tree
I wrote a tree in Java that supports multiple children nodes and edges. I haven't had to worry about scaling this application up until now. The use case now requires that there be 100 or more instances of the tree to be searched and maintained.

I've done very minimal research in this domain. The first thing that comes to mind is Spark. How I understand it though, is that Spark batches windows of events - almost removing the "in stream" aspect. Time is very critical here.

So I was thinking of taking advantage of Hadoop's file system. Indexing the tree across the cluster and using MapReduce to do maintenance.

I don't mind a good read. If there is any articles, tutorials, and or recommendations, that would be greatly appreciated.

Cheers

答:
Hadoop and Spark are both distributed processing systems. Spark was designed to override the drawbacks of Hadoop system.

Hadoop has two parts, a storage system called hdfs and a processing algorithm called map-reduce. Spark was developed analyzing drawbacks in map-reduce. Hence RDD (resilient distributed datasets) was introduced in spark for in memory distributed processing. More information can be found in Apache Spark and Jacek

We can use the powerful hadoop filesystem with Spark processing as well.

If you choose spark, you would learn functional programming with scala or python or R. Hadoop is dependent on map-reduce algorithm which is a bit complex to be followed.

And there are apis for Tree in scala and there are works uderway too for example this and this

I hope this is helpful.

Title: Scaling a Java based tree


问:
Powershell -replace  with a special character of ">" not working
I've got a block of code that does -replace on a number of  entries in some HTML output.

The data that is read comes from a .csv, so all values coming in are string type

The entire block of code is as follows:

```<code>$Report | Select Server, WMI, SVC, UptimeDays | ConvertTo-HTML | ForEach {

$PSitem -replace "<td>Not installed</td>", "<td style='background-
color:Yellow;color=black'>Not installed</td>"`

-replace "<td>Failed</td>", "<td style='background-
color:#FF0000;color=white'>Failed</td>"`

-replace "<td>Installed/Not running</td>", "<td style='background-
color:#FF0000;color=white'>Installed/Not running</td>"`

-replace "<td>WMI timed-out</td>", "<td style='background-
color:#FF0000;color=white'>WMI timed-out</td>"`

-replace "<td>Offline</td>", "<td style='background-
color:#FF0000;color=white'>Offline</td>"`

-replace "<td>Uptime > 7 days</td>", "<td style='background-
color:Yellow;color=black'>Uptime > 7 days</td>"

} | out-String
</code>```

The -replace on all  entries, with the expected colored background/text,  but not for the " Uptime > 7 days	"

...I'm assuming it's because I've got the ">" in there. I would rather not re-format the input CSV to remove the ">". Is it just a matter of adding an escape "/" character in the right place? How would I do that with the above code?

答:
Even though you didn't answer the relevant part of my comment, I'm pretty certain that's it:

Test data:

```<code>PS D:\t> 1,2,3|select @{n='num';e={$_}},@{n='days';e={'days > 7'}}

num days
--- ----
  1 days > 7
  2 days > 7
  3 days > 7
</code>```

Converted to HTML:

```<code>PS D:\t> 1,2,3|select @{n='num';e={$_}},@{n='days';e={'days > 7'}} | ConvertTo-Html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE</title>
</head><body>
<table>
<colgroup><col/><col/></colgroup>
<tr><th>num</th><th>days</th></tr>
<tr><td>1</td><td>days > 7</td></tr>
<tr><td>2</td><td>days > 7</td></tr>
<tr><td>3</td><td>days > 7</td></tr>
</table>
</body></html>
</code>```

See the > has been replaced with the HTML entity code for the greater-than symbol, >.

So your replace will have to match "Uptime > 7 days	".

Title: Powershell -replace <td> with a special character of ">" not working

Body:
I've got a block of code that does -replace on a number of  entries in some HTML output.

The data that is read comes from a .csv, so all values coming in are string type

The entire block of code is as follows:

$Report | Select Server, WMI, SVC, UptimeDays | ConvertTo-HTML | ForEach {

$PSitem -replace "Not installed	", "Not installed	"`

-replace "Failed	", "Failed	"`

-replace "Installed/Not running	", "Installed/Not running	"`

-replace "WMI timed-out	", "WMI timed-out	"`

-replace "Offline	", "Offline	"`

-replace "Uptime > 7 days	", "Uptime > 7 days	"

} | out-String

The -replace on all  entries, with the expected colored background/text,  but not for the " Uptime > 7 days	"

...I'm assuming it's because I've got the ">" in there. I would rather not re-format the input CSV to remove the ">". Is it just a matter of adding an escape "/" character in the right place? How would I do that with the above code?

Body:
Even though you didn't answer the relevant part of my comment, I'm pretty certain that's it:

Test data:

PS D:\t> 1,2,3|select @{n='num';e={$_}},@{n='days';e={'days > 7'}}

num days
--- ----
  1 days > 7
  2 days > 7
  3 days > 7

Converted to HTML:

PS D:\t> 1,2,3|select @{n='num';e={$_}},@{n='days';e={'days > 7'}} | ConvertTo-Html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE</title>
</head><body>
<table>
<colgroup><col/><col/></colgroup>
<tr><th>num</th><th>days</th></tr>
<tr><td>1</td><td>days &gt; 7</td></tr>
<tr><td>2</td><td>days &gt; 7</td></tr>
<tr><td>3</td><td>days &gt; 7</td></tr>
</table>
</body></html>

See the > has been replaced with the HTML entity code for the greater-than symbol, &gt;.

So your replace will have to match "<td>Uptime &gt; 7 days</td>".


问:
Selectively expand associations in Spring Data Rest response
I have a standard Spring data JPA and Spring data Rest setup which, correctly, returns associations as links to the correct resources.

```<code>{
    "id": 1,
    "version": 2,
    "date": "2011-11-22",
    "description": "XPTO",
    "_links": {
        "self": {
            "href": "http://localhost:8000/api/domain/1"
        },
        "otherDomain": {
            "href": "http://localhost:8000/api/domain/1/otherDomain"
        }
    }
}
</code>```

However in some requests i would like to have the association to the "otherDomain" expanded (so the client does not have to do N+1 requests to get the full data).

Is it possible to configure Spring Data Rest to handle the response in this way?

答:
My solution applies to all requests, but some might find it relevant.

I have a simular situation, where I have the userPersons association nested in my User json response, like so:

```<code>{
"_embedded":{
  "users":[
     {
        "userName":"Albert"
        "userPersons":[
           {
              "personId":2356,
              "activeBoolean":1
           },
           {
              "personId":123617783,
              "activeBoolean":1
           }
        ],
        "_links":{
           "self":{
              "href":"http://localhost:8080/api/users/1"
           }
        }
     }
  ]
</code>```

}
}

My base entity like so:

```<code>@Entity
public class User {

...

@Getter @Setter
private String userName;

@Getter @Setter
@OneToMany(mappedBy = "user")
private Set<Userperson> userPersons;
</code>```

}

And a single repository:

```<code>@RepositoryRestResource
public interface UserRepo extends JpaRepository<User, Integer> {
}
</code>```

My solution is this:

By simply NOT exposing a Userperson @RepositoryRestResource, Spring Data Rest will embed your association.

If you define a @RepositoryRestResource for the nested type, Spring Data Rest will render a link to the resource and not embed it.

If you need the nested type repository for internal business logic, set it to @RepositoryRestResource(exported = false), to have the same behavior.

To avoid the 1+N problem, you can configure the association for eager loading, perhaps using an @EntityGraph like this guy - though I yet haven't found the best way to implement this in Spring Data Rest.

Body:
I have a standard Spring data JPA and Spring data Rest setup which, correctly, returns associations as links to the correct resources.

{
    "id": 1,
    "version": 2,
    "date": "2011-11-22",
    "description": "XPTO",
    "_links": {
        "self": {
            "href": "http://localhost:8000/api/domain/1"
        },
        "otherDomain": {
            "href": "http://localhost:8000/api/domain/1/otherDomain"
        }
    }
}

However in some requests i would like to have the association to the "otherDomain" expanded (so the client does not have to do N+1 requests to get the full data).

Is it possible to configure Spring Data Rest to handle the response in this way?

Body:
My solution applies to all requests, but some might find it relevant.

I have a simular situation, where I have the userPersons association nested in my User json response, like so:

{
"_embedded":{
  "users":[
     {
        "userName":"Albert"
        "userPersons":[
           {
              "personId":2356,
              "activeBoolean":1
           },
           {
              "personId":123617783,
              "activeBoolean":1
           }
        ],
        "_links":{
           "self":{
              "href":"http://localhost:8080/api/users/1"
           }
        }
     }
  ]

}
}

My base entity like so:

@Entity
public class User {

...

@Getter @Setter
private String userName;

@Getter @Setter
@OneToMany(mappedBy = "user")
private Set<Userperson> userPersons;

}

And a single repository:

@RepositoryRestResource
public interface UserRepo extends JpaRepository<User, Integer> {
}

My solution is this:

By simply NOT exposing a Userperson @RepositoryRestResource, Spring Data Rest will embed your association.

If you define a @RepositoryRestResource for the nested type, Spring Data Rest will render a link to the resource and not embed it.

If you need the nested type repository for internal business logic, set it to @RepositoryRestResource(exported = false), to have the same behavior.

To avoid the 1+N problem, you can configure the association for eager loading, perhaps using an @EntityGraph like this guy - though I yet haven't found the best way to implement this in Spring Data Rest.


问:
Python BeautifulSoup cannot find table ID
I am running into some trouble scraping a table using BeautifulSoup. Here is my code

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats = soup.find('table',  id = 'totals')

In [78]: print(stats)
None
</code>```

When I right click on the table to inspect the element the HTML looks as I'd expect, however when I view the source the only element with id = 'totals' is commented out. Is there a way to scrape a table from the commented source code?

I have referenced this post but can't seem to replicate their solution.

Here is a link to the webpage I am interested in. I'd like to scrape the table labeled "Totals" and store it as a data frame.

I am relatively new to Python, HTML, and web scraping. Any help would be greatly appreciated.

Thanks in advance.

Michael

答:
You can do this:

```<code>from urllib2 import *
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"lxml")

stats = soup.findAll('div', id = 'all_totals')
print stats
</code>```

Please inform me if I helped!

Body:
I am running into some trouble scraping a table using BeautifulSoup. Here is my code

from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats = soup.find('table',  id = 'totals')

In [78]: print(stats)
None

When I right click on the table to inspect the element the HTML looks as I'd expect, however when I view the source the only element with id = 'totals' is commented out. Is there a way to scrape a table from the commented source code?

I have referenced this post but can't seem to replicate their solution.

Here is a link to the webpage I am interested in. I'd like to scrape the table labeled "Totals" and store it as a data frame.

I am relatively new to Python, HTML, and web scraping. Any help would be greatly appreciated.

Thanks in advance.

Michael

Body:
You can do this:

from urllib2 import *
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"lxml")

stats = soup.findAll('div', id = 'all_totals')
print stats

Please inform me if I helped!


问:
Action is not dispatched again after the props change in React-Redux
I have the following React Component:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {loadJobTitleSkills} from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';

class SkillPage extends React.Component {

  componentDidMount() {
    if (this.props.user_positions[0]) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
  }

  render() {
    return (
      <div>
        <SkillList skills={this.props.job_title_skills} />
      </div>
    );
  }
}

SkillPage.propTypes = {
  job_title_skills: PropTypes.array.isRequired,
  user_positions: PropTypes.array.isRequired,
};

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

export default connect(mapStateToProps)(SkillPage);
</code>```

state.user_positions = {} when the component is rendered as a previous component is a form that submits state.user_positions. Right after the SkillPage component is rendered, state.user_positions is populated, which I validated in the Redux chrome extension.

The problem is this SkillPage component is not automatically re-rendering. I expect the component to automatically detect state.user_positions has changed and rerun componentDidMount, which would then dispatch loadJobTitleSkills().

What am I doing wrong here? Why isn't my component re-rendering whenever state.user_positions is modified?

userPositionReducer.js:

```<code>import * as types from '../actions/actionTypes';

const initialState = {}

export default function userPositionReducer(state = initialState, action) {
  switch (action.type) {
    case types.CREATE_USERPOSITION_SUCCESS:
      return action.user_position
    case types.LOAD_USERPOSITION_SUCCESS:
      return action.user_positions
    default:
      return state;
  }
}
</code>```

jobTitleSkillsReducer.js:

```<code>import * as types from '../actions/actionTypes';

const initialState = []

export default function jobTitleSkillsReducer(state = initialState, action) {
  switch (action.type) {
    case types.LOAD_JOBTITLESKILLS_SUCCESS:
     return action.job_title_skills
    default:
      return state;
  }
}
</code>```

Update

I was able to get it to "work" by adding the following to my SkillPage component and removing componentDidMount()

```<code>  componentDidUpdate() {
    if (this.props.user_positions[0] && this.props.job_title_skills.length === 0) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
  }
</code>```

This feels super hacky. Is there a better way to do this?

Update 2

```<code>Working with this added:

  componentWillReceiveProps(nextProps) {
    if (nextProps.user_positions && nextProps.user_positions.length > 0) {
      if (this.props.user_positions[0] !== nextProps.user_positions[0]) {
        this.props.dispatch(loadJobTitleSkills(nextProps.user_positions[0].job_title_id));
      }
    }
  }
</code>```

This solution still feels super hacky.

Update 3 - Adding Action Creators

jobTitleSkillsActions.js

```<code>import * as types from './actionTypes';
import JobTitleSkillsApi from '../api/JobTitleSkillsApi';

export function loadJobTitleSkillsSuccess(job_title_skills) {
  return {type: types.LOAD_JOBTITLESKILLS_SUCCESS, job_title_skills};
}

export function loadJobTitleSkills(job_title_id) {
  return function(dispatch) {
    return JobTitleSkillsApi.getAllJobTitleSkills(job_title_id).then(skills => {
      dispatch(loadJobTitleSkillsSuccess(skills));
    }).catch(error => {
      throw(error);
    });
  };
}
</code>```

UserPositionActions.js

```<code>import * as types from './actionTypes';
import userPositionsApi from '../api/UserPositionsApi';

export function createUserPositionSuccess(user_position) {
  return {type: types.CREATE_USERPOSITION_SUCCESS, user_position};
}

export function loadUserPositionSuccess(user_positions) {
  return {type: types.LOAD_USERPOSITION_SUCCESS, user_positions};
}

export function loadUserPositions() {
  // console.log('actions: loadUserPosition')
  return function(dispatch) {
    return userPositionsApi.getAllUserPositions().then(user_positions => {
      dispatch(loadUserPositionSuccess(user_positions));
    }).catch(error => {
      throw(error);
    });
  };
}

export function createUserPosition(user_position) {
  // console.log('actions: createUserPosition')
  return function (dispatch) {
    return userPositionsApi.createUserPosition(user_position).then(responseUserPosition => {
      dispatch(createUserPositionSuccess(responseUserPosition));
      return responseUserPosition;
    }).catch(error => {
      throw(error);
    });
  };
}
</code>```

答:
ComponentDidMount lifeCycle function is only executed once, at the time of component Mount. What you want is the componentWillReceiveProps function which too which gets executed on every prop change

Do this

```<code>componentDidMount() {
    if (this.props.user_positions[0] ) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
  }
componentWillReceiveProps(nextProps) {

     if (this.props.user_positions[0] !== nextProps.userPositions[0]) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following React Component:

import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {loadJobTitleSkills} from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';

class SkillPage extends React.Component {

  componentDidMount() {
    if (this.props.user_positions[0]) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
  }

  render() {
    return (

        <SkillList skills={this.props.job_title_skills} />

    );
  }
}

SkillPage.propTypes = {
  job_title_skills: PropTypes.array.isRequired,
  user_positions: PropTypes.array.isRequired,
};

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

export default connect(mapStateToProps)(SkillPage);

state.user_positions = {} when the component is rendered as a previous component is a form that submits state.user_positions. Right after the SkillPage component is rendered, state.user_positions is populated, which I validated in the Redux chrome extension.

The problem is this SkillPage component is not automatically re-rendering. I expect the component to automatically detect state.user_positions has changed and rerun componentDidMount, which would then dispatch loadJobTitleSkills().

What am I doing wrong here? Why isn't my component re-rendering whenever state.user_positions is modified?

userPositionReducer.js:

import * as types from '../actions/actionTypes';

const initialState = {}

export default function userPositionReducer(state = initialState, action) {
  switch (action.type) {
    case types.CREATE_USERPOSITION_SUCCESS:
      return action.user_position
    case types.LOAD_USERPOSITION_SUCCESS:
      return action.user_positions
    default:
      return state;
  }
}

jobTitleSkillsReducer.js:

import * as types from '../actions/actionTypes';

const initialState = []

export default function jobTitleSkillsReducer(state = initialState, action) {
  switch (action.type) {
    case types.LOAD_JOBTITLESKILLS_SUCCESS:
     return action.job_title_skills
    default:
      return state;
  }
}

Update

I was able to get it to "work" by adding the following to my SkillPage component and removing componentDidMount()

  componentDidUpdate() {
    if (this.props.user_positions[0] && this.props.job_title_skills.length === 0) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
  }

This feels super hacky. Is there a better way to do this?

Update 2

Working with this added:

  componentWillReceiveProps(nextProps) {
    if (nextProps.user_positions && nextProps.user_positions.length > 0) {
      if (this.props.user_positions[0] !== nextProps.user_positions[0]) {
        this.props.dispatch(loadJobTitleSkills(nextProps.user_positions[0].job_title_id));
      }
    }
  }

This solution still feels super hacky.

Update 3 - Adding Action Creators

jobTitleSkillsActions.js

import * as types from './actionTypes';
import JobTitleSkillsApi from '../api/JobTitleSkillsApi';

export function loadJobTitleSkillsSuccess(job_title_skills) {
  return {type: types.LOAD_JOBTITLESKILLS_SUCCESS, job_title_skills};
}

export function loadJobTitleSkills(job_title_id) {
  return function(dispatch) {
    return JobTitleSkillsApi.getAllJobTitleSkills(job_title_id).then(skills => {
      dispatch(loadJobTitleSkillsSuccess(skills));
    }).catch(error => {
      throw(error);
    });
  };
}

UserPositionActions.js

import * as types from './actionTypes';
import userPositionsApi from '../api/UserPositionsApi';

export function createUserPositionSuccess(user_position) {
  return {type: types.CREATE_USERPOSITION_SUCCESS, user_position};
}

export function loadUserPositionSuccess(user_positions) {
  return {type: types.LOAD_USERPOSITION_SUCCESS, user_positions};
}

export function loadUserPositions() {
  // console.log('actions: loadUserPosition')
  return function(dispatch) {
    return userPositionsApi.getAllUserPositions().then(user_positions => {
      dispatch(loadUserPositionSuccess(user_positions));
    }).catch(error => {
      throw(error);
    });
  };
}

export function createUserPosition(user_position) {
  // console.log('actions: createUserPosition')
  return function (dispatch) {
    return userPositionsApi.createUserPosition(user_position).then(responseUserPosition => {
      dispatch(createUserPositionSuccess(responseUserPosition));
      return responseUserPosition;
    }).catch(error => {
      throw(error);
    });
  };
}

Body:
ComponentDidMount lifeCycle function is only executed once, at the time of component Mount. What you want is the componentWillReceiveProps function which too which gets executed on every prop change

Do this

componentDidMount() {
    if (this.props.user_positions[0] ) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
  }
componentWillReceiveProps(nextProps) {

     if (this.props.user_positions[0] !== nextProps.userPositions[0]) {
      this.props.dispatch(loadJobTitleSkills(this.props.user_positions[0].job_title_id));
    }
}


问:
What the various ways of calling a method at runtime?
I need to call a method on an object but I do not know the method name until runtime.

What are the techniques available?

(e.g. GetMethod().Invoke(), delegates, c# 4.0 dynamic)

Thanks!

答:
You can use Reflection to call functions that you do not know the name of until run time. Here's some doc:

http://msdn.microsoft.com/en-us/library/f7ykdhsy%28VS.80%29.aspx


问:
Unexpected token import with Webpack and Babel
I added react-router v4 to my project with Webpack and NodeJS. The app compiled correctly without any error messages in the log, but the browser console gave me this:

```<code>Uncaught SyntaxError: Unexpected token import
    at Object.<anonymous> (bundle.js:3391)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:11:25)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:24:27)
    at eval (eval at <anonymous> (bundle.js:1405), <anonymous>:25:30)
    at Object.<anonymous> (bundle.js:1405)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:3379), <anonymous>:12:17)
</code>```

I think that the problem is in the Webpack configuration. This is my webpack.config.js:

```<code>var path = require('path')
var webpack = require('webpack')
var NpmInstallPlugin = require('npm-install-webpack-plugin')
var autoprefixer = require('autoprefixer');
var precss = require('precss');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    'babel-polyfill',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new NpmInstallPlugin()
  ],
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loaders: ['eslint'],
        include: [
          path.resolve(__dirname, "src"),
        ],
      }
    ],
    loaders: [
      {
        loaders: ['react-hot', 'babel-loader'],
        include: [
          path.resolve(__dirname, "src"),
        ],
        test: /\.js$/,
        plugins: ['transform-runtime'],
        presets: ['es2015','react']
      },
      {
        test:   /\.css$/,
        loader: "style-loader!css-loader!postcss-loader"
      }
    ]
  },
  postcss: function () {
    return [autoprefixer, precss];
  }
}
</code>```

Here is my package.json file:

```<code>{
  "name": "redux-ru-tutorial",
  "version": "1.0.0",
  "description": "Redux RU tutorial",
  "main": "index.js",
  "scripts": {
    "start": "node server.js"
  },
  "author": "Yuriy Shipovalov",
  "license": "MIT",
  "devDependencies": {
    "autoprefixer": "^6.3.1",
    "babel-core": "^6.4.5",
    "babel-eslint": "^4.1.6",
    "babel-loader": "^6.2.1",
    "babel-plugin-transform-runtime": "^6.4.3",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",
    "css-loader": "^0.23.1",
    "eslint": "^1.10.3",
    "eslint-loader": "^1.2.1",
    "eslint-plugin-react": "^3.16.1",
    "express": "^4.13.4",
    "npm-install-webpack-plugin": "^2.0.2",
    "postcss-loader": "^0.8.0",
    "precss": "^1.4.0",
    "react-hot-loader": "^1.3.0",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.12",
    "webpack-dev-middleware": "^1.5.1",
    "webpack-hot-middleware": "^2.6.4"
  },
  "dependencies": {
    "babel-polyfill": "^6.3.14",
    "babel-runtime": "^6.3.19",
    "cors": "^2.8.3",
    "history": "^4.6.1",
    "jquery": "^3.2.1",
    "react": "^0.14.6",
    "react-dom": "^0.14.6",
    "react-redux": "^4.0.6",
    "react-redux-router": "0.0.5",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "redux": "^3.3.1",
    "redux-logger": "2.5.2",
    "redux-thunk": "1.0.3"
  }
}
</code>```

Here is my index.js file:

```<code>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import App from './containers/App'
import './styles/app.css'
import configureStore from './store/configureStore'

const store = configureStore()
console.log(store.getState())
render(
  <Provider store={store}>
      <Router>
          <Route> path="/" component={App}></Route>
      </Router>
  </Provider>,
  document.getElementById('root')
)
</code>```

答:
Here's an example from webpack documentation:

module.rules allows you to specify several loaders within your webpack configuration. This is a concise way to display loaders, and helps to maintain clean code. It also offers you a full overview of each respective loader.

In your case, you can:

```<code>module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [
          'react-hot','babel-loader'
        ]
      }
    ]
  }
</code>```

Hope this helps.

Body:
I added react-router v4 to my project with Webpack and NodeJS. The app compiled correctly without any error messages in the log, but the browser console gave me this:

Uncaught SyntaxError: Unexpected token import
    at Object.<anonymous> (bundle.js:3391)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:11:25)
    at Object.eval (eval at <anonymous> (bundle.js:1405), <anonymous>:24:27)
    at eval (eval at <anonymous> (bundle.js:1405), <anonymous>:25:30)
    at Object.<anonymous> (bundle.js:1405)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.eval (eval at <anonymous> (bundle.js:3379), <anonymous>:12:17)

I think that the problem is in the Webpack configuration. This is my webpack.config.js:

var path = require('path')
var webpack = require('webpack')
var NpmInstallPlugin = require('npm-install-webpack-plugin')
var autoprefixer = require('autoprefixer');
var precss = require('precss');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    'babel-polyfill',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new NpmInstallPlugin()
  ],
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loaders: ['eslint'],
        include: [
          path.resolve(__dirname, "src"),
        ],
      }
    ],
    loaders: [
      {
        loaders: ['react-hot', 'babel-loader'],
        include: [
          path.resolve(__dirname, "src"),
        ],
        test: /\.js$/,
        plugins: ['transform-runtime'],
        presets: ['es2015','react']
      },
      {
        test:   /\.css$/,
        loader: "style-loader!css-loader!postcss-loader"
      }
    ]
  },
  postcss: function () {
    return [autoprefixer, precss];
  }
}

Here is my package.json file:

{
  "name": "redux-ru-tutorial",
  "version": "1.0.0",
  "description": "Redux RU tutorial",
  "main": "index.js",
  "scripts": {
    "start": "node server.js"
  },
  "author": "Yuriy Shipovalov",
  "license": "MIT",
  "devDependencies": {
    "autoprefixer": "^6.3.1",
    "babel-core": "^6.4.5",
    "babel-eslint": "^4.1.6",
    "babel-loader": "^6.2.1",
    "babel-plugin-transform-runtime": "^6.4.3",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",
    "css-loader": "^0.23.1",
    "eslint": "^1.10.3",
    "eslint-loader": "^1.2.1",
    "eslint-plugin-react": "^3.16.1",
    "express": "^4.13.4",
    "npm-install-webpack-plugin": "^2.0.2",
    "postcss-loader": "^0.8.0",
    "precss": "^1.4.0",
    "react-hot-loader": "^1.3.0",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.12",
    "webpack-dev-middleware": "^1.5.1",
    "webpack-hot-middleware": "^2.6.4"
  },
  "dependencies": {
    "babel-polyfill": "^6.3.14",
    "babel-runtime": "^6.3.19",
    "cors": "^2.8.3",
    "history": "^4.6.1",
    "jquery": "^3.2.1",
    "react": "^0.14.6",
    "react-dom": "^0.14.6",
    "react-redux": "^4.0.6",
    "react-redux-router": "0.0.5",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "redux": "^3.3.1",
    "redux-logger": "2.5.2",
    "redux-thunk": "1.0.3"
  }
}

Here is my index.js file:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import App from './containers/App'
import './styles/app.css'
import configureStore from './store/configureStore'

const store = configureStore()
console.log(store.getState())
render(
  <Provider store={store}>
      <Router>
          <Route> path="/" component={App}></Route>
      </Router>
  </Provider>,
  document.getElementById('root')
)

Body:
Here's an example from webpack documentation:

module.rules allows you to specify several loaders within your webpack configuration. This is a concise way to display loaders, and helps to maintain clean code. It also offers you a full overview of each respective loader.

In your case, you can:

module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [
          'react-hot','babel-loader'
        ]
      }
    ]
  }

Hope this helps.


问:
How to load image in android from server(Amazon S3) with Https URL?
I am beginner to android.
I am working on client side code I have to read images store on server and display it in imageview.
I have refer some stackoverflow question but not able to succeed.
I did simple plain java program with HttpsURLConnection class I got the some binary response from server for image, thats ok with plain java code.
But when I tried the same thing in android with little bit change in code, I got the Exception:

```<code>01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativeconnect(Native Method)
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:316)
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.getSecureSocket(HttpConnection.java:168)
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:399)
</code>```

This is my public URL of sample image:

https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg

The code which works fine for me in plain java is as follows:

```<code>package com.psl.dao;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

mport javax.net.ssl.HttpsURLConnection;

   public class HttpsClient{

   public static void main(String[] args)
   {
        String url = "https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg";
        try {
            new HttpsClient().print(url);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
   }

   public void print(String url)throws Exception
   {
     String httpsURL = url;
     URL myurl = new URL(httpsURL);

     System.setProperty("https.proxyHost", "puproxy.company.co.in");
     System.setProperty("https.proxyPort", "8080");

     HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
     System.out.println(con.toString());
     InputStream ins = con.getInputStream();
     InputStreamReader isr = new InputStreamReader(ins);
     BufferedReader in = new BufferedReader(isr);

     String inputLine;

     while ((inputLine = in.readLine()) != null)
     {
       System.out.println(inputLine);
     }

     in.close();
   }
}
</code>```

Then I have refer some android tutorial and tried following code in my android app:

```<code>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestSSL {

    public static void main(String[] args) throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        System.setProperty("https.proxyHost", "puproxy.company.co.in");
       System.setProperty("https.proxyPort", "8080");

        URL url = new URL("https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg");
        URLConnection con = url.openConnection();
        final Reader reader = new InputStreamReader(con.getInputStream());
        final BufferedReader br = new BufferedReader(reader);
        String line = "";
        while ((line = br.readLine()) != null) {
            Log.d("tag",line+"");
        }
        br.close();
    } // End of main
} // End of the class //
</code>```

But I got exception as above said:

```<code>01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
</code>```

Any other code that works fine with Apache HttpClient or Async HttP client library by using Asynynchronusly loading of image would welcome.
Also I dont know how to do proxy setting in android. so please do it for me with respective parameter

I have tried follwing tutorial but my image is not displayed.

http://javatechig.com/android/download-image-using-asynctask-in-android

The above tutorial works fine for Http URL but not for Https

I want code like in above tutorial that works fine for HTTPS URL For time being consider server certificate is not important for me.

答:
You can simply set dataBinding in your build.gradle to true add Glide Lib to load Images nicely

```<code>android {
   compileSdkVersion 25
   buildToolsVersion '25.0.3'

   dataBinding {
       enabled = true
   }
...
}
</code>```

And create a BindingAdapter, this will overwrite the current method(in this case
android:src="...") and load the image.

```<code>@BindingAdapter("android:src")
public static void setImageUrl(ImageView imageView, String url) {
    Context context = imageView.getContext();
    Glide.with(context).load(url).into(imageView);
}
</code>```

Now you can just simple pass an url in the xml and it will load the Image, this method can be placed anywhere in the code.

```<code><ImageView
  android:id="@+id/status_avatar"
  android:layout_width="64dp"
  android:layout_height="64dp"
  android:src="http://knightwise.com/wp-content/uploads/2014/02/android-apple-wallpaper.jpg"/>
</code>```

Body:
I am beginner to android.
I am working on client side code I have to read images store on server and display it in imageview.
I have refer some stackoverflow question but not able to succeed.
I did simple plain java program with HttpsURLConnection class I got the some binary response from server for image, thats ok with plain java code.
But when I tried the same thing in android with little bit change in code, I got the Exception:

01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativeconnect(Native Method)
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:316)
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.getSecureSocket(HttpConnection.java:168)
01-29 18:39:28.249: WARN/System.err(2045):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:399)

This is my public URL of sample image:

https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg

The code which works fine for me in plain java is as follows:

package com.psl.dao;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

mport javax.net.ssl.HttpsURLConnection;

   public class HttpsClient{

   public static void main(String[] args)
   {
        String url = "https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg";
        try {
            new HttpsClient().print(url);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
   }

   public void print(String url)throws Exception
   {
     String httpsURL = url;
     URL myurl = new URL(httpsURL);

     System.setProperty("https.proxyHost", "puproxy.company.co.in");
     System.setProperty("https.proxyPort", "8080");

     HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
     System.out.println(con.toString());
     InputStream ins = con.getInputStream();
     InputStreamReader isr = new InputStreamReader(ins);
     BufferedReader in = new BufferedReader(isr);

     String inputLine;

     while ((inputLine = in.readLine()) != null)
     {
       System.out.println(inputLine);
     }

     in.close();
   }
}

Then I have refer some android tutorial and tried following code in my android app:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestSSL {

    public static void main(String[] args) throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        System.setProperty("https.proxyHost", "puproxy.company.co.in");
       System.setProperty("https.proxyPort", "8080");

        URL url = new URL("https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg");
        URLConnection con = url.openConnection();
        final Reader reader = new InputStreamReader(con.getInputStream());
        final BufferedReader br = new BufferedReader(reader);
        String line = "";
        while ((line = br.readLine()) != null) {
            Log.d("tag",line+"");
        }
        br.close();
    } // End of main
} // End of the class //

But I got exception as above said:

01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0

Any other code that works fine with Apache HttpClient or Async HttP client library by using Asynynchronusly loading of image would welcome.
Also I dont know how to do proxy setting in android. so please do it for me with respective parameter

I have tried follwing tutorial but my image is not displayed.

http://javatechig.com/android/download-image-using-asynctask-in-android

The above tutorial works fine for Http URL but not for Https

I want code like in above tutorial that works fine for HTTPS URL For time being consider server certificate is not important for me.

Body:
You can simply set dataBinding in your build.gradle to true add Glide Lib to load Images nicely

android {
   compileSdkVersion 25
   buildToolsVersion '25.0.3'

   dataBinding {
       enabled = true
   }
...
}

And create a BindingAdapter, this will overwrite the current method(in this case
android:src="...") and load the image.

@BindingAdapter("android:src")
public static void setImageUrl(ImageView imageView, String url) {
    Context context = imageView.getContext();
    Glide.with(context).load(url).into(imageView);
}

Now you can just simple pass an url in the xml and it will load the Image, this method can be placed anywhere in the code.

<ImageView
  android:id="@+id/status_avatar"
  android:layout_width="64dp"
  android:layout_height="64dp"
  android:src="http://knightwise.com/wp-content/uploads/2014/02/android-apple-wallpaper.jpg"/>


问:
Delete or not create a file for each entry in webpack
Hi I have a webpack config with these entry points:

```<code>  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor':    './src/vendor.ts',
    'app':       './src/app.ts',
    'css': './src/css/main.unique.scss',
    'index': './src/index.unique.html',
  },
</code>```

My webpack is creating a [name].bundle.js and a [name].map for each entry.

It makes sense for the first 3 javascript entries but the CSS and the INDEX entries are just for processing my main CSS file and my main html file which get treated later by the ExtractTextPlugin

So after a build I'm stuck with some garbage like css.bundle.js and css.map which only contains:

```<code>webpackJsonp([1],[
/* 0 */
/***/ function(module, exports) {

    // removed by extract-text-webpack-plugin

/***/ }
]);
//# sourceMappingURL=css.map
</code>```

How can I tell webpack to NOT build files for some entries? (like css/index)

Or alternatively to delete those useless files after the compile?

Thanks in advance

答:
I put together a webpack plugin to remove extra files based on their output size, rather than basing it on their name - it's been a little more future proof for me as I continue to add extra entry points to my webpack config.

Install using npm or yarn

```<code>npm install webpack-extraneous-file-cleanup-plugin --save-dev
yarn add webpack-extraneous-file-cleanup-plugin --dev
</code>```

In your webpack.config.js file:

```<code>const ExtraneousFileCleanupPlugin = require('webpack-extraneous-file-cleanup-plugin');

module.exports = {
  ...
  plugins: [
    new ExtraneousFileCleanupPlugin({
      extensions: ['.js']
    })
  ]
}
</code>```

You can see the full list of options on the Webpack Extraneous File Cleanup Plugin Github Page

Body:
Hi I have a webpack config with these entry points:

  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor':    './src/vendor.ts',
    'app':       './src/app.ts',
    'css': './src/css/main.unique.scss',
    'index': './src/index.unique.html',
  },

My webpack is creating a [name].bundle.js and a [name].map for each entry.

It makes sense for the first 3 javascript entries but the CSS and the INDEX entries are just for processing my main CSS file and my main html file which get treated later by the ExtractTextPlugin

So after a build I'm stuck with some garbage like css.bundle.js and css.map which only contains:

webpackJsonp([1],[
/* 0 */
/***/ function(module, exports) {

    // removed by extract-text-webpack-plugin

/***/ }
]);
//# sourceMappingURL=css.map

How can I tell webpack to NOT build files for some entries? (like css/index)

Or alternatively to delete those useless files after the compile?

Thanks in advance

Body:
I put together a webpack plugin to remove extra files based on their output size, rather than basing it on their name - it's been a little more future proof for me as I continue to add extra entry points to my webpack config.

Install using npm or yarn

npm install webpack-extraneous-file-cleanup-plugin --save-dev
yarn add webpack-extraneous-file-cleanup-plugin --dev

In your webpack.config.js file:

const ExtraneousFileCleanupPlugin = require('webpack-extraneous-file-cleanup-plugin');

module.exports = {
  ...
  plugins: [
    new ExtraneousFileCleanupPlugin({
      extensions: ['.js']
    })
  ]
}

You can see the full list of options on the Webpack Extraneous File Cleanup Plugin Github Page


问:
How to get C++-template-like behavior but only allow two specific types to be instantiated?
I'm trying to get a specific type of behavior from an inline C++ function, and I'm not sure if there's a way to do it or not.

I want my function to accept either a signed or an unsigned 16-bit value as an argument, perform an operation on that value, and then return a value of that same type.  If the argument's signed/unsigned-ness is ambiguous (e.g. because it's a constant), then it's okay for the compiler to just pick the signed version.  Here's a toy program showing my first attempt at getting that behavior:

```<code> #include <iostream>
 #include <cstdint>

  int16_t getValuePlusOne( int16_t x) {return x+1;}
 uint16_t getValuePlusOne(uint16_t x) {return x+1;}

 using namespace std;

 int main(int, char **)
 {
     int16_t   signedVal = -15;
    uint16_t unsignedVal = 23;

    cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
    cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
    cout << getValuePlusOne(1234)        << endl;  // COMPILE ERROR, ambiguous!  D'oh!
    return 0;
 }
</code>```

So that almost worked, but it errors out on the getValuePlusOne(1234) since 1234 is ambiguous (it could be signed or unsigned).  Fair enough, but I'd like it not to do that.

So here's my second attempt:

```<code>#include <iostream>
#include <cstdint>

template <typename T> T getValuePlusOne(T val) {return val+1;}

using namespace std;

int main(int, char **)
{
    int16_t   signedVal = 5;
   uint16_t unsignedVal = 5;

   cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
   cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
   cout << getValuePlusOne(1234)        << endl;  // works, yay!

   uint32_t inappropriateType32 = 54321;
   cout << getValuePlusOne(inappropriateType32) << endl;  // works, but I want this to be a compile-time error!  D'oh!

   float inappropriateTypeFloat = 666.0;
   cout << getValuePlusOne(inappropriateTypeFloat) << endl;  // works, but I want this to be a compile-time error!

   return 0;
}
</code>```

This version works just how I want it to work for the first three calls to getValuePlusOne() -- they compile without errors and the template mechanism makes sure that getValuePlusOne()'s return type matches its argument type, and chooses a default argument/return type in the ambiguous case.  Yay!

But -- this version also allows the user to pass in inappropriate values (e.g. 32-bit integers, or even -- gasp -- floating point types) which don't make sense in the context of my application, so I want the compiler to flag those calls as compile-time errors, and that doesn't happen with this implementation.

Is there any way for me to have my cake and eat it too?

答:
My approach would be to make a templated function and split it into header and cpp file. This way you have to provide the allowed types, otherwise you'll get a compilation error:

main.cpp:

```<code>#include <iostream>
#include "GetValuePlusOne.h"

int main() {
    int i = 2;
    std::cout << GetValuePlusOne(i) << std::endl;

    return 0;
}
</code>```

GetValuePlusOne.h:

```<code>#pragma once

template <typename T>
T GetValuePlusOne(T value);
</code>```

GetValuePlusOne.cpp:

```<code>#include <cstdint>

template <typename T>
T GetValuePlusOne(T value) {
    return value + 1;
}

template int GetValuePlusOne<int>(int);
template int16_t  GetValuePlusOne<int16_t>(int16_t );
template uint16_t   GetValuePlusOne<uint16_t >(uint16_t  );
</code>```

As Igor already pointed out you need an "int" template to compile your "1234" example. Hope this works, couldn't test it.

Body:
I'm trying to get a specific type of behavior from an inline C++ function, and I'm not sure if there's a way to do it or not.

I want my function to accept either a signed or an unsigned 16-bit value as an argument, perform an operation on that value, and then return a value of that same type.  If the argument's signed/unsigned-ness is ambiguous (e.g. because it's a constant), then it's okay for the compiler to just pick the signed version.  Here's a toy program showing my first attempt at getting that behavior:

 #include <iostream>
 #include <cstdint>

  int16_t getValuePlusOne( int16_t x) {return x+1;}
 uint16_t getValuePlusOne(uint16_t x) {return x+1;}

 using namespace std;

 int main(int, char **)
 {
     int16_t   signedVal = -15;
    uint16_t unsignedVal = 23;

    cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
    cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
    cout << getValuePlusOne(1234)        << endl;  // COMPILE ERROR, ambiguous!  D'oh!
    return 0;
 }

So that almost worked, but it errors out on the getValuePlusOne(1234) since 1234 is ambiguous (it could be signed or unsigned).  Fair enough, but I'd like it not to do that.

So here's my second attempt:

#include <iostream>
#include <cstdint>

template <typename T> T getValuePlusOne(T val) {return val+1;}

using namespace std;

int main(int, char **)
{
    int16_t   signedVal = 5;
   uint16_t unsignedVal = 5;

   cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
   cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
   cout << getValuePlusOne(1234)        << endl;  // works, yay!

   uint32_t inappropriateType32 = 54321;
   cout << getValuePlusOne(inappropriateType32) << endl;  // works, but I want this to be a compile-time error!  D'oh!

   float inappropriateTypeFloat = 666.0;
   cout << getValuePlusOne(inappropriateTypeFloat) << endl;  // works, but I want this to be a compile-time error!

   return 0;
}

This version works just how I want it to work for the first three calls to getValuePlusOne() -- they compile without errors and the template mechanism makes sure that getValuePlusOne()'s return type matches its argument type, and chooses a default argument/return type in the ambiguous case.  Yay!

But -- this version also allows the user to pass in inappropriate values (e.g. 32-bit integers, or even -- gasp -- floating point types) which don't make sense in the context of my application, so I want the compiler to flag those calls as compile-time errors, and that doesn't happen with this implementation.

Is there any way for me to have my cake and eat it too?

Body:
My approach would be to make a templated function and split it into header and cpp file. This way you have to provide the allowed types, otherwise you'll get a compilation error:

main.cpp:

#include <iostream>
#include "GetValuePlusOne.h"

int main() {
    int i = 2;
    std::cout << GetValuePlusOne(i) << std::endl;

    return 0;
}

GetValuePlusOne.h:

#pragma once

template <typename T>
T GetValuePlusOne(T value);

GetValuePlusOne.cpp:

#include <cstdint>

template <typename T>
T GetValuePlusOne(T value) {
    return value + 1;
}

template int GetValuePlusOne<int>(int);
template int16_t  GetValuePlusOne<int16_t>(int16_t );
template uint16_t   GetValuePlusOne<uint16_t >(uint16_t  );

As Igor already pointed out you need an "int" template to compile your "1234" example. Hope this works, couldn't test it.


问:
Android How to check .apk are using Multidex?
I got an "old" .apk build from colleague, and I wanted to check whether it support Multidex or not. But I don't have the old projects files, is it possible to check it only from the .apk?</p>

答: Rename this "old.apk" to "old.zip", and unzip it, if there is only one "classes.dex", it doesn't support multidex, and if there are "classes.dex"、"classes2.dex"...it support multidex</p>


问:
How to launch a Uikit notification from AngularJS controller
I want launch a uikit notification after login in my system or when I fail in the login by password or user incorrect. I think that I can to do it using AngularJS. In my project when I try login, first my data are send to a controller that send this data a django view.

login.html

```<code>  <div class="input" ng-controller="conIngreso">

    {% csrf_token %}

    <div class="login-input-group spacer-field">
      <span class="login-input-group-addon">
        <i class="fa fa-at fa-fw"></i>
      </span>
      <input type="email" class="form-control" name="email" placeholder="Correo electrónico" ng-model="email">
    </div>
    <div class="login-input-group">
      <span class="login-input-group-addon">
        <i class="fa fa-key fa-fw"></i>
      </span>
      <input type="password" class="form-control" name="password" placeholder="Contraseña" ng-model="password">
    </div>

    <button class="btn btn-default btn-lg submit" type="submit" ng-click="ingresar(email, password)">Ingresar</button>
  </div>
</code>```

conIngreso.js

```<code>var app = angular.module('appLogin');

app.controller('conIngreso', ['$scope', '$http', function($scope, $http){
$scope.user={email:'',password:''}

$scope.ingresar=function(email,password){
    $http({method:'POST',
        url:'/cliente/ingreso/',
        data:$.param({email: email, password: password})
    }).then(
        function(response2){
            //UIkit.notification("...", {pos: 'top-right'});
            window.location.href='javascript:history.back()';
        },function(response2){
            $scope.user = response2.data || 'Request failed';
        }
    );
}
}])
</code>```

In the conIngreso.js file above I try to do it before window.location...

But does not work

Thanks

答:
its </p>

```<code>UIkit.notify
</code>```

<p>and you are using </p>

```<code>UIkit.notification
</code>```

Body:
I want launch a uikit notification after login in my system or when I fail in the login by password or user incorrect. I think that I can to do it using AngularJS. In my project when I try login, first my data are send to a controller that send this data a django view.

login.html

    {% csrf_token %}

      <input type="email" class="form-control" name="email" placeholder="Correo electrónico" ng-model="email">

      <input type="password" class="form-control" name="password" placeholder="Contraseña" ng-model="password">

    <button class="btn btn-default btn-lg submit" type="submit" ng-click="ingresar(email, password)">Ingresar</button>

conIngreso.js

var app = angular.module('appLogin');

app.controller('conIngreso', ['$scope', '$http', function($scope, $http){
$scope.user={email:'',password:''}

$scope.ingresar=function(email,password){
    $http({method:'POST',
        url:'/cliente/ingreso/',
        data:$.param({email: email, password: password})
    }).then(
        function(response2){
            //UIkit.notification("...", {pos: 'top-right'});
            window.location.href='javascript:history.back()';
        },function(response2){
            $scope.user = response2.data || 'Request failed';
        }
    );
}
}])

In the conIngreso.js file above I try to do it before window.location...

But does not work

Thanks

Body:
its

UIkit.notify

and you are using

UIkit.notification


问:
Android Development: pass information and fail
I got 2 classes in my project. The first class(main) have a listview and this is the onclick():

```<code>@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        // Get the item that was clicked
        Object o = this.getListAdapter().getItem(position);
        String keyword = o.toString();
        class2 sec = new Class2();

        Intent intent = new Intent(this, Class2.class);
        startActivity(intent) ;
        if (keyword == "hello"){
            sec.setInfo(keyword);
        }

    }
</code>```

so and then in my other class which have a defferent layout.xml. The code is:

```<code>public class det extends Activity {
    static WebView map;
    public TextView header;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details);

}
    public void setInfo(String mystring){
        header = (TextView) findViewById(R.id.text01);
        header.setText(mystring);
        //Toast.makeText(this, map, Toast.LENGTH_LONG).show();
        //return;
    }
</code>```

Ye, i keep getting force close on my android phone. The App i meant to change the header text to text that ive tapped on the listview. But when i click a item it pop up a window with FC.

ive try to comment away the:

```<code>header = (TextView) findViewById(R.id.text01);
        header.setText(mystring);
</code>```

and it worked without a FC however the headertext is stil null.

Thank you!
Your Friend!

答:
First of all, you need to post the stack trace for us to have any idea how to help.

Second, I'm assuming Class2 extends Activity or else Intent intent = new Intent(this, Class2.class); doesn't make any sense. That being the case, class2 sec = new Class2(); is ALWAYS wrong. You never ever call new on a class that extends Activity.

You can't call methods on another activity like that. Your only real option is to send the keyword in the intent by using putExtra, and then getting retrieving it in Class2

Body:
I got 2 classes in my project. The first class(main) have a listview and this is the onclick():

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        // Get the item that was clicked
        Object o = this.getListAdapter().getItem(position);
        String keyword = o.toString();
        class2 sec = new Class2();

        Intent intent = new Intent(this, Class2.class);
        startActivity(intent) ;
        if (keyword == "hello"){
            sec.setInfo(keyword);
        }

    }

so and then in my other class which have a defferent layout.xml. The code is:

public class det extends Activity {
    static WebView map;
    public TextView header;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details);

}
    public void setInfo(String mystring){
        header = (TextView) findViewById(R.id.text01);
        header.setText(mystring);
        //Toast.makeText(this, map, Toast.LENGTH_LONG).show();
        //return;
    }

Ye, i keep getting force close on my android phone. The App i meant to change the header text to text that ive tapped on the listview. But when i click a item it pop up a window with FC.

ive try to comment away the:

header = (TextView) findViewById(R.id.text01);
        header.setText(mystring);

and it worked without a FC however the headertext is stil null.

Thank you!
Your Friend!