问:
Microsoft graph API: empty BCC field
Scenario:

Jenny and Tom have gmail accounts. Jerry is o365 user

Jenny sends email to Tom (in TO: field) and BCC: Jerry.

When Jerry gets message from graph api and doesn't see himself in BCC entry, which is empty (in both versions of API - 1 and beta).

If Jenny, Jerry and Tom would be in the group and Jenny have sent email to group, it would exactly the same for Jerry. There is no way to distinguish those two cases.

I would expect that when user is in BCC he should see himself there.
I know if sender is O365 user and getsMessage via graph API he will see all BCC users.

Is there any API call that I could use to learn that given user was in BCC of given message?

Here is what Jerry sees:

```<code>   {
        "@odata.etag": "W/\"CQAAABYAAACWhXAbJxpFRb0V3o8I2vIPAACwRstA\"",
        "id": "AAMkAGMyNDE4NGI5LTRlNmItNDUzMy04ZTBlLTgxNjM3MDZhODE5NgBGAAAAAABT6x1NTxG_S7bw4uHJw-_tBwDEbTtXm_E6Rr8LT_x2xj5KAAAAnJfJAACWhXAbJxpFRb0V3o8I2vIPAACwGG_qAAA=",
        "createdDateTime": "2017-11-15T19:50:57Z",
        "lastModifiedDateTime": "2017-11-15T19:50:57Z",
        "changeKey": "CQAAABYAAACWhXAbJxpFRb0V3o8I2vIPAACwRstA",
        "categories": [],
        "receivedDateTime": "2017-11-15T19:50:57Z",
        "sentDateTime": "2017-11-15T19:50:54Z",
        "hasAttachments": false,
        "internetMessageId": "<CAHF5u5KsOQd43c4dtnx0uTQRor_dt7Y1uy=F3G4i6-c+TdUgug@mail.gmail.com>",
        "subject": "test bcc=",
        "bodyPreview": "test bcc",
        "importance": "normal",
        "parentFolderId": "AAMkAGMyE4NGI5LTRlNmItNDUzMy04ZTBlLTgxNjM3MDZhODE5NgAuAAAAAABT6x1NTxG_S7bw4uHJw-_tAQDEbTtXm_E6Rr8LT_x2xj5KAAAAnJfJAAA=",
        "conversationId": "AAQkAGMyGI5LTRlNmItNDUzMy04ZTBlLTgxNjM3MDZhODE5NgAQAMaAYzrmsyxGq7ZujLh23q0=",
        "conversationIndex": "AQHTXxoBjOuazLEartm6MuHberQ==",
        "isDeliveryReceiptRequested": null,
        "isReadReceiptRequested": false,
        "isRead": false,
        "isDraft": false,
        "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkAGMyNDE4NAACwGG%2BqAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
        "inferenceClassification": "focused",
        "unsubscribeData": [],
        "unsubscribeEnabled": false,
        "body": {
            "contentType": "html",
            "content": "<html>\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n<meta content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>\r\n<div dir=\"ltr\">test bcc<br>\r\n</div>\r\n</body>\r\n</html>\r\n"
        },
        "sender": {
            "emailAddress": {
                "name": "Jenny",
                "address": "jenny1234@gmail.com"
            }
        },
        "from": {
            "emailAddress": {
                "name": "Jenny",
                "address": "jenny1234@gmail.com"
            }
        },
        "toRecipients": [
            {
                "emailAddress": {
                    "name": "Tom",
                    "address": "tom1234@gmail.com"
                }
            }
        ],
        "ccRecipients": [],
        "bccRecipients": [],
        "replyTo": [],
        "mentionsPreview": null,
        "flag": {
            "flagStatus": "notFlagged"
        }
    },
</code>```

答:
For any messages that comes from an external source (in this case GMail), there is no BCC data available.

This works this way in order to meet the requirements set forth for "Blind Carbon Copy" in RFC 2822.

Title: Microsoft graph API: empty BCC field

Body:
Scenario:

Jenny and Tom have gmail accounts. Jerry is o365 user

Jenny sends email to Tom (in TO: field) and BCC: Jerry.

When Jerry gets message from graph api and doesn't see himself in BCC entry, which is empty (in both versions of API - 1 and beta).

If Jenny, Jerry and Tom would be in the group and Jenny have sent email to group, it would exactly the same for Jerry. There is no way to distinguish those two cases.

I would expect that when user is in BCC he should see himself there.
I know if sender is O365 user and getsMessage via graph API he will see all BCC users.

Is there any API call that I could use to learn that given user was in BCC of given message?

Here is what Jerry sees:

   {
        "@odata.etag": "W/\"CQAAABYAAACWhXAbJxpFRb0V3o8I2vIPAACwRstA\"",
        "id": "AAMkAGMyNDE4NGI5LTRlNmItNDUzMy04ZTBlLTgxNjM3MDZhODE5NgBGAAAAAABT6x1NTxG_S7bw4uHJw-_tBwDEbTtXm_E6Rr8LT_x2xj5KAAAAnJfJAACWhXAbJxpFRb0V3o8I2vIPAACwGG_qAAA=",
        "createdDateTime": "2017-11-15T19:50:57Z",
        "lastModifiedDateTime": "2017-11-15T19:50:57Z",
        "changeKey": "CQAAABYAAACWhXAbJxpFRb0V3o8I2vIPAACwRstA",
        "categories": [],
        "receivedDateTime": "2017-11-15T19:50:57Z",
        "sentDateTime": "2017-11-15T19:50:54Z",
        "hasAttachments": false,
        "internetMessageId": "<CAHF5u5KsOQd43c4dtnx0uTQRor_dt7Y1uy=F3G4i6-c+TdUgug@mail.gmail.com>",
        "subject": "test bcc=",
        "bodyPreview": "test bcc",
        "importance": "normal",
        "parentFolderId": "AAMkAGMyE4NGI5LTRlNmItNDUzMy04ZTBlLTgxNjM3MDZhODE5NgAuAAAAAABT6x1NTxG_S7bw4uHJw-_tAQDEbTtXm_E6Rr8LT_x2xj5KAAAAnJfJAAA=",
        "conversationId": "AAQkAGMyGI5LTRlNmItNDUzMy04ZTBlLTgxNjM3MDZhODE5NgAQAMaAYzrmsyxGq7ZujLh23q0=",
        "conversationIndex": "AQHTXxoBjOuazLEartm6MuHberQ==",
        "isDeliveryReceiptRequested": null,
        "isReadReceiptRequested": false,
        "isRead": false,
        "isDraft": false,
        "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkAGMyNDE4NAACwGG%2BqAAA%3D&exvsurl=1&viewmodel=ReadMessageItem",
        "inferenceClassification": "focused",
        "unsubscribeData": [],
        "unsubscribeEnabled": false,
        "body": {
            "contentType": "html",
            "content": "\r\n\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n<meta content=\"text/html; charset=utf-8\">\r\n\r\n\r\n
test bcc
\r\n
\r\n\r\n\r\n"
        },
        "sender": {
            "emailAddress": {
                "name": "Jenny",
                "address": "jenny1234@gmail.com"
            }
        },
        "from": {
            "emailAddress": {
                "name": "Jenny",
                "address": "jenny1234@gmail.com"
            }
        },
        "toRecipients": [
            {
                "emailAddress": {
                    "name": "Tom",
                    "address": "tom1234@gmail.com"
                }
            }
        ],
        "ccRecipients": [],
        "bccRecipients": [],
        "replyTo": [],
        "mentionsPreview": null,
        "flag": {
            "flagStatus": "notFlagged"
        }
    },


来源: stackexchange

问:
Mysql "UPDATE" isn't doing anything
This is my code for the update:

```<code>$key = $skills[$ind];
echo "\t\t<td>" . $key . "</td>\n";

//explode using a comma as a delimiter
$data_n = explode(",", $word);
$score[$key][”Rank”] = $data_n[0];
$score[$key][”Level”] = $data_n[1];
$score[$key][”Exp”] = $data_n[2];

echo "\t\t<td>" .$data_n[0] . "</td>\n";
echo "\t\t<td>" .$data_n[1] . "</td>\n";
echo "\t\t<td>" .$data_n[2] . "</td>\n";

$result = mysql_query("UPDATE accounts SET $key ='$data_n[1]' WHERE username = '$user'")
          or
          die(mysql_error());
</code>```

Basically, there's a string "key" that is the name of the thing I'm trying to update, but it's just not updating. I've changed "mysql_query" to "print" and it prints out exactly what it's supposed to:

```<code>UPDATE accounts SET Total ='1144' WHERE username = 'derekboy'
</code>```

There aren't any errors. printing out $result shows that it's "True" that it sent the message to MySQL. Can anyone see the problem, because I've been looking for a whole day and still nothing.

All of my code is located here; thanks. You can see that I connect to a database at the very top of the script.

答:
I don't know PHP particularly well, but it seems that you are surrounding the variables with single quotes, in which variables aren't interpolated.

Try something like:

```<code>$result = mysql_query("UPDATE accounts SET " . $key . " ='" . $data_n[1] . "' WHERE username = '". $user" . "'") or die(mysql_error());
</code>```

ContentLicense: CC BY-SA 2.5

Title: Mysql "UPDATE" isn't doing anything

Body:
This is my code for the update:

$key = $skills[$ind];
echo "\t\t" . $key . "	\n";

//explode using a comma as a delimiter
$data_n = explode(",", $word);
$score[$key][”Rank”] = $data_n[0];
$score[$key][”Level”] = $data_n[1];
$score[$key][”Exp”] = $data_n[2];

echo "\t\t" .$data_n[0] . "	\n";
echo "\t\t" .$data_n[1] . "	\n";
echo "\t\t" .$data_n[2] . "	\n";

$result = mysql_query("UPDATE accounts SET $key ='$data_n[1]' WHERE username = '$user'")
          or
          die(mysql_error());

Basically, there's a string "key" that is the name of the thing I'm trying to update, but it's just not updating. I've changed "mysql_query" to "print" and it prints out exactly what it's supposed to:

UPDATE accounts SET Total ='1144' WHERE username = 'derekboy'

There aren't any errors. printing out $result shows that it's "True" that it sent the message to MySQL. Can anyone see the problem, because I've been looking for a whole day and still nothing.

All of my code is located here; thanks. You can see that I connect to a database at the very top of the script.

Body:
I don't know PHP particularly well, but it seems that you are surrounding the variables with single quotes, in which variables aren't interpolated.

Try something like:

$result = mysql_query("UPDATE accounts SET " . $key . " ='" . $data_n[1] . "' WHERE username = '". $user" . "'") or die(mysql_error());


问:
Pass parameter to callback node.js
I'm developing a RESTful application in Node.js and I'm implementing the http requests using the https library.

At the moment, each file contains an http request with certain parameters as you can see in the code below:

```<code>//test.js

var https = require('https');

module.exports.httpResponse = function (callback) {

    var options = {
      host: 'api.github.com',
      path: '/users/Guilherme-Routar',
      method: 'GET',
      //headers: {'user-agent': userAgent}
    }

    var str = '';

    var request = https.request(options, function (response) {

        response.on('data', function (body) {
            str += body;
        });

        response.on('end', function () {
            return callback(str);
        });
    });

    request.on('error', (e) => {
        console.log(e);
    });

    request.end();
}
</code>```

Now I want to encapsulate the http request itself in a separated file (for refactoring purposes) so that each file will call the template and pass it's own parameters to it. But here's where the issue lies. Is it possible to pass parameters to a callback?

```<code>//test.js
var https = require('https');

//I tried adding 'options' next to the 'callback' parameter
module.exports.httpResponse = function (callback, options) {

    var str = '';
    var request = https.request(options, function (response) {

        response.on('data', function (body) {
            str += body;
        });
        response.on('end', function () {
            return callback(str);
        });
    });
    request.on('error', (e) => {
        console.log(e);
    });
    request.end();
}
</code>```

On another file I'd define and pass the parameters of the function

```<code>//user.js

var test = require('../test.js');

var options = {
  host: 'api.github.com',
  path: '/users/Guilherme-Routar',
  method: 'GET',
  //headers: {'user-agent': userAgent}
}

// Passing 'options' as a parameter
test.httpResponse(function(response, options) {
  console.log('response = ' + response);
})
</code>```

But this clearly doesn't work. Any suggestions you can give me? Thanks in advance.

答:
It seems that you want to pass the options as an additional argument after the callback, not expect it to be passed within the callback.

Instead of:

```<code>test.httpResponse(function(response, options) {
  //                                 ^ you don't want option to be part of the callback
  console.log('response = ' + response);
})
</code>```

You want:

```<code>test.httpResponse(function(response) {
  console.log('response = ' + response);
}, options)
// ^ pass options as second parameter
</code>```

As Bergi mentioned below, the usual convention in Node is to pass the callback as the last parameter (as you can see in the https.request method you're using), which would require you to flip the arguments of your httpResponse method:

```<code>module.exports.httpResponse = function (options, callback) {
// ...                                  ^^^^^^^^^^^^^^^^^ flip these two so that callback is at the end
}
</code>```

Then use it:

```<code>test.httpResponse(options, function(response) {
//                ^ pass options as first parameter
  console.log('response = ' + response);
})
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pass parameter to callback node.js

Body:
I'm developing a RESTful application in Node.js and I'm implementing the http requests using the https library.

At the moment, each file contains an http request with certain parameters as you can see in the code below:

//test.js

var https = require('https');

module.exports.httpResponse = function (callback) {

    var options = {
      host: 'api.github.com',
      path: '/users/Guilherme-Routar',
      method: 'GET',
      //headers: {'user-agent': userAgent}
    }

    var str = '';

    var request = https.request(options, function (response) {

        response.on('data', function (body) {
            str += body;
        });

        response.on('end', function () {
            return callback(str);
        });
    });

    request.on('error', (e) => {
        console.log(e);
    });

    request.end();
}

Now I want to encapsulate the http request itself in a separated file (for refactoring purposes) so that each file will call the template and pass it's own parameters to it. But here's where the issue lies. Is it possible to pass parameters to a callback?

//test.js
var https = require('https');

//I tried adding 'options' next to the 'callback' parameter
module.exports.httpResponse = function (callback, options) {

    var str = '';
    var request = https.request(options, function (response) {

        response.on('data', function (body) {
            str += body;
        });
        response.on('end', function () {
            return callback(str);
        });
    });
    request.on('error', (e) => {
        console.log(e);
    });
    request.end();
}

On another file I'd define and pass the parameters of the function

//user.js

var test = require('../test.js');

var options = {
  host: 'api.github.com',
  path: '/users/Guilherme-Routar',
  method: 'GET',
  //headers: {'user-agent': userAgent}
}

// Passing 'options' as a parameter
test.httpResponse(function(response, options) {
  console.log('response = ' + response);
})

But this clearly doesn't work. Any suggestions you can give me? Thanks in advance.

Body:
It seems that you want to pass the options as an additional argument after the callback, not expect it to be passed within the callback.

Instead of:

test.httpResponse(function(response, options) {
  //                                 ^ you don't want option to be part of the callback
  console.log('response = ' + response);
})

You want:

test.httpResponse(function(response) {
  console.log('response = ' + response);
}, options)
// ^ pass options as second parameter

As Bergi mentioned below, the usual convention in Node is to pass the callback as the last parameter (as you can see in the https.request method you're using), which would require you to flip the arguments of your httpResponse method:

module.exports.httpResponse = function (options, callback) {
// ...                                  ^^^^^^^^^^^^^^^^^ flip these two so that callback is at the end
}

Then use it:

test.httpResponse(options, function(response) {
//                ^ pass options as first parameter
  console.log('response = ' + response);
})


问:
How do I put all of my user input from a for loop into an array (or variable)
I'm having trouble with my code :( I am trying to get the answer from my for loop and put it in an array(or variable). This is my code

```<code>Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

String szFavouriteSubjects = null;
int iSubject;

System.out.print("How many of your GCSE subjects do you enjoy? ");
iSubject = iKeyboard.nextInt();

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    szFavouriteSubjects = szKeyboard.nextLine();
}

System.out.println(szFavouriteSubjects);
</code>```

This is the output

How many of your GCSE subjects do you enjoy? 4

Enter subject 1: English

Enter subject 2: Maths

Enter subject 3: French

Enter subject 4: German

German

答:
Put the results in a list:</p>

```<code>Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

List<String> results = new ArrayList<>();
int iSubject;

System.out.print("How many of your GCSE subjects do you enjoy? ");
iSubject = iKeyboard.nextInt();

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    results.add(szKeyboard.nextLine());
}

System.out.println(results);
</code>```

Body:
I'm having trouble with my code :( I am trying to get the answer from my for loop and put it in an array(or variable). This is my code

Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

String szFavouriteSubjects = null;
int iSubject;

System.out.print("How many of your GCSE subjects do you enjoy? ");
iSubject = iKeyboard.nextInt();

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    szFavouriteSubjects = szKeyboard.nextLine();
}

System.out.println(szFavouriteSubjects);

This is the output

How many of your GCSE subjects do you enjoy? 4

Enter subject 1: English

Enter subject 2: Maths

Enter subject 3: French

Enter subject 4: German

German

Body:
Put the results in a list:

Scanner szKeyboard = new Scanner(System.in);
Scanner iKeyboard = new Scanner(System.in);

List<String> results = new ArrayList<>();
int iSubject;

System.out.print("How many of your GCSE subjects do you enjoy? ");
iSubject = iKeyboard.nextInt();

for(int i=1; i<=iSubject; i++)
{
    System.out.print("Enter subject " + i + ": ");
    results.add(szKeyboard.nextLine());
}

System.out.println(results);


问:
Attribute consists of other attributes, MySQL
I want to implement the attribute "name". this attribute consists of the 2 other attributes "firstname" and "lastname".

my code:

```<code>firstname VARCHAR (30),
lastname VARCHAR (30),
name VARCHAR (firstname, lastname)
</code>```

but i get the error that the syntax is not correct. so what is the right way to do it?

答:
MySQL doesn't automatically allow you to have a column that contains data from other columns (why duplicate data?). If this is what you want, I would suggest that you setup a view. Your base table would just contain the firstname and lastname, and then your view would return the firstname/lastname combination.

However, that's fairly redundant. I don't know what purpose you have for wanting a merged "name" column, but you could just return that directly with a select statement that uses the concat function.

```<code>select
    name = concat(firstname, " ", lastname),
    firstname, lastname
from
    my_table
</code>```

Body:
I want to implement the attribute "name". this attribute consists of the 2 other attributes "firstname" and "lastname".

my code:

firstname VARCHAR (30),
lastname VARCHAR (30),
name VARCHAR (firstname, lastname)

but i get the error that the syntax is not correct. so what is the right way to do it?

Body:
MySQL doesn't automatically allow you to have a column that contains data from other columns (why duplicate data?). If this is what you want, I would suggest that you setup a view. Your base table would just contain the firstname and lastname, and then your view would return the firstname/lastname combination.

However, that's fairly redundant. I don't know what purpose you have for wanting a merged "name" column, but you could just return that directly with a select statement that uses the concat function.

select
    name = concat(firstname, " ", lastname),
    firstname, lastname
from
    my_table


问:
Minikube unable to expose service with yaml
Trying to run a local registry. I have the following configuration:

Deployment:

```<code>apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: registry
  labels:
    app: registry
    role: registry
spec:
  replicas: 1
  selector:
    matchLabels:
      app: registry
  template:
    metadata:
      labels:
        app: registry
    spec:
      containers:
      - name: registry
        image: registry:latest
        ports:
        - containerPort: 5000
        volumeMounts:
          - mountPath: '/registry'
            name: registry-volume
      volumes:
      - name: registry-volume
        hostPath:
          path: '/data'
          type: Directory
</code>```

Service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: registry
  namespace: default
  labels:
    app: registry
spec:
  selector:
    role: registry
  type: NodePort
  ports:
    - name: registry
      nodePort: 31001
      port: 5000
      protocol: TCP
</code>```

It all works well when I create deployment/service. kubectl shows status as Running for both service and deployment:

```<code>NAME              DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deploy/registry   1         1         1            1           30m

NAME                     DESIRED   CURRENT   READY     AGE
rs/registry-6549cbc974   1         1         1         30m

NAME              DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deploy/registry   1         1         1            1           30m

NAME                     DESIRED   CURRENT   READY     AGE
rs/registry-6549cbc974   1         1         1         30m

NAME                           READY     STATUS    RESTARTS   AGE
po/registry-6549cbc974-mmqpj   1/1       Running   0          30m

NAME             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
svc/kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP          37m
svc/registry     NodePort    10.0.0.6     <none>        5000:31001/TCP   7m
</code>```

However, when I try to get external IP for service using: minikube service registry --url, it times-out/fails: Waiting, endpoint for service is not ready yet....

When I delete the service (keeping deployment intact), and manually expose the deployment using kubectl expose deployment registry --type=NodePort, I am able to get it working.

Minikube log can be found here.

答:
You need to specify the correct spec.selector in registry service manifest:

```<code>apiVersion: v1
kind: Service
metadata:
  name: registry
  namespace: default
  labels:
    app: registry
spec:
  selector:
    app: registry
  type: NodePort
  ports:
    - name: registry
      nodePort: 31001
      port: 5000
      protocol: TCP
</code>```

Now registry service correctly points to the registry pod:

```<code>$ kubectl get endpoints
NAME         ENDPOINTS         AGE
kubernetes   10.0.2.15:8443    14m
registry     172.17.0.4:5000   4s
</code>```

And you can get external url as well:

```<code>$ minikube service registry --url
http://192.168.99.106:31001
</code>```

Body:
Trying to run a local registry. I have the following configuration:

Deployment:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: registry
  labels:
    app: registry
    role: registry
spec:
  replicas: 1
  selector:
    matchLabels:
      app: registry
  template:
    metadata:
      labels:
        app: registry
    spec:
      containers:
      - name: registry
        image: registry:latest
        ports:
        - containerPort: 5000
        volumeMounts:
          - mountPath: '/registry'
            name: registry-volume
      volumes:
      - name: registry-volume
        hostPath:
          path: '/data'
          type: Directory

Service:

apiVersion: v1
kind: Service
metadata:
  name: registry
  namespace: default
  labels:
    app: registry
spec:
  selector:
    role: registry
  type: NodePort
  ports:
    - name: registry
      nodePort: 31001
      port: 5000
      protocol: TCP

It all works well when I create deployment/service. kubectl shows status as Running for both service and deployment:

NAME              DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deploy/registry   1         1         1            1           30m

NAME                     DESIRED   CURRENT   READY     AGE
rs/registry-6549cbc974   1         1         1         30m

NAME              DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deploy/registry   1         1         1            1           30m

NAME                     DESIRED   CURRENT   READY     AGE
rs/registry-6549cbc974   1         1         1         30m

NAME                           READY     STATUS    RESTARTS   AGE
po/registry-6549cbc974-mmqpj   1/1       Running   0          30m

NAME             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
svc/kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP          37m
svc/registry     NodePort    10.0.0.6     <none>        5000:31001/TCP   7m

However, when I try to get external IP for service using: minikube service registry --url, it times-out/fails: Waiting, endpoint for service is not ready yet....

When I delete the service (keeping deployment intact), and manually expose the deployment using kubectl expose deployment registry --type=NodePort, I am able to get it working.

Minikube log can be found here.

Body:
You need to specify the correct spec.selector in registry service manifest:

apiVersion: v1
kind: Service
metadata:
  name: registry
  namespace: default
  labels:
    app: registry
spec:
  selector:
    app: registry
  type: NodePort
  ports:
    - name: registry
      nodePort: 31001
      port: 5000
      protocol: TCP

Now registry service correctly points to the registry pod:

$ kubectl get endpoints
NAME         ENDPOINTS         AGE
kubernetes   10.0.2.15:8443    14m
registry     172.17.0.4:5000   4s

And you can get external url as well:

$ minikube service registry --url
http://192.168.99.106:31001


问:
Best way to get vertices of a mesh three.js
I am new to Three.js so perhaps I am not going abut this optimally,

I have geometry which I create as follows,

```<code>const geo = new THREE.PlaneBufferGeometry(10,0);
</code>```

I then apply a rotation to it

```<code>geo.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI * 0.5 ) );
</code>```

then I create a Mesh from it

```<code>const open = new THREE.Mesh( geo, materialNormal);
</code>```

I then apply a bunch of operations to the mesh to position it correctly, as follows:

```<code>open.position.copy(v2(10,20);
open.position.z = 0.5*10

open.position.x -= 20
open.position.y -= 10
open.rotation.z = angle;
</code>```

Now what is the best way to get the vertices of the mesh both before and after it's position is changed? I was surpised to discover that the vertices of a mesh are not in-built into three.js.

Any hints and code samples would be greatly appreciated.

答:
I think you're getting tripped-up by some semantics regarding three.js objects.

1) A Mesh does not have vertices. A Mesh contains references to Geometry/BufferGeometry, and Material(s). The vertices are contained in the Mesh's geometry property/object.

2) You're using PlaneBufferGeometry, which means an implementation of a BufferGeometry object. BufferGeometry keeps its vertices in the position attribute (mesh.geometry.attributes.position). Keep in mind that the vertex order may be affected by the index property (mesh.geometry.index).

Now to your question, the geometric origin is also its parent Mesh's origin, so your "before mesh transformation" vertex positions are exactly the same as when you created the mesh. Just read them out as-is.

To get the "after mesh transformation" vertex positions, you'll need to take each vertex, and convert it from the Mesh's local space, into world space. Luckily, three.js has a convenient function to do this:

```<code>var tempVertex = new THREE.Vector3();
// set tempVertex based on information from mesh.geometry.attributes.position

mesh.localToWorld(tempVertex);
// tempVertex is converted from local coordinates into world coordinates,
// which is its "after mesh transformation" position
</code>```

Body:
I am new to Three.js so perhaps I am not going abut this optimally,

I have geometry which I create as follows,

const geo = new THREE.PlaneBufferGeometry(10,0);

I then apply a rotation to it

geo.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI * 0.5 ) );

then I create a Mesh from it

const open = new THREE.Mesh( geo, materialNormal);

I then apply a bunch of operations to the mesh to position it correctly, as follows:

open.position.copy(v2(10,20);
open.position.z = 0.5*10

open.position.x -= 20
open.position.y -= 10
open.rotation.z = angle;

Now what is the best way to get the vertices of the mesh both before and after it's position is changed? I was surpised to discover that the vertices of a mesh are not in-built into three.js.

Any hints and code samples would be greatly appreciated.

Body:
I think you're getting tripped-up by some semantics regarding three.js objects.

1) A Mesh does not have vertices. A Mesh contains references to Geometry/BufferGeometry, and Material(s). The vertices are contained in the Mesh's geometry property/object.

2) You're using PlaneBufferGeometry, which means an implementation of a BufferGeometry object. BufferGeometry keeps its vertices in the position attribute (mesh.geometry.attributes.position). Keep in mind that the vertex order may be affected by the index property (mesh.geometry.index).

Now to your question, the geometric origin is also its parent Mesh's origin, so your "before mesh transformation" vertex positions are exactly the same as when you created the mesh. Just read them out as-is.

To get the "after mesh transformation" vertex positions, you'll need to take each vertex, and convert it from the Mesh's local space, into world space. Luckily, three.js has a convenient function to do this:

var tempVertex = new THREE.Vector3();
// set tempVertex based on information from mesh.geometry.attributes.position

mesh.localToWorld(tempVertex);
// tempVertex is converted from local coordinates into world coordinates,
// which is its "after mesh transformation" position


问:
Exposing Inline function vs declared function in service AngularJS
I'm having trouble understanding why the follow code doesn't work.

index.html

```<code><html>
<head lang="en">
    <script src="../Scripts/angular.js"></script>
    <script src="app/books/BooksController.js"></script>
    <script src="app/services/dataService.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="BooksController as vm">
        <h3>All Books</h3>

        <div>
            <ul>
                <li ng-repeat="book in vm.allBooks">
                    {{ book.title }} - {{ book.author }}
                </li>
            </ul>
        </div>
    </div>

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

BookController.js

```<code>(function() {

  var app = angular.module('app', []);

  var BooksController = function(dataService) {
    var vm = this;

    vm.allBooks = dataService.getAllBooks;

  }

  app.controller('BooksController', ["dataService", BooksController]);
})();
</code>```

dataService.js

```<code>(function() {

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

  var dataService = function() {

    return {
      getAllBooks: getAllBooks
    };

    var getAllBooks = function() {
      return [{
          book_id: 1,
          title: "Harry Pptter and the Deathly Hallows",
          author: "J.K. Rowling",
          year_published: 2000
        },
        {
          book_id: 2,
          title: "The Cat in the Hat",
          author: "Dr. Seuss",
          year_published: 1957
        },
        {
          book_id: 3,
          title: "Encyclopedia Brown, Boy Detective",
          author: "Donald J. Sobol",
          year_published: 1963
        }
      ];
    };
  }

  app.factory('dataService', dataService);
})();
</code>```

The problem seems to be when I expose the methods through the service using:

```<code>return {
    getAllBooks: getAllBooks
};
</code>```

If I change the declaration of the function getAllBooks to look like this,

```<code>function getAllBooks() {
    ...
}
</code>```

and call the service in my controller as:

```<code>vm.allBooks = dataService.getAllBooks()
</code>```

It'll work fine.

My question is, why doesn't it work for declare functions and putting them in variables? Is it because the function is only defined, but not actually executed?

答:
Another way to get around the hoisting issue is to write your factory this way. Create an object within the factory then attach each method to it and then just return the object and your method(s) will be available in your controller.</p>

```<code>(function() {

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

var dataService = function() {

var factory = {};

factory.getAllBooks = function() {
  return [];
};

return factory;
}

app.factory('dataService', dataService);
})();
</code>```

Body:
I'm having trouble understanding why the follow code doesn't work.

index.html

All Books

                    {{ book.title }} - {{ book.author }}

BookController.js

(function() {

  var app = angular.module('app', []);

  var BooksController = function(dataService) {
    var vm = this;

    vm.allBooks = dataService.getAllBooks;

  }

  app.controller('BooksController', ["dataService", BooksController]);
})();

dataService.js

(function() {

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

  var dataService = function() {

    return {
      getAllBooks: getAllBooks
    };

    var getAllBooks = function() {
      return [{
          book_id: 1,
          title: "Harry Pptter and the Deathly Hallows",
          author: "J.K. Rowling",
          year_published: 2000
        },
        {
          book_id: 2,
          title: "The Cat in the Hat",
          author: "Dr. Seuss",
          year_published: 1957
        },
        {
          book_id: 3,
          title: "Encyclopedia Brown, Boy Detective",
          author: "Donald J. Sobol",
          year_published: 1963
        }
      ];
    };
  }

  app.factory('dataService', dataService);
})();

The problem seems to be when I expose the methods through the service using:

return {
    getAllBooks: getAllBooks
};

If I change the declaration of the function getAllBooks to look like this,

function getAllBooks() {
    ...
}

and call the service in my controller as:

vm.allBooks = dataService.getAllBooks()

It'll work fine.

My question is, why doesn't it work for declare functions and putting them in variables? Is it because the function is only defined, but not actually executed?

Body:
Another way to get around the hoisting issue is to write your factory this way. Create an object within the factory then attach each method to it and then just return the object and your method(s) will be available in your controller.

(function() {

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

var dataService = function() {

var factory = {};

factory.getAllBooks = function() {
  return [];
};

return factory;
}

app.factory('dataService', dataService);
})();


问:
Google sheets: Get column headers when data is present
I'm trying to get column headers based on a filter in table and if the data returns a 1. For example:

```<code>     ColA ColB ColC  ColD  ColE
Row1           Stat1 Stat2 Stat3
Row2 Bob  Hat  0     0     1
Row3 Bob  Glv  1     1     0
</code>```

So if I have the Filter function:

```<code>=FILTER(C2:E3, A2:A="Bob", B2:B="Glv")
</code>```

I'd like the return ArrayFormula to be {Stat1, Stat2} (or {Stat3} if the second condition is "Hat").

Can anyone point me in the right direction?
Thanks.

答:
Use the formula as the logical expression for an IF nested in ArrayFormula using an empty parameter for the value if false:

=ArrayFormula(IF(FILTER(C2:E3, A2:A3="Bob", B2:B3="Hat"),C1:E1,))

The above will return {Stat1,Stat2,}

To remove the empty members of the result array use JOIN and SPLIT:

=ArrayFormula(SPLIT(JOIN(",", IF(FILTER(C2:E3, A2:A3="Bob", B2:B3="Hat"), C1:E1,)), ",", FALSE))

Body:
I'm trying to get column headers based on a filter in table and if the data returns a 1. For example:

     ColA ColB ColC  ColD  ColE
Row1           Stat1 Stat2 Stat3
Row2 Bob  Hat  0     0     1
Row3 Bob  Glv  1     1     0

So if I have the Filter function:

=FILTER(C2:E3, A2:A="Bob", B2:B="Glv")

I'd like the return ArrayFormula to be {Stat1, Stat2} (or {Stat3} if the second condition is "Hat").

Can anyone point me in the right direction?
Thanks.


问:
Setting JVM arguments at runtime
I keep getting the following error when I run my program:

java.lang.OutOfMemoryError : Java heap space

I tried fixing this by adding -Xms512M -Xmx1524M to both Program arguments and VM arguments (I use eclipse), but this doesn't seem to prevent the error.

If the solution is adding more memory in eclipse run configuration, the question is > is this going to be exported too? or is it just for me, how can I make sure this doesn't happen on other computers?

Current code

```<code> private static void checkSumGen() throws IOException NoSuchAlgorithmException
    {

    File plFolder = new File(".\\Plugins");
    File[] listOfFiles = plFolder.listFiles();
    List<String> listClone = new ArrayList<String>();
    for (int i = 0; i < listOfFiles.length; i++)
        {
            File file = listOfFiles[i];
            String fileloc = file.getAbsolutePath();
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            FileInputStream fis = new FileInputStream(fileloc);

            byte[] dataBytes = new byte[1024];

            int nread = 0;
            while ((nread = fis.read(dataBytes)) != -1)
            {
                md.update(dataBytes, 0, nread);
            } ;
            byte[] mdbytes = md.digest();

            // convert the byte to hex format method 1
            StringBuffer sb = new StringBuffer();
            for (int i1 = 0; i1 < mdbytes.length; i++)
                {
                    sb.append(Integer.toString((mdbytes[i1] & 0xff) + 0x100, 16).substring(1));
                }

            System.out.println("Hex format : " + sb.toString());

            // convert the byte to hex format method 2
            StringBuffer hexString = new StringBuffer();
            for (int i2 = 0; i2 < mdbytes.length; i++)
                {
                    hexString.append(Integer.toHexString(0xFF & mdbytes[i2]));
                }
            System.out.println("Hex format : " + hexString.toString());
        }

}
</code>```

答:
You have an infinite loop in your code that causes the OutOfMemoryError.

In:

```<code>for (int i1 = 0; i1 < mdbytes.length; i++)
</code>```

you increment i instead of i1 causing i1 < mdbytes.length to be true forever.

Title: Setting JVM arguments at runtime

Body:
I keep getting the following error when I run my program:

java.lang.OutOfMemoryError : Java heap space

I tried fixing this by adding -Xms512M -Xmx1524M to both Program arguments and VM arguments (I use eclipse), but this doesn't seem to prevent the error.

If the solution is adding more memory in eclipse run configuration, the question is > is this going to be exported too? or is it just for me, how can I make sure this doesn't happen on other computers?

Current code

 private static void checkSumGen() throws IOException NoSuchAlgorithmException
    {

    File plFolder = new File(".\\Plugins");
    File[] listOfFiles = plFolder.listFiles();
    List<String> listClone = new ArrayList<String>();
    for (int i = 0; i < listOfFiles.length; i++)
        {
            File file = listOfFiles[i];
            String fileloc = file.getAbsolutePath();
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            FileInputStream fis = new FileInputStream(fileloc);

            byte[] dataBytes = new byte[1024];

            int nread = 0;
            while ((nread = fis.read(dataBytes)) != -1)
            {
                md.update(dataBytes, 0, nread);
            } ;
            byte[] mdbytes = md.digest();

            // convert the byte to hex format method 1
            StringBuffer sb = new StringBuffer();
            for (int i1 = 0; i1 < mdbytes.length; i++)
                {
                    sb.append(Integer.toString((mdbytes[i1] & 0xff) + 0x100, 16).substring(1));
                }

            System.out.println("Hex format : " + sb.toString());

            // convert the byte to hex format method 2
            StringBuffer hexString = new StringBuffer();
            for (int i2 = 0; i2 < mdbytes.length; i++)
                {
                    hexString.append(Integer.toHexString(0xFF & mdbytes[i2]));
                }
            System.out.println("Hex format : " + hexString.toString());
        }

}

Body:
You have an infinite loop in your code that causes the OutOfMemoryError.

In:

for (int i1 = 0; i1 < mdbytes.length; i++)

you increment i instead of i1 causing i1 < mdbytes.length to be true forever.


问:
Automatically insert user prompt in DOS/System via Matlab
In Matlab, using the dos() (or system()) command it is possible to run command line scripts via Matlab itself.

Let's say I have a script called, dummy.exe, which does not need any input parameters; that is, nothing like

dummy.exe -flag1 arg1 -flag2 arg2 ...

Rather, during its execution, it prompts the user for some variables.

It is possible to automatically feed user prompts?

答:
This might be the solution you are looking for:</p>

```<code>tmp = tempname();

fid = fopen(tmp,'wt');
fprintf(fid,'%s\n',answer_1);
fprintf(fid,'%s\n',answer_2);
fprintf(fid,'%s\n',answer_3);
fclose(fid);

system(sprintf('"%s" < "%s"','dummy.exe',tmp));

delete(tmp);
</code>```

Body:
This might be the solution you are looking for:

tmp = tempname();

fid = fopen(tmp,'wt');
fprintf(fid,'%s\n',answer_1);
fprintf(fid,'%s\n',answer_2);
fprintf(fid,'%s\n',answer_3);
fclose(fid);

system(sprintf('"%s" < "%s"','dummy.exe',tmp));

delete(tmp);


问:
Javascript function to return PHP get_file_contents
I am stumped here, have asked this a few different ways. What I need to do is return the contents of a text file in PHP on click of an a tag.  I thought it would be easy enough to just have the click and ID of the anchor tag in the JS and put the PHP method in the template like so. $textPath is var that points to the file in the settings. It goes to a help section and the text file authenticates the user. So the UL ends up being www.blahblah.com/help

```<code>  <li><a id="help" target="_blank"><? echo file_get_contents($textPath);?> </a></li>

  //Simple JS (part of another 'open' function for the menu)

   $('#help').attr("href", "/help")
</code>```

But it's still not working at all. Any ideas? Thanks

答:
Highlighting a part of your code here:

```<code><a id="help" target="_blank"><? echo file_get_contents($textPath);?> </a>
</code>```

See you are using the shorthand echo tag. The opening tag should be <?= insead of <?. And since this is a shorthand echo tag, you don't need to use the echo construct.

This shall work fine:

```<code><a id="help" target="_blank"><?=file_get_contents($textPath);?> </a>
</code>```

Quoting from the PHP Manual

echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.

```<code>I have <?=$foo?> foo.
</code>```

Coming to the question, you want to return the contents of the file. Your best bet will be achieving this via AJAX.

You can output as you wish. The best way will be to make a separate php file for handling all the ajax calls and return the output as plain text. To authenticate the user, just include the auth.php file(assuming that you are using one) in the ajax.php page.

ajax.php

```<code><php
//Below code checks if a GET request is sent
if (isset($_GET['path'])) {
echo file_get_contents($textPath);
}
?>
</code>```

jQuery

```<code>$('#help').click(function(e) {
  e.preventDefault(); // Prevents the default action
  // Send an AJAX request
  $.get("ajax.php?path", function(s) {
    //s is the responsetext. It contains the response from the server
    your code here
  });
});
</code>```

Body:
I am stumped here, have asked this a few different ways. What I need to do is return the contents of a text file in PHP on click of an a tag.  I thought it would be easy enough to just have the click and ID of the anchor tag in the JS and put the PHP method in the template like so. $textPath is var that points to the file in the settings. It goes to a help section and the text file authenticates the user. So the UL ends up being www.blahblah.com/help

<? echo file_get_contents($textPath);?>

  //Simple JS (part of another 'open' function for the menu)

   $('#help').attr("href", "/help")

But it's still not working at all. Any ideas? Thanks

Body:
Highlighting a part of your code here:

<a id="help" target="_blank"><? echo file_get_contents($textPath);?> </a>

See you are using the shorthand echo tag. The opening tag should be <?= insead of <?. And since this is a shorthand echo tag, you don't need to use the echo construct.

This shall work fine:

<a id="help" target="_blank"><?=file_get_contents($textPath);?> </a>

Quoting from the PHP Manual

echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.

I have <?=$foo?> foo.

Coming to the question, you want to return the contents of the file. Your best bet will be achieving this via AJAX.

You can output as you wish. The best way will be to make a separate php file for handling all the ajax calls and return the output as plain text. To authenticate the user, just include the auth.php file(assuming that you are using one) in the ajax.php page.

ajax.php

<php
//Below code checks if a GET request is sent
if (isset($_GET['path'])) {
echo file_get_contents($textPath);
}
?>

jQuery

$('#help').click(function(e) {
  e.preventDefault(); // Prevents the default action
  // Send an AJAX request
  $.get("ajax.php?path", function(s) {
    //s is the responsetext. It contains the response from the server
    your code here
  });
});


问:
Confused, how do I use a key and sign a document Symmetrically?
Im trying to work out how to do the below in c#.

Posted a couple of times about this seems very confusing. I have an xml document I want to be able to sign the document symmetrically and create a signature at the end.

First:

The signature needs to be created using

1) the data in the document
2) a unique key (a word or byte array that we create)

And then I need to write a program which will spit out a signature that we can ship with the document using the data and key above.

Second:

At the other end the custumer will run the program which has the unique key in it (the key in step 2) above), it will look at the signature that we shipped. And it will then be able to tell if the data was signed using that key. If the data has changed then the test will fail. This way we know the customer has not tampered with the xml file.

NOTE: I undestand that this isnt very secure but is enough for now for us.

How is this done? just cant seem to get the basics of encryption :-)

答:
For "pretty good" security, I would recommend HMAC-SHA1 with a key that is at least 160 bits (20 bytes) long. For learning about more advanced cryptography, I highly recommend the classic Schneier book, Applied Cryptography.

To generate the HMAC, you can use the handy HMACSHA1 class.

For example:

```<code>/// Pass in the xml text to sign, along with a hex or Base64-encoded, 160-bit secret key
public string GenerateSignature(string xml, string secretKey)
{
  using (HMACSHA1 encoder = new HMACSHA1(secretKey.ToAscii(), true))
  {
    return encoder.ComputeHash(xml.ToUtf8()).ToBase64();
  }
}
</code>```

...using these extension methods:

```<code>public static byte[] ToUtf8(this string str)
{
  return Encoding.UTF8.GetBytes(str);
}

public static byte[] ToAscii(this string str)
{
  return Encoding.ASCII.GetBytes(str);
}

public static string ToBase64(this byte[] bytes)
{
  return Convert.ToBase64String(bytes);
}
</code>```

To generate the secret key, you can go to random.org (not completely secure, but may be adequate for your needs), or do it programmatically like so:

```<code>System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
byte[] key = new byte[20];

rng.GetBytes(key);
string secretKey = key.ToBase64()
</code>```

Here are some more extension methods you might find handy:

```<code>public static string ToHex(this byte[] bytes)
{
  char[] c = new char[bytes.Length * 2];

  byte b;

  for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
  {
    b = ((byte)(bytes[bx] >> 4));
    c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);

    b = ((byte)(bytes[bx] & 0x0F));
    c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
  }

  return new string(c);
}

public static byte[] HexToBytes(this string str)
{
  if (str.Length == 0 || str.Length % 2 != 0)
    return new byte[0];

  byte[] buffer = new byte[str.Length / 2];
  char c;
  for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
  {
    // Convert first half of byte
    c = str[sx];
    buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);

    // Convert second half of byte
    c = str[++sx];
    buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
  }

  return buffer;
}
</code>```

Body:
For "pretty good" security, I would recommend HMAC-SHA1 with a key that is at least 160 bits (20 bytes) long. For learning about more advanced cryptography, I highly recommend the classic Schneier book, Applied Cryptography.

To generate the HMAC, you can use the handy HMACSHA1 class.

For example:

/// Pass in the xml text to sign, along with a hex or Base64-encoded, 160-bit secret key
public string GenerateSignature(string xml, string secretKey)
{
  using (HMACSHA1 encoder = new HMACSHA1(secretKey.ToAscii(), true))
  {
    return encoder.ComputeHash(xml.ToUtf8()).ToBase64();
  }
}

...using these extension methods:

public static byte[] ToUtf8(this string str)
{
  return Encoding.UTF8.GetBytes(str);
}

public static byte[] ToAscii(this string str)
{
  return Encoding.ASCII.GetBytes(str);
}

public static string ToBase64(this byte[] bytes)
{
  return Convert.ToBase64String(bytes);
}

To generate the secret key, you can go to random.org (not completely secure, but may be adequate for your needs), or do it programmatically like so:

System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
byte[] key = new byte[20];

rng.GetBytes(key);
string secretKey = key.ToBase64()

Here are some more extension methods you might find handy:

public static string ToHex(this byte[] bytes)
{
  char[] c = new char[bytes.Length * 2];

  byte b;

  for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
  {
    b = ((byte)(bytes[bx] >> 4));
    c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);

    b = ((byte)(bytes[bx] & 0x0F));
    c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
  }

  return new string(c);
}

public static byte[] HexToBytes(this string str)
{
  if (str.Length == 0 || str.Length % 2 != 0)
    return new byte[0];

  byte[] buffer = new byte[str.Length / 2];
  char c;
  for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
  {
    // Convert first half of byte
    c = str[sx];
    buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);

    // Convert second half of byte
    c = str[++sx];
    buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
  }

  return buffer;
}


问:
Passing client files to webassembly from the front-end
I'm looking to pass user-submitted data to a c++ function which I've compiled to wasm. The data is a file which the user submits on the front end via an input tag, like so:

```<code><input type="file" onChange={this.handleFile.bind(this)} />
</code>```

The onChange callback currently looks like this:

```<code>handleFile(e){
    const file = e.currentTarget.files[0];
    const reader = new FileReader();
    reader.onloadend = evt => {
        window.Module.readFile(evt.target.result);
    }
    reader.readAsArrayBuffer(file);
}
</code>```

Finally, the .cpp file containing the readFile function looks like this:

```<code>void readFile(const std::string & rawString){
  std::vector<uint8_t> data(rawString.begin(), rawString.end());
  //...
}

EMSCRIPTEN_BINDINGS(my_module) {
  emscripten::function("readFile", &readFile);
}
</code>```

I've spend my afternoon reading various docs so I'm aware that I'm supposed to allocate memory for these files on the heap and then pass a ptr from js to readFile instead of passing all of the data. My problem is that I just don't really understand how all of that is supposed to work. Could someone explain?

答:
This is a partial answer. It's superior to what I originally did and I feel like it might be closer to what the creators intended. However, I'm still creating more than one copy of the file. Credit to this post for making it click for me.

This is now my handleFile callback, commented with things I learned.

```<code>handleFile(e){

    const file = e.currentTarget.files[0];
    if(!(file instanceof Blob)) return;
    const reader = new FileReader();
    reader.onloadend = evt => {

        //evt.target.result is an ArrayBuffer. In js,
        //you can't do anything with an ArrayBuffer
        //so we have to ???cast??? it to an Uint8Array
        const uint8_t_arr = new Uint8Array(evt.target.result);

        //Right now, we have the file as a unit8array in javascript memory.
        //As far as I understand, wasm can't directly access javascript memory.
        //Which is why we need to allocate special wasm memory and then
        //copy the file from javascript memory into wasm memory so our wasm functions
        //can work on it.

        //First we need to allocate the wasm memory.
        //_malloc returns the address of the new wasm memory as int32.
        //This call is probably similar to
        //uint8_t * ptr = new uint8_t[sizeof(uint8_t_arr)/sizeof(uint8_t_arr[0])]
        const uint8_t_ptr = window.Module._malloc(uint8_t_arr.length);

        //Now that we have a block of memory we can copy the file data into that block
        //This is probably similar to
        //std::memcpy(uint8_t_ptr, uint8_t_arr, sizeof(uint8_t_arr)/sizeof(uint8_t_arr[0]))
        window.Module.HEAPU8.set(uint8_t_arr, uint8_t_ptr);

        //The only thing that's now left to do is pass
        //the address of the wasm memory we just allocated
        //to our function as well as the size of our memory.
        window.Module.readFile(uint8_t_ptr, uint8_t_arr.length);

        //At this point we're forced to wait until wasm is done with the memory.
        //Your site will now freeze if the memory you're working on is big.
        //Maybe we can somehow let our wasm function run on a seperate thread and pass a callback?

        //Retreiving our (modified) memory is also straight forward.
        //First we get some javascript memory and then we copy the
        //relevant chunk of the wasm memory into our javascript object.
        const returnArr = new Uint8Array(uint8_t_arr.length);
        //If returnArr is std::vector<uint8_t>, then is probably similar to
        //returnArr.assign(ptr, ptr + dataSize)
        returnArr.set(window.Module.HEAPU8.subarray(uint8_t_ptr, uint8_t_ptr + uint8_t_arr.length));

        //Lastly, according to the docs, we should call ._free here.
        //Do we need to call the gc somehow?
        window.Module._free(uint8_t_ptr);

    }
    reader.readAsArrayBuffer(file);
}
</code>```

Here is readFile.cpp.

```<code>#include <emscripten/bind.h>

//We get out pointer as a plain int from javascript
void readFile(const int & addr, const size_t & len){
  //We use a reinterpret_cast to turn our plain int into a uint8_t pointer. After
  //which we can play with the data just like we would normally.
  uint8_t * data = reinterpret_cast<uint8_t *>(addr);
  for(size_t i = 0; i < len; ++i){
    data[i] += 1;
  }
}

//Using this command to compile
//  emcc --bind -O3 readFile.cpp -s WASM=1 -s TOTAL_MEMORY=268435456 -o api.js --std=c++11
//Note that you need to make sure that there's enough memory available to begin with.
//I got only 16mb without passing the TOTAL_MEMORY setting.
EMSCRIPTEN_BINDINGS(my_module) {
  emscripten::function("readFile", &readFile);
}
</code>```

Body:
I'm looking to pass user-submitted data to a c++ function which I've compiled to wasm. The data is a file which the user submits on the front end via an input tag, like so:

<input type="file" onChange={this.handleFile.bind(this)} />

The onChange callback currently looks like this:

handleFile(e){
    const file = e.currentTarget.files[0];
    const reader = new FileReader();
    reader.onloadend = evt => {
        window.Module.readFile(evt.target.result);
    }
    reader.readAsArrayBuffer(file);
}

Finally, the .cpp file containing the readFile function looks like this:

void readFile(const std::string & rawString){
  std::vector<uint8_t> data(rawString.begin(), rawString.end());
  //...
}

EMSCRIPTEN_BINDINGS(my_module) {
  emscripten::function("readFile", &readFile);
}

I've spend my afternoon reading various docs so I'm aware that I'm supposed to allocate memory for these files on the heap and then pass a ptr from js to readFile instead of passing all of the data. My problem is that I just don't really understand how all of that is supposed to work. Could someone explain?

Body:
This is a partial answer. It's superior to what I originally did and I feel like it might be closer to what the creators intended. However, I'm still creating more than one copy of the file. Credit to this post for making it click for me.

This is now my handleFile callback, commented with things I learned.

handleFile(e){

    const file = e.currentTarget.files[0];
    if(!(file instanceof Blob)) return;
    const reader = new FileReader();
    reader.onloadend = evt => {

        //evt.target.result is an ArrayBuffer. In js,
        //you can't do anything with an ArrayBuffer
        //so we have to ???cast??? it to an Uint8Array
        const uint8_t_arr = new Uint8Array(evt.target.result);

        //Right now, we have the file as a unit8array in javascript memory.
        //As far as I understand, wasm can't directly access javascript memory.
        //Which is why we need to allocate special wasm memory and then
        //copy the file from javascript memory into wasm memory so our wasm functions
        //can work on it.

        //First we need to allocate the wasm memory.
        //_malloc returns the address of the new wasm memory as int32.
        //This call is probably similar to
        //uint8_t * ptr = new uint8_t[sizeof(uint8_t_arr)/sizeof(uint8_t_arr[0])]
        const uint8_t_ptr = window.Module._malloc(uint8_t_arr.length);

        //Now that we have a block of memory we can copy the file data into that block
        //This is probably similar to
        //std::memcpy(uint8_t_ptr, uint8_t_arr, sizeof(uint8_t_arr)/sizeof(uint8_t_arr[0]))
        window.Module.HEAPU8.set(uint8_t_arr, uint8_t_ptr);

        //The only thing that's now left to do is pass
        //the address of the wasm memory we just allocated
        //to our function as well as the size of our memory.
        window.Module.readFile(uint8_t_ptr, uint8_t_arr.length);

        //At this point we're forced to wait until wasm is done with the memory.
        //Your site will now freeze if the memory you're working on is big.
        //Maybe we can somehow let our wasm function run on a seperate thread and pass a callback?

        //Retreiving our (modified) memory is also straight forward.
        //First we get some javascript memory and then we copy the
        //relevant chunk of the wasm memory into our javascript object.
        const returnArr = new Uint8Array(uint8_t_arr.length);
        //If returnArr is std::vector<uint8_t>, then is probably similar to
        //returnArr.assign(ptr, ptr + dataSize)
        returnArr.set(window.Module.HEAPU8.subarray(uint8_t_ptr, uint8_t_ptr + uint8_t_arr.length));

        //Lastly, according to the docs, we should call ._free here.
        //Do we need to call the gc somehow?
        window.Module._free(uint8_t_ptr);

    }
    reader.readAsArrayBuffer(file);
}

Here is readFile.cpp.

#include <emscripten/bind.h>

//We get out pointer as a plain int from javascript
void readFile(const int & addr, const size_t & len){
  //We use a reinterpret_cast to turn our plain int into a uint8_t pointer. After
  //which we can play with the data just like we would normally.
  uint8_t * data = reinterpret_cast<uint8_t *>(addr);
  for(size_t i = 0; i < len; ++i){
    data[i] += 1;
  }
}

//Using this command to compile
//  emcc --bind -O3 readFile.cpp -s WASM=1 -s TOTAL_MEMORY=268435456 -o api.js --std=c++11
//Note that you need to make sure that there's enough memory available to begin with.
//I got only 16mb without passing the TOTAL_MEMORY setting.
EMSCRIPTEN_BINDINGS(my_module) {
  emscripten::function("readFile", &readFile);
}


问:
Can you import data into an Access database using only the runtime environment?
I have developed an Access database for a small business and wish to create a way of adding new entries remotely, I am not sure how exactly, but I'd like to know if there is a way to import data if said business is utilizing access only with the runtime environment which doesn't provide any of the "menu buttons" of the main product, among which there are several import options (excel, access, xml etc...).

Alternatively, would it be possible to hook up the databse with an external source from which it will pull new entries periodically?

答:
You are correct that the runtime environment hides a lot of the functionality in Access, but almost anything that can be done with a full version of Access can be done in the runtime environment, including imports and exports.

In your case, you will want to look into the VBA methods DoCmd.TransferText, DoCmd.TransferSpreadsheet, and DoCmd.TransferDatabase. You will need to create a button or a menu item in the runtime environment to call a custom VBA method where the appropriate DoCmd.Transfer* method is called with parameters you will have to supply from your custom user interface or values stored in your database.


问:
how to get physical constant in scipy in cgs unit?
I was wondering how do I get some physical constants from scipy.constants in cgs unit.

for example: if I want thomson cross section constant from scipy I do,

```<code>constants.value(u'Thomson cross section')
6.6524587158e-29
</code>```

But this is built in SI unit. Also it does not show me the unit that comes with it. I want to import it in cgs:
Is there any command in scipy that will allow me select the unit as well? Maybe something like the following:

```<code>constants.value(u'Thomson cross section').in_units_of(cm**2)
</code>```

Your suggestion is appreciated.

答:
From browsing the constants.py file (documentation) I deduce that I can get:

```<code>In [183]: constants.value('Thomson cross section')
Out[183]: 6.6524587158e-29
In [184]: constants.unit('Thomson cross section')
Out[184]: 'm^2'
In [187]: constants.precision('Thomson cross section')
Out[187]: 1.367915290986615e-09
</code>```

This value is in a dictionary:

```<code>In [196]: constants.physical_constants['Thomson cross section']
Out[196]: (6.6524587158e-29, 'm^2', 9.1e-38)
</code>```

See the scipy.constants.codata.py file for more information.

I don't see any code in the constants.py file to do unit conversions.  Guess you'll have to do that yourself.

Body:
I was wondering how do I get some physical constants from scipy.constants in cgs unit.

for example: if I want thomson cross section constant from scipy I do,

constants.value(u'Thomson cross section')
6.6524587158e-29

But this is built in SI unit. Also it does not show me the unit that comes with it. I want to import it in cgs:
Is there any command in scipy that will allow me select the unit as well? Maybe something like the following:

constants.value(u'Thomson cross section').in_units_of(cm**2)

Your suggestion is appreciated.

Body:
From browsing the constants.py file (documentation) I deduce that I can get:

In [183]: constants.value('Thomson cross section')
Out[183]: 6.6524587158e-29
In [184]: constants.unit('Thomson cross section')
Out[184]: 'm^2'
In [187]: constants.precision('Thomson cross section')
Out[187]: 1.367915290986615e-09

This value is in a dictionary:

In [196]: constants.physical_constants['Thomson cross section']
Out[196]: (6.6524587158e-29, 'm^2', 9.1e-38)

See the scipy.constants.codata.py file for more information.

I don't see any code in the constants.py file to do unit conversions.  Guess you'll have to do that yourself.


问:
Routing with Express when using React
I want to set the routes for my web app using Express, and I'm also using React to handle the front end. The problem is that I don't understand how to route things properly when using React components.

I have in my index.html:

```<code><script> document.getElementById("input").onchange = function() {  ...  } </script>
</code>```

And my App.js:

```<code>class App extends Component {
    render() {
        return ( <div><input id="input" /></div> );
    }

}
</code>```

And router.js:

```<code>app.get('/', function (req, res) {
    res.sendFile(path.resolve('public/index.html'))
})
app.use(express.static('static'));
app.listen(3001, function () {
  console.log('Example app listening on port 3001!')
})
</code>```

And static/index.js:

```<code>ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
</code>```

The problem is that I'm getting "Cannot set property 'onchange' of null". Obviously the App object was not rendered, but I don't understand why. How can I make this work?

答:
I believe you need the express router

Differences between express.Router and app.get?

```<code>var express = require('express');
var path = require('path');
var router = express.Router();

router.get('/', function(req, res) {
    res.sendFile(path.join(__dirname), '../public/index.html');
});
</code>```

Title: Routing with Express when using React

Body:
I want to set the routes for my web app using Express, and I'm also using React to handle the front end. The problem is that I don't understand how to route things properly when using React components.

I have in my index.html:

And my App.js:

class App extends Component {
    render() {
        return (
<input id="input" />
 );
    }

}

And router.js:

app.get('/', function (req, res) {
    res.sendFile(path.resolve('public/index.html'))
})
app.use(express.static('static'));
app.listen(3001, function () {
  console.log('Example app listening on port 3001!')
})

And static/index.js:

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

The problem is that I'm getting "Cannot set property 'onchange' of null". Obviously the App object was not rendered, but I don't understand why. How can I make this work?

Body:
I believe you need the express router

Differences between express.Router and app.get?

var express = require('express');
var path = require('path');
var router = express.Router();

router.get('/', function(req, res) {
    res.sendFile(path.join(__dirname), '../public/index.html');
});


问:
Why does sourcing this file behave differently the second time?
Starting with this directory structure:

```<code> $ tree
.
├── 1
│   └── 2
│       └── foo.jar
└── a
    └── b
        └── c
            └── setAlias
</code>```

The goal is to come up with the contents of setAlias, so I can source the file, and it will create an alias that runs java -jar /absolute/path/to/foo.jar

Here's what I have so far:

```<code>FOO="java -jar $(realpath $(dirname $_)/../../../1/2/foo.jar)"
echo "Setting Alias:"
echo "    foo -> $FOO"
alias foo='$FOO'
</code>```

If I source setAlias from its own directly, everything works fine.  But if I set it from the root directory, I have to run it twice before the absoulute path is resolved:

```<code>$ source a/b/c/setAlias
realpath: ./../../../1/2/foo.jar: No such file or directory
Setting Alias:
    foo -> java -jar

$ source a/b/c/setAlias
Setting Alias:
    foo -> java -jar /home/MatrixManAtYrService/1/2/foo.jar
</code>```

If I do this from ./a/b/c the path is resolved on the first try.

What is happening here?  Why does realpath take two tries to find the file?

答:
This is a very strange thing to do, but it's easily explained. Here's an excerpt from man bash under Special Parameters

$_ [..] expands  to the last argument to the  previous  command,  after  expansion. [...]

In other words, it refers to the last argument of the most recently executed command:

```<code>$ echo foo bar baz
foo bar baz

$ echo $_
baz
</code>```

In your case, you run some arbitrary command not shown in your post, followed by source twice:

```<code>$ true foobar           # $_ now becomes "foobar"
$ source a/b/c/setAlias # fails because $_ is "foobar", sets $_ to a/b/c/setAlias
$ source a/b/c/setAlias # works because $_ is now "a/b/c/setAlias"
</code>```

In other words, your source will only work when preceded by a command that uses the value you require of $_ as its last argument. This could be anything:

```<code>$ wc -l a/b/c/setAlias  # also sets $_ to a/b/c/setAlias
4
$ source a/b/c/setAlias # Works, because $_ is set to the expected value
</code>```

Maybe you wanted to get the current script's path instead?

Body:
Starting with this directory structure:

 $ tree
.
├── 1
│   └── 2
│       └── foo.jar
└── a
    └── b
        └── c
            └── setAlias

The goal is to come up with the contents of setAlias, so I can source the file, and it will create an alias that runs java -jar /absolute/path/to/foo.jar

Here's what I have so far:

FOO="java -jar $(realpath $(dirname $_)/../../../1/2/foo.jar)"
echo "Setting Alias:"
echo "    foo -> $FOO"
alias foo='$FOO'

If I source setAlias from its own directly, everything works fine.  But if I set it from the root directory, I have to run it twice before the absoulute path is resolved:

$ source a/b/c/setAlias
realpath: ./../../../1/2/foo.jar: No such file or directory
Setting Alias:
    foo -> java -jar

$ source a/b/c/setAlias
Setting Alias:
    foo -> java -jar /home/MatrixManAtYrService/1/2/foo.jar

If I do this from ./a/b/c the path is resolved on the first try.

What is happening here?  Why does realpath take two tries to find the file?

Body:
This is a very strange thing to do, but it's easily explained. Here's an excerpt from man bash under Special Parameters

$_ [..] expands  to the last argument to the  previous  command,  after  expansion. [...]

In other words, it refers to the last argument of the most recently executed command:

$ echo foo bar baz
foo bar baz

$ echo $_
baz

In your case, you run some arbitrary command not shown in your post, followed by source twice:

$ true foobar           # $_ now becomes "foobar"
$ source a/b/c/setAlias # fails because $_ is "foobar", sets $_ to a/b/c/setAlias
$ source a/b/c/setAlias # works because $_ is now "a/b/c/setAlias"

In other words, your source will only work when preceded by a command that uses the value you require of $_ as its last argument. This could be anything:

$ wc -l a/b/c/setAlias  # also sets $_ to a/b/c/setAlias
4
$ source a/b/c/setAlias # Works, because $_ is set to the expected value

Maybe you wanted to get the current script's path instead?


问:
Google App Engine is not creating table (python)
I have this model

```<code>class SiteUser(db.Model):
    site_user = db.UserProperty()
    total_votes = db.IntegerProperty(default=1)
    liked_items = db.StringProperty()

class Item(db.Model):
    user_who_liked_this_item = db.UserProperty()
    title = db.StringProperty()
    url = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    points = db.IntegerProperty(default=1)
</code>```

Item table is created but SiteUser table is not created. Can anyone help me understand what I am doing wrong?

Thanks?

答: There are no 'tables' on App Engine. A kind will show up in the datastore viewer if you have inserted at least one record with that kind; my guess is that you haven't inserted any SiteUser entities into the datastore.

Body:
I have this model

class SiteUser(db.Model):
    site_user = db.UserProperty()
    total_votes = db.IntegerProperty(default=1)
    liked_items = db.StringProperty()

class Item(db.Model):
    user_who_liked_this_item = db.UserProperty()
    title = db.StringProperty()
    url = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    points = db.IntegerProperty(default=1)

Item table is created but SiteUser table is not created. Can anyone help me understand what I am doing wrong?

Thanks?


问:
Can I display image in full screen mode with PIL?
How to display image on full screen with Python Imaging Library?

```<code>from PIL import Image

img1 = Image.open ('colagem3.png');
img1.show ();
</code>```

DISPLAY ON FULL SCREEN MODE!

答:
Core of the problem

PIL has no native way of opening an image in full screen.  And it makes sense that it can't.  What PIL does is it simply opens your file in the default .bmp file viewing program (commonly, Windows Photos on Windows [although this is Windows version dependent]).  In order for it to open that program in full screen, PIL would need to know what arguments to send the program.  There is no standard syntax for that.  Thus, it is impossible.

But, that doesn't mean that there isn't a solution to opening images in fullscreen.  By using a native library in Python, Tkinter, we can create our own window that displays in fullscreen which shows an image.

Compatibility

In order to avoid being system reliant (calling .dll and .exe files directly).  This can be accomplished with Tkinter.  Tkinter is a display library.  This code will work perfectly on any computer that runs Python 2 or 3.

Our function

```<code>import sys
if sys.version_info[0] == 2:  # the tkinter library changed it's name from Python 2 to 3.
    import Tkinter
    tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
    import tkinter
from PIL import Image, ImageTk

def showPIL(pilImage):
    root = tkinter.Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.overrideredirect(1)
    root.geometry("%dx%d+0+0" % (w, h))
    root.focus_set()
    root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
    canvas = tkinter.Canvas(root,width=w,height=h)
    canvas.pack()
    canvas.configure(background='black')
    imgWidth, imgHeight = pilImage.size
    if imgWidth > w or imgHeight > h:
        ratio = min(w/imgWidth, h/imgHeight)
        imgWidth = int(imgWidth*ratio)
        imgHeight = int(imgHeight*ratio)
        pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(w/2,h/2,image=image)
    root.mainloop()
</code>```

Usage

```<code>pilImage = Image.open("colagem3.png")
showPIL(pilImage)
</code>```

Output

It creates a fullscreen window with your image centered on a black canvas.  If need be, your image will be resized.  Here's a visual of it:

Note: use escape to close fullscreen

Body:
How to display image on full screen with Python Imaging Library?

from PIL import Image

img1 = Image.open ('colagem3.png');
img1.show ();

DISPLAY ON FULL SCREEN MODE!

Body:
Core of the problem

PIL has no native way of opening an image in full screen.  And it makes sense that it can't.  What PIL does is it simply opens your file in the default .bmp file viewing program (commonly, Windows Photos on Windows [although this is Windows version dependent]).  In order for it to open that program in full screen, PIL would need to know what arguments to send the program.  There is no standard syntax for that.  Thus, it is impossible.

But, that doesn't mean that there isn't a solution to opening images in fullscreen.  By using a native library in Python, Tkinter, we can create our own window that displays in fullscreen which shows an image.

Compatibility

In order to avoid being system reliant (calling .dll and .exe files directly).  This can be accomplished with Tkinter.  Tkinter is a display library.  This code will work perfectly on any computer that runs Python 2 or 3.

Our function

import sys
if sys.version_info[0] == 2:  # the tkinter library changed it's name from Python 2 to 3.
    import Tkinter
    tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
    import tkinter
from PIL import Image, ImageTk

def showPIL(pilImage):
    root = tkinter.Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.overrideredirect(1)
    root.geometry("%dx%d+0+0" % (w, h))
    root.focus_set()
    root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
    canvas = tkinter.Canvas(root,width=w,height=h)
    canvas.pack()
    canvas.configure(background='black')
    imgWidth, imgHeight = pilImage.size
    if imgWidth > w or imgHeight > h:
        ratio = min(w/imgWidth, h/imgHeight)
        imgWidth = int(imgWidth*ratio)
        imgHeight = int(imgHeight*ratio)
        pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(w/2,h/2,image=image)
    root.mainloop()

Usage

pilImage = Image.open("colagem3.png")
showPIL(pilImage)

Output

It creates a fullscreen window with your image centered on a black canvas.  If need be, your image will be resized.  Here's a visual of it:

Note: use escape to close fullscreen


问:
Render multilpe times - Double render in rails
How to avoid this double render issue, i have been trying to replicate but couldn't. So is there any issue with this below code?

```<code>def check_count
  assign_values_from_params
  if count >= failed_count
    render partial: params[:view_name], layout: false and return
  else
    render text: 'works' and return
  end
end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  end

  if @counted_obj != 5
    # call one function
  end
end
</code>```

Also should i try something this way Double render error rails ?

答:
Try this and see if it works for you.</p>

```<code>def check_count
  assign_values_from_params

end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  else
    if @counted_obj != 5
      # call one function
    end

    if count >= failed_count
      render partial: params[:view_name], layout: false and return
    else
      render text: 'works' and return
    end
  end

end
</code>```

Body:
How to avoid this double render issue, i have been trying to replicate but couldn't. So is there any issue with this below code?

def check_count
  assign_values_from_params
  if count >= failed_count
    render partial: params[:view_name], layout: false and return
  else
    render text: 'works' and return
  end
end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  end

  if @counted_obj != 5
    # call one function
  end
end

Also should i try something this way Double render error rails ?

Body:
Try this and see if it works for you.

def check_count
  assign_values_from_params

end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  else
    if @counted_obj != 5
      # call one function
    end

    if count >= failed_count
      render partial: params[:view_name], layout: false and return
    else
      render text: 'works' and return
    end
  end

end


问:
What does this Flow JS "polymorphic type instead of intersection type" error mean?
What does this Flow JS error mean?

Expected polymorphic type instead of any member of intersection type.

Details:

The error is thrown by Document in the export line below. I don't understand why it's happening or what I can do to fix it. (I tried looking this up in the Flow documentation, but still couldn't figure it out.)

```<code>// @flow
import Document, {Head, Main, NextScript} from 'next/document'

export default class IntlDocument extends Document {
  static async getInitialProps (context) {
    const props = await super.getInitialProps(context)
    const {req: {localeDataScript}} = context
    return {
      ...props,
      localeDataScript
    }
  }

  render () {
    return (
      <html>
        <Head />
        <body>
          <Main />
          <script
            dangerouslySetInnerHTML={{
              __html: this.props.localeDataScript
            }}
          />
          <NextScript />
        </body>
      </html>
    )
  }
}
</code>```

And the next/document type declaration is this:

```<code>declare module "next/document" {
  import type {Component} from 'react';

  declare type Context = {
    pathname: string,
    query: any,
    req?: any,
    res?: any,
    xhr?: any,
    err?: any,
  };
  declare export var Head: Class<Component<void, *, *>>;
  declare export var Main: Class<Component<void, *, *>>;
  declare export var NextScript: Class<Component<void, *, *>>;
  declare export default Class<Component<void, *, *>> & {
    getInitialProps: (ctx: Context) => Promise<*>;
    renderPage(cb: Function): void;
  };
}
</code>```

答:
First I want to note that the code that you provided needs some updates to work with Flow v0.53.0 or later. That version made big changes to the way that Flow annotations for React work. In particular the Component class changed to taking two type parameters instead of three. I have made the necessary changes in the code snippets in my answer.

In the latest version of Flow (v0.59.0) the error message reports much more detail:

```<code>Error: react.js:7
  7: export default class IntlDocument extends Document {
                                               ^^^^^^^^ identifier `Document`. Expected polymorphic type instead of any member of intersection type
  7: export default class IntlDocument extends Document {
                                               ^^^^^^^^ intersection
  Member 1:
   15:   declare export default Class<Component<*, *>> & {
                                ^^^^^^^^^^^^^^^^^^^^^^ class type: type application of Component. See lib: types/next-document.js:15
  Error:
    9:     const props = await super.getInitialProps(context)
                                     ^^^^^^^^^^^^^^^ property `getInitialProps`. Property not found in
    9:     const props = await super.getInitialProps(context)
                               ^^^^^ statics of React$Component
  Member 2:
                                                         v
   15:   declare export default Class<Component<*, *>> & {
   16:     getInitialProps: (ctx: Context) => Promise<*>;
   17:     renderPage(cb: Function): void;
   18:   };
         ^ object type. See lib: types/next-document.js:15
  Error:
    7: export default class IntlDocument extends Document {
                                                 ^^^^^^^^ identifier `Document`. Expected polymorphic type instead of
                                                         v
   15:   declare export default Class<Component<*, *>> & {
   16:     getInitialProps: (ctx: Context) => Promise<*>;
   17:     renderPage(cb: Function): void;
   18:   };
         ^ object type. See lib: types/next-document.js:15

Found 1 error
</code>```

The intersection type in question is the type Document (the default export of "next/document"), which is an intersection of

```<code>Class<Component<void, *, *>>
</code>```

and

```<code>{
  getInitialProps: (ctx: Context) => Promise<*>;
  renderPage(cb: Function): void;
}
</code>```

It looks like the intention is that Document is a subclass of React's Component class with the static methods getInitialProps and renderPage. Flow does see getInitialProps and renderPage as methods that can be called on Document. The problem is that Flow does not see those as static methods for purposes of subclassing; so your call to super.getInitialProps(context) fails.

A simple way around this is to change the invocation super.getInitialProps(context) to Document.getInitialProps(context).

A better fix is to replace the type intersection with a proper class declaration in the "next/document" type definitions:

```<code>declare export default class Document<Props, State = void> extends React$Component<Props, State> {
  static getInitialProps(ctx: Context): Promise<Props>;
  static renderPage(cb: Function): void;
}
</code>```

I can see why the original author did not do it this way. That type definition file imports the Component type like this:

```<code>import type {Component} from 'react';
</code>```

In Flow a class is a value and a type with the same name. You need the value to create a subclass, because a subclass is something that exists at runtime, and types do not exist at runtime. That import brings in the Component type, but not the value, and Flow will not let you declare a subclass if the value is not in scope. If you try you will get an error like this:

```<code>types/next-document.js:26
 26:   declare export default class Document<Props, State = void> extends Component<Props, State> {
                                                                          ^^^^^^^^^ Component. type referenced from value position
  2:   import type {Component} from 'react';
                    ^^^^^^^^^ type Component
</code>```

The original author imported the just the type because type definition files are not allowed to import values - they can only import types. The author found that they could not properly declare a subclass, and resorted to that type union workaround.

It happens that the type definitions for React (which are built into Flow, see react.js) put some types into the global namespace. This is a workaround that type definition authors use sometimes due to problems importing things in type definition files. The convention is to prefix globally-scoped types with the capitalized module name and a dollar sign. So you can use the React$Component type in type definition files without importing it; which is what I did in the declaration above.

Body:
What does this Flow JS error mean?

Expected polymorphic type instead of any member of intersection type.

Details:

The error is thrown by Document in the export line below. I don't understand why it's happening or what I can do to fix it. (I tried looking this up in the Flow documentation, but still couldn't figure it out.)

// @flow
import Document, {Head, Main, NextScript} from 'next/document'

export default class IntlDocument extends Document {
  static async getInitialProps (context) {
    const props = await super.getInitialProps(context)
    const {req: {localeDataScript}} = context
    return {
      ...props,
      localeDataScript
    }
  }

  render () {
    return (

Body:
First I want to note that the code that you provided needs some updates to work with Flow v0.53.0 or later. That version made big changes to the way that Flow annotations for React work. In particular the Component class changed to taking two type parameters instead of three. I have made the necessary changes in the code snippets in my answer.

In the latest version of Flow (v0.59.0) the error message reports much more detail:

Error: react.js:7
  7: export default class IntlDocument extends Document {
                                               ^^^^^^^^ identifier `Document`. Expected polymorphic type instead of any member of intersection type
  7: export default class IntlDocument extends Document {
                                               ^^^^^^^^ intersection
  Member 1:
   15:   declare export default Class<Component<*, *>> & {
                                ^^^^^^^^^^^^^^^^^^^^^^ class type: type application of Component. See lib: types/next-document.js:15
  Error:
    9:     const props = await super.getInitialProps(context)
                                     ^^^^^^^^^^^^^^^ property `getInitialProps`. Property not found in
    9:     const props = await super.getInitialProps(context)
                               ^^^^^ statics of React$Component
  Member 2:
                                                         v
   15:   declare export default Class<Component<*, *>> & {
   16:     getInitialProps: (ctx: Context) => Promise<*>;
   17:     renderPage(cb: Function): void;
   18:   };
         ^ object type. See lib: types/next-document.js:15
  Error:
    7: export default class IntlDocument extends Document {
                                                 ^^^^^^^^ identifier `Document`. Expected polymorphic type instead of
                                                         v
   15:   declare export default Class<Component<*, *>> & {
   16:     getInitialProps: (ctx: Context) => Promise<*>;
   17:     renderPage(cb: Function): void;
   18:   };
         ^ object type. See lib: types/next-document.js:15

Found 1 error

The intersection type in question is the type Document (the default export of "next/document"), which is an intersection of

Class<Component<void, *, *>>

and

{
  getInitialProps: (ctx: Context) => Promise<*>;
  renderPage(cb: Function): void;
}

It looks like the intention is that Document is a subclass of React's Component class with the static methods getInitialProps and renderPage. Flow does see getInitialProps and renderPage as methods that can be called on Document. The problem is that Flow does not see those as static methods for purposes of subclassing; so your call to super.getInitialProps(context) fails.

A simple way around this is to change the invocation super.getInitialProps(context) to Document.getInitialProps(context).

A better fix is to replace the type intersection with a proper class declaration in the "next/document" type definitions:

declare export default class Document<Props, State = void> extends React$Component<Props, State> {
  static getInitialProps(ctx: Context): Promise<Props>;
  static renderPage(cb: Function): void;
}

I can see why the original author did not do it this way. That type definition file imports the Component type like this:

import type {Component} from 'react';

In Flow a class is a value and a type with the same name. You need the value to create a subclass, because a subclass is something that exists at runtime, and types do not exist at runtime. That import brings in the Component type, but not the value, and Flow will not let you declare a subclass if the value is not in scope. If you try you will get an error like this:

types/next-document.js:26
 26:   declare export default class Document<Props, State = void> extends Component<Props, State> {
                                                                          ^^^^^^^^^ Component. type referenced from value position
  2:   import type {Component} from 'react';
                    ^^^^^^^^^ type Component

The original author imported the just the type because type definition files are not allowed to import values - they can only import types. The author found that they could not properly declare a subclass, and resorted to that type union workaround.

It happens that the type definitions for React (which are built into Flow, see react.js) put some types into the global namespace. This is a workaround that type definition authors use sometimes due to problems importing things in type definition files. The convention is to prefix globally-scoped types with the capitalized module name and a dollar sign. So you can use the React$Component type in type definition files without importing it; which is what I did in the declaration above.


问:
jQuery UI Slider: Range with 3 handles, and configurable colors?
I would like a jQuery UI slider that has five differently colored ranges defined by three handles. (So the first range would be handle 0 - handle 1, and the second range would be handle 1 to handle 2.) Is this possible through configuration, or must I hack it? If I have to modify the source, is there any guidelines for how to go about doing that?

Update: What I'm looking for in terms of ranges is:

| --- color 1 ----- handle1 --------- color 2 ------------- handle2 ------- color3 --------- handle3 -----color 4 ----|

(hopefully that makes sense.)

答:
You probably want to use a range slider and pass in an array of 3 values to create 3 handles (according to the docs):

The slider widget will create handle
  elements with the class
  'ui-slider-handle' on initialization.
  You can specify custom handle elements
  by creating and appending the elements
  and adding the 'ui-slider-handle'
  class before init. It will only create
  the number of handles needed to match
  the length of value/values. For
  example, if you specify 'values: [1,
  5, 18]' and create one custom handle,
  the plugin will create the other two.


问:
Why JSON format is important for android apps? and Who specifies that I should use it or no in my app?
I am not too old in android development, so sorry if the question is so stupid.
I have recently learnt about JSON data format and downloading JSON data arrays and objects in my app? but in all tutorials I have seen the instructor creates a JSON file him self and upload it online then download it from the android app(which he is creating the tutorial about).
I Know that it is faster than xml it downloading and rendering but who to know that the data I am downloading is in JSON or not? who specifies that?
Thank u in advance. </p>

答:
The server define the response and the client (mobile app) should be prepared to receive the data in the specified content type from the server.

JSON content type example :

```<code>Content-type: application/json
</code>```

Body:
The server define the response and the client (mobile app) should be prepared to receive the data in the specified content type from the server.

JSON content type example :

Content-type: application/json


问:
Cordova app not displaying correctly on iPhone X (Simulator)
I tested my Cordova-based app yesterday on the iPhone X Simulator in Xcode 9.0 (9A235) and it didn't look good.
Firstly, instead of filling the full screen area, there was a black area above and below the app content.
And worse, between the app content and the black was two white bars.

Adding cordova-plugin-wkwebview-engine so Cordova renders using WKWebView (not UIWebView) fixes the white bars.
By my app is not migrated from UIWebView to WKWebView due to performance and memory leak issues when using cordova-plugin-wkwebview-engine which occur when loading images downloaded from Inapp Purchase hosted content into an HTML5 canvas (direct file:// access by the Webview is not possible due to security restrictions in WKWebView so the image data must be loaded via cordova-plugin-file).

These screenshots show a test app with a blue background set on the <body>.
Above and below UIWebView, you can see the white bars, but not with WKWebView:

(source: pbrd.co)

(source: pbrd.co)

Both Cordova Webviews exhibit the black areas when compared to a native app which fills the full screen area:

答:
For a manual fix to an existing cordova project

The black bars

Add this to your info.plist file. Fixing the launch image is a separate issue i.e. How to Add iPhoneX Launch Image

```<code><key>UILaunchStoryboardName</key>
<string>CDVLaunchScreen</string>
</code>```

The white bars

Set viewport-fit=cover in the meta tag

```<code><meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For a manual fix to an existing cordova project

The black bars

Add this to your info.plist file. Fixing the launch image is a separate issue i.e. How to Add iPhoneX Launch Image

<key>UILaunchStoryboardName</key>
<string>CDVLaunchScreen</string>

The white bars

Set viewport-fit=cover in the meta tag

<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">