问:
How to convert a working curl/jquery.ajax call onto the backend in Node/Express

I'm a first time question asker here, my apologies in advance if I make any mistakes in this process.  Thank you for your time and assistance in advance.

My end goal is to to use a Node/Express server to access photos from the Webdam.com API. The API docs provide a working CURL command which I converted into a jQuery.ajax() http call that I tested in my browser.  I wish to convert the working jQuery.ajax() call into code on a Node/Express server in order to protect my API keys.

In the end I hope to use something along the lines of Axios or Request but I'm open to other options.  I've looked into using jQuery on my Node server as is mentioned here, but it appears these code examples are deprecated and because jQuery needs a window.document to work, it seems to me Axios or Request would be a better way to go.

Some background info about the working jQuery.ajax() http call, I first retrieve an Oauth2 token.  After I receive a token, I make another jQuery.ajax() call to retrieve the Webdam photo content, API docs are here.

Would someone assist me please in converting this jQuery.ajax() code into Node/Express code so I can retrieve a OAuth2 token.

WORKING CURL COMMAND:

curl -X POST https://apiv2.webdamdb.com/oauth2/token -d 'grant_type=password&client_id=CLIENT_ID&client_secret=SECRET_KEY&username=USERNAME&password=USER_PASSWORD'

WORKING JQUERY.AJAX() CALL:

 var params = {
  grant_type: 'password',
  client_id: CLIENT_ID,
  client_secret: SECRET_KEY,
  username: USERNAME,
  password: USER_PASSWORD
};

$.ajax({
  url: 'https://apiv2.webdamdb.com/oauth2/token',
  type: 'POST',
  dataType: 'json',
  data: params,
  success: function(response) {
    return response.access_token;
  },
  error: function(error) {
    return 'ERROR in webdamAuthenticate';
  }
});```
</div>
</div>

AXIOS ATTEMP THAT IS NOT WORKING:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const axios = require('axios');
const params = {
  grant_type: 'password',
  client_id: CLIENT_ID,
  client_secret: SECRET_KEY,
  username: USERNAME,
  password: USER_PASSWORD
};

axios.post('https://apiv2.webdamdb.com/oauth2/token/', params)
  .then(response => {
    console.log('success in axios webdamAuth', response);
  })
  .catch(err => {
    console.log('ERROR in axios webdamAuth ');
  });</code>```

This is the error response I get, I thought I was specifying the grant_type but it tells me I am not.  I have Googled the error but don't understand what I am missing, please help.

{ error: 'invalid_request',
  error_description: 'The grant type was not specified in the request' }
400
{ date: 'Mon, 04 Dec 2017 19:19:34 GMT',
  server: 'Apache',
  'strict-transport-security': 'max-age=86400; includeSubDomains',
  'access-control-allow-origin': '*',
  'access-control-allow-headers': 'Authorization, X-XSRF-TOKEN',
  'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE, PUT',
  'cache-control': 'private, no-cache, no-store, proxy-revalidate, no-transform, max-age=0, must-revalidate',
  pragma: 'no-cache',
  'content-length': '97',
  connection: 'close',
  'content-type': 'application/json'}```

答:
From you working curl command it sends POST data with default format application/x-www-form-urlencoded. To encode your form url-encode your data in axios you can refer to this.

For instance :

```<code>const axios = require('axios');
const querystring = require('querystring');

var params = {
    grant_type: 'password',
    client_id: CLIENT_ID,
    client_secret: SECRET_KEY,
    username: USERNAME,
    password: USER_PASSWORD
};

axios.post(
    'https://apiv2.webdamdb.com/oauth2/token',
    querystring.stringify(params), {
        headers: {
            'User-Agent': 'YourApp'
        }
});
</code>```

Body:
I'm a first time question asker here, my apologies in advance if I make any mistakes in this process.  Thank you for your time and assistance in advance.

My end goal is to to use a Node/Express server to access photos from the Webdam.com API. The API docs provide a working CURL command which I converted into a jQuery.ajax() http call that I tested in my browser.  I wish to convert the working jQuery.ajax() call into code on a Node/Express server in order to protect my API keys.

In the end I hope to use something along the lines of Axios or Request but I'm open to other options.  I've looked into using jQuery on my Node server as is mentioned here, but it appears these code examples are deprecated and because jQuery needs a window.document to work, it seems to me Axios or Request would be a better way to go.

Some background info about the working jQuery.ajax() http call, I first retrieve an Oauth2 token.  After I receive a token, I make another jQuery.ajax() call to retrieve the Webdam photo content, API docs are here.

Would someone assist me please in converting this jQuery.ajax() code into Node/Express code so I can retrieve a OAuth2 token.

WORKING CURL COMMAND:

curl -X POST https://apiv2.webdamdb.com/oauth2/token -d 'grant_type=password&client_id=CLIENT_ID&client_secret=SECRET_KEY&username=USERNAME&password=USER_PASSWORD'

WORKING JQUERY.AJAX() CALL:

 var params = {
  grant_type: 'password',
  client_id: CLIENT_ID,
  client_secret: SECRET_KEY,
  username: USERNAME,
  password: USER_PASSWORD
};

$.ajax({
  url: 'https://apiv2.webdamdb.com/oauth2/token',
  type: 'POST',
  dataType: 'json',
  data: params,
  success: function(response) {
    return response.access_token;
  },
  error: function(error) {
    return 'ERROR in webdamAuthenticate';
  }
});

AXIOS ATTEMP THAT IS NOT WORKING:

const axios = require('axios');
const params = {
  grant_type: 'password',
  client_id: CLIENT_ID,
  client_secret: SECRET_KEY,
  username: USERNAME,
  password: USER_PASSWORD
};

axios.post('https://apiv2.webdamdb.com/oauth2/token/', params)
  .then(response => {
    console.log('success in axios webdamAuth', response);
  })
  .catch(err => {
    console.log('ERROR in axios webdamAuth ');
  });

This is the error response I get, I thought I was specifying the grant_type but it tells me I am not.  I have Googled the error but don't understand what I am missing, please help.

{ error: 'invalid_request',
  error_description: 'The grant type was not specified in the request' }
400
{ date: 'Mon, 04 Dec 2017 19:19:34 GMT',
  server: 'Apache',
  'strict-transport-security': 'max-age=86400; includeSubDomains',
  'access-control-allow-origin': '*',
  'access-control-allow-headers': 'Authorization, X-XSRF-TOKEN',
  'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE, PUT',
  'cache-control': 'private, no-cache, no-store, proxy-revalidate, no-transform, max-age=0, must-revalidate',
  pragma: 'no-cache',
  'content-length': '97',
  connection: 'close',
  'content-type': 'application/json'}

Body:
From you working curl command it sends POST data with default format application/x-www-form-urlencoded. To encode your form url-encode your data in axios you can refer to this.

For instance :

const axios = require('axios');
const querystring = require('querystring');

var params = {
    grant_type: 'password',
    client_id: CLIENT_ID,
    client_secret: SECRET_KEY,
    username: USERNAME,
    password: USER_PASSWORD
};

axios.post(
    'https://apiv2.webdamdb.com/oauth2/token',
    querystring.stringify(params), {
        headers: {
            'User-Agent': 'YourApp'
        }
});


来源: stackexchange

问:
Javascript .match regular expression with reverse quantifier (or parse right to left)
Given a string like such...

```<code>"ABCDEFG"
</code>```

Is it possible to have a quantifier that works in "reverse" so to say?

For instance:

```<code>var foo = "ABCDEFG";
foo.match(/.{1,3}/g);
</code>```

Results in:

```<code>// Array(3) ["ABC", "DEF", "G"]
</code>```

What I'm trying achieve:

```<code>// Array(3) ["A", "BCD", "EFG"]
</code>```

So regardless of the string length, the array is always a representation of the string, with each node 3 characters in length (except possibly the 1st) but always starting at the end of the string.  So the first array item might be 1, 2 or 3 characters long, simply depending on what's "left over".

I have tried using the following to error:

```<code>foo.match(/.{-1,3}/g); // null
foo.match(/.{1,-3}/g); // null
</code>```

Thinking perhaps I could use negatives similar to splitting strings, however each of those examples returns null.

I'm assuming this can be done within the pattern somehow and not the quantifier, so I'd like to understand how that would be written with .match().  Or would this require having to write a custom method that would involve other string manipulation in order to accomplish this?

答:
If you construct a custom regex, you can use that to pull out the matches in the right order:</p>

```<code>var foo = "ABCDEFG";
console.log(foo.match(new RegExp("(.{"+foo.length % 3+"})"+"(...)".repeat(Math.floor(foo.length / 3)))));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given a string like such...

"ABCDEFG"

Is it possible to have a quantifier that works in "reverse" so to say?

For instance:

var foo = "ABCDEFG";
foo.match(/.{1,3}/g);

Results in:

// Array(3) ["ABC", "DEF", "G"]

What I'm trying achieve:

// Array(3) ["A", "BCD", "EFG"]

So regardless of the string length, the array is always a representation of the string, with each node 3 characters in length (except possibly the 1st) but always starting at the end of the string.  So the first array item might be 1, 2 or 3 characters long, simply depending on what's "left over".

I have tried using the following to error:

foo.match(/.{-1,3}/g); // null
foo.match(/.{1,-3}/g); // null

Thinking perhaps I could use negatives similar to splitting strings, however each of those examples returns null.

I'm assuming this can be done within the pattern somehow and not the quantifier, so I'd like to understand how that would be written with .match().  Or would this require having to write a custom method that would involve other string manipulation in order to accomplish this?

Body:
If you construct a custom regex, you can use that to pull out the matches in the right order:

var foo = "ABCDEFG";
console.log(foo.match(new RegExp("(.{"+foo.length % 3+"})"+"(...)".repeat(Math.floor(foo.length / 3)))));


问:
Wordpress - The Templates drop-down menu lists up to 9 items?
The Templates drop-down menu does not display all my templates. Is there a maximum number that can be displayed? I have 10 templates but I exempt a maximum of 9 templates. How do I list all? I am using Using WP 4.9.

And

答: Thanks McNab, that was exactly it. The problem was in vs 4.9 which caches the list of files obtained from themes, and can take 1 hour to update.</p>


问:
Websphere MQ client deploy to Jboss Fuse
Error appear when MQConnectionFactory try to create connection.
At the same time I'm able to send\receive message from standalone application.

jboss stack trace.

```<code>Caused by: com.ibm.mq.MQException: JMSCMQ0001: JMSCMQ0001, 2, MQCC_FAILED, 2195, MQRC_UNEXPECTED_ERROR
    at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:209)
    ... 24 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2195;AMQ9204: Connection to host 'hostname(1450)' rejected. [1=com.ibm.mq.jmqi.JmqiException[CC=2;RC=2195],3=hostname(1450),5=WMQThreadPool.enqueue]
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:2053)
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1226)
    at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:346)
    ... 23 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2195
    at com.ibm.msg.client.wmq.common.internal.WMQThreadPool.enqueue(WMQThreadPool.java:109)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnection.setUpAsyncMode(RemoteConnection.java:1554)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnection.initSess(RemoteConnection.java:1348)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnection.connect(RemoteConnection.java:727)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.getSessionFromNewConnection(RemoteConnectionSpecification.java:400)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.getSession(RemoteConnectionSpecification.java:299)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnectionPool.getSession(RemoteConnectionPool.java:164)
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1598)
    ... 25 more
Caused by: com.ibm.msg.client.commonservices.CSIException: JMSCS0002
    at com.ibm.msg.client.commonservices.workqueue.PIWorkQueueManager.enqueueItem(PIWorkQueueManager.java:67)
    at com.ibm.msg.client.commonservices.workqueue.WorkQueueManager.enqueue(WorkQueueManager.java:225)
    at com.ibm.msg.client.commonservices.workqueue.WorkQueueManager.enqueue(WorkQueueManager.java:194)
    at com.ibm.msg.client.wmq.common.internal.WMQThreadPool.enqueue(WMQThreadPool.java:91)
</code>```

Query manager log:

```<code>----- amqrmrsa.c : 898 --------------------------------------------------------
24.03.2015 17:09:06 - Process(21296.261) User(mqm) Program(amqrmppa)
                    Host(localserver-name) Installation(Installation1)
                    VRMF(7.5.0.2) QMgr(manager-name)

AMQ9209: Connection to host 'jboss-short-hostname (jboss-ip)' for channel
'channel-name' closed.

EXPLANATION:
An error occurred receiving data from 'jboss-short-hostname (jboss-ip)' over TCP/IP.
The connection to the remote host has unexpectedly terminated.

The channel name is 'channel-name'; in some cases it cannot be determined and so
is shown as '????'.
ACTION:
Tell the systems administrator.
----- amqccita.c : 3843 -------------------------------------------------------
24.03.2015 17:09:06 - Process(21296.261) User(mqm) Program(amqrmppa)
                    Host(localserver-name) Installation(Installation1)
                    VRMF(7.5.0.2) QMgr(manager-name)

AMQ9999: Channel 'channel-name' to host 'jboss-short-hostname (jboss-ip)' ended
abnormally.

EXPLANATION:
The channel program running under process ID 21296 for channel 'channel-name'
ended abnormally. The host name is 'jboss-short-hostname (jboss-ip)'; in some cases
the host name cannot be determined and so is shown as '????'.
ACTION:
Look at previous error messages for the channel program in the error logs to
determine the cause of the failure. Note that this message can be excluded
completely or suppressed by tuning the "ExcludeMessage" or "SuppressMessage"
attributes under the "QMErrorLog" stanza in qm.ini. Further information can be
found in the System Administration Guide.
----- amqrmrsa.c : 898 --------------------------------------------------------
</code>```

About my test stand:
Fuse Fabric  (7.2.0.redhat-024)
IBM WebSphere MQ  Version : 7.5.0.2
Java 1.7

Server WebSphere MQ and jboss installed on different servers.

I installed as features following jars:

```<code>com.ibm.mq.osgi.directip_7.5.0.2.jar
com.ibm.mq.osgi.java_7.5.0.2.jar
com.ibm.msg.client.osgi.commonservices.j2se_7.5.0.2.jar
com.ibm.msg.client.osgi.jms.prereq_7.5.0.2.jar
com.ibm.msg.client.osgi.jms_7.5.0.2.jar
com.ibm.msg.client.osgi.nls_7.5.0.2.jar
com.ibm.msg.client.osgi.wmq.nls_7.5.0.2.jar
com.ibm.msg.client.osgi.wmq.prereq_7.5.0.2.jar
com.ibm.msg.client.osgi.wmq_7.5.0.2.jar
</code>```

My code snippet:

```<code> MQQueueConnectionFactory cf = new MQQueueConnectionFactory();

            // Config
            cf.setHostName("hostname");
            cf.setPort("port");
            cf.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
            cf.setChannel("channel-name");
            cf.setQueueManager("manager-name");
            MQQueueConnection connectionDpc = (MQQueueConnection) cf.createQueueConnection("user", "pass");
</code>```

答: Please try using the IBM MQ 7.5.0.6 (or later) OSGI bundles.  The 7.5.0.2 bundles are known to have this issue.</p>

Body:
Error appear when MQConnectionFactory try to create connection.
At the same time I'm able to send\receive message from standalone application.

jboss stack trace.

Caused by: com.ibm.mq.MQException: JMSCMQ0001: JMSCMQ0001, 2, MQCC_FAILED, 2195, MQRC_UNEXPECTED_ERROR
    at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:209)
    ... 24 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2195;AMQ9204: Connection to host 'hostname(1450)' rejected. [1=com.ibm.mq.jmqi.JmqiException[CC=2;RC=2195],3=hostname(1450),5=WMQThreadPool.enqueue]
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:2053)
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1226)
    at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:346)
    ... 23 more
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2195
    at com.ibm.msg.client.wmq.common.internal.WMQThreadPool.enqueue(WMQThreadPool.java:109)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnection.setUpAsyncMode(RemoteConnection.java:1554)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnection.initSess(RemoteConnection.java:1348)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnection.connect(RemoteConnection.java:727)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.getSessionFromNewConnection(RemoteConnectionSpecification.java:400)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.getSession(RemoteConnectionSpecification.java:299)
    at com.ibm.mq.jmqi.remote.impl.RemoteConnectionPool.getSession(RemoteConnectionPool.java:164)
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1598)
    ... 25 more
Caused by: com.ibm.msg.client.commonservices.CSIException: JMSCS0002
    at com.ibm.msg.client.commonservices.workqueue.PIWorkQueueManager.enqueueItem(PIWorkQueueManager.java:67)
    at com.ibm.msg.client.commonservices.workqueue.WorkQueueManager.enqueue(WorkQueueManager.java:225)
    at com.ibm.msg.client.commonservices.workqueue.WorkQueueManager.enqueue(WorkQueueManager.java:194)
    at com.ibm.msg.client.wmq.common.internal.WMQThreadPool.enqueue(WMQThreadPool.java:91)

Query manager log:

----- amqrmrsa.c : 898 --------------------------------------------------------
24.03.2015 17:09:06 - Process(21296.261) User(mqm) Program(amqrmppa)
                    Host(localserver-name) Installation(Installation1)
                    VRMF(7.5.0.2) QMgr(manager-name)

AMQ9209: Connection to host 'jboss-short-hostname (jboss-ip)' for channel
'channel-name' closed.

EXPLANATION:
An error occurred receiving data from 'jboss-short-hostname (jboss-ip)' over TCP/IP.
The connection to the remote host has unexpectedly terminated.

The channel name is 'channel-name'; in some cases it cannot be determined and so
is shown as '????'.
ACTION:
Tell the systems administrator.
----- amqccita.c : 3843 -------------------------------------------------------
24.03.2015 17:09:06 - Process(21296.261) User(mqm) Program(amqrmppa)
                    Host(localserver-name) Installation(Installation1)
                    VRMF(7.5.0.2) QMgr(manager-name)

AMQ9999: Channel 'channel-name' to host 'jboss-short-hostname (jboss-ip)' ended
abnormally.

EXPLANATION:
The channel program running under process ID 21296 for channel 'channel-name'
ended abnormally. The host name is 'jboss-short-hostname (jboss-ip)'; in some cases
the host name cannot be determined and so is shown as '????'.
ACTION:
Look at previous error messages for the channel program in the error logs to
determine the cause of the failure. Note that this message can be excluded
completely or suppressed by tuning the "ExcludeMessage" or "SuppressMessage"
attributes under the "QMErrorLog" stanza in qm.ini. Further information can be
found in the System Administration Guide.
----- amqrmrsa.c : 898 --------------------------------------------------------

About my test stand:
Fuse Fabric  (7.2.0.redhat-024)
IBM WebSphere MQ  Version : 7.5.0.2
Java 1.7

Server WebSphere MQ and jboss installed on different servers.

I installed as features following jars:

com.ibm.mq.osgi.directip_7.5.0.2.jar
com.ibm.mq.osgi.java_7.5.0.2.jar
com.ibm.msg.client.osgi.commonservices.j2se_7.5.0.2.jar
com.ibm.msg.client.osgi.jms.prereq_7.5.0.2.jar
com.ibm.msg.client.osgi.jms_7.5.0.2.jar
com.ibm.msg.client.osgi.nls_7.5.0.2.jar
com.ibm.msg.client.osgi.wmq.nls_7.5.0.2.jar
com.ibm.msg.client.osgi.wmq.prereq_7.5.0.2.jar
com.ibm.msg.client.osgi.wmq_7.5.0.2.jar

My code snippet:

 MQQueueConnectionFactory cf = new MQQueueConnectionFactory();

            // Config
            cf.setHostName("hostname");
            cf.setPort("port");
            cf.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
            cf.setChannel("channel-name");
            cf.setQueueManager("manager-name");
            MQQueueConnection connectionDpc = (MQQueueConnection) cf.createQueueConnection("user", "pass");


问:
replacement of words in strings
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

```<code>a1<- c(" the classroom is ful ")
a2<- c(" full")
</code>```

In this case I would be replacing ful for full in a1

答:
I think the function you are looking for is gsub():</p>

```<code>gsub (pattern = "ful", replacement = a2, x = a1)
</code>```

Title: replacement of words in strings

Body:
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

a1<- c(" the classroom is ful ")
a2<- c(" full")

In this case I would be replacing ful for full in a1

Body:
I think the function you are looking for is gsub():

gsub (pattern = "ful", replacement = a2, x = a1)


问:
Find a winning condition in Connect4
My program is a game similar to connect 4 but it is a 15x15 board. The winning condition is 5 adjacent pieces. The method is supposed to return True if there are 5 pieces and False otherwise. Right now this is my horizontal check, but it just skips my for loops and returns None. Really all I need is some advice on how to get the for loops to work as they are just skipped over</p>

```<code>def current_player_is_winner(self):

    print(self.__current_player)
    piece = GoPiece(self.__current_player)
    print(piece)
    win_count = 0

    #Horizontal test
    row = 0
    col = 0
    for col in range(self.__board_size):
        for row in (range(self.__board_size)):
            if self.__go_board[row][col] == piece:
                win_count += 1
                col += 1
                print(win_count)
                if win_count == 5:
                    return True
                else:
                    return False
            else:
                row+=1
                win_count = 0
</code>```

答:
Your are calling return False in your for loop.  You really only want to do that in the True case.

You should also look into the for:else: construct.

Do the return False AFTER you have searched through the whole matrix.  This is what your logic should look like:

```<code>def current_player_is_winner(self):
    ''' Depending on the win_count parameter once that many pieces are adjacendt a winer is declared'''
    print(self.__current_player)
    piece = GoPiece(self.__current_player)
    print(piece)
    win_count = 0

    #Horizontal test
    row = 0
    col = 0
    for col in range(self.__board_size):
        for row in (range(self.__board_size)):
            if self.__go_board[row][col] == piece:
                win_count += 1
                col += 1
                print(win_count)
                if win_count == 5:
                    return True
            else:
                row+=1
                win_count = 0
    return False
</code>```

Title: Find a winning condition in Connect4

Body:
My program is a game similar to connect 4 but it is a 15x15 board. The winning condition is 5 adjacent pieces. The method is supposed to return True if there are 5 pieces and False otherwise. Right now this is my horizontal check, but it just skips my for loops and returns None. Really all I need is some advice on how to get the for loops to work as they are just skipped over

def current_player_is_winner(self):

    print(self.__current_player)
    piece = GoPiece(self.__current_player)
    print(piece)
    win_count = 0

    #Horizontal test
    row = 0
    col = 0
    for col in range(self.__board_size):
        for row in (range(self.__board_size)):
            if self.__go_board[row][col] == piece:
                win_count += 1
                col += 1
                print(win_count)
                if win_count == 5:
                    return True
                else:
                    return False
            else:
                row+=1
                win_count = 0

Body:
Your are calling return False in your for loop.  You really only want to do that in the True case.

You should also look into the for:else: construct.

Do the return False AFTER you have searched through the whole matrix.  This is what your logic should look like:

def current_player_is_winner(self):
    ''' Depending on the win_count parameter once that many pieces are adjacendt a winer is declared'''
    print(self.__current_player)
    piece = GoPiece(self.__current_player)
    print(piece)
    win_count = 0

    #Horizontal test
    row = 0
    col = 0
    for col in range(self.__board_size):
        for row in (range(self.__board_size)):
            if self.__go_board[row][col] == piece:
                win_count += 1
                col += 1
                print(win_count)
                if win_count == 5:
                    return True
            else:
                row+=1
                win_count = 0
    return False


问:
Can an event be dispatched to Activity after onDestroy?
Consider that activity is destroyed and onDestroy was fired. Can I be sure that no other messages will be dispatched into this activity handlers like onKeyDown?</p>

答:
According to the docs, no.

"OnDestroy

The final call you receive before your activity is destroyed"

http://developer.android.com/reference/android/app/Activity.html

ContentLicense: CC BY-SA 2.5


问:
Redirect to dynamically generated html in Angular 5
I am building an SPA with Angular 5 and I'm calling an authentication and authorization service.
This service checks if I have a session active and if there's no session or if it has expired then returns 401 and an HTML with the company-wide login page.
I built a service for making this call, like this:

```<code>@Injectable()
export class AuthService {

    private authServicePath = '/<path-to-the-service>';
    private authToken: string;
    private serviceURL: string;
    private requestOptions: any;

    constructor(private http: HttpClient, private cookieService: CookieService) { }

    validateAuth() {
        this.serviceURL = environment.endpoint + this.authServicePath;
        this.authToken = this.cookieService.get('SESSION-TOKEN-COOKIE');
        this.requestOptions = {
            headers: new HttpHeaders(
                {
                    'SESSION-TOKEN-COOKIE': this.authToken
                }
            )
        };

        return this
                .http
                .get(this.serviceURL, this.requestOptions)
                .subscribe(
                    data => {
                        // Do nothing
                    },
                    (err: HttpErrorResponse) => {
                        /*window.document.write = err.error;
                        window.document.close();*/
                    }
                );
    }
}
</code>```

As you can see, I'm calling the service. If the token is valid then there's nothing to do, but if I don't have any active/valid session, then the service will return the 401 Unauthorized and in its payload (.error field) I will get something like this:

```<code><html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
      </head>
      <body>
        <form action="..." ...
</code>```

How do I tell my app to redirect me to this generated page?

As you can see, I tried writing a new HTML with window.document.write but it didn't work.
I understand that Angular Router can only redirect to components belonging to the app.

Thanks in advance.

答:
Ok, so, I found a way to do this. It looks very hackish to me, but it is the first step.
If someone has any advice on this, please let me know.

I used Javascript the old way to append the content of the generated HTML to the  tag of my app. Since the HTML contains an unnamed form, I've done this:

```<code>(err: HttpErrorResponse) => {
                        if (err.status === 401){
                            document.body.innerHTML = err.error;
                            let form = <HTMLFormElement>document.getElementsByTagName('form')[0];
                            form.submit();
                        }
                    }
</code>```

It looks ugly to me, but it is the best that I can get at this time. If someone has another approach to this, please let me know.
I'll mark this question as answered and if there is a better answer I'll be happy to mark it as the right answer.

Thanks

Body:
I am building an SPA with Angular 5 and I'm calling an authentication and authorization service.
This service checks if I have a session active and if there's no session or if it has expired then returns 401 and an HTML with the company-wide login page.
I built a service for making this call, like this:

@Injectable()
export class AuthService {

    private authServicePath = '/<path-to-the-service>';
    private authToken: string;
    private serviceURL: string;
    private requestOptions: any;

    constructor(private http: HttpClient, private cookieService: CookieService) { }

    validateAuth() {
        this.serviceURL = environment.endpoint + this.authServicePath;
        this.authToken = this.cookieService.get('SESSION-TOKEN-COOKIE');
        this.requestOptions = {
            headers: new HttpHeaders(
                {
                    'SESSION-TOKEN-COOKIE': this.authToken
                }
            )
        };

        return this
                .http
                .get(this.serviceURL, this.requestOptions)
                .subscribe(
                    data => {
                        // Do nothing
                    },
                    (err: HttpErrorResponse) => {
                        /*window.document.write = err.error;
                        window.document.close();*/
                    }
                );
    }
}

As you can see, I'm calling the service. If the token is valid then there's nothing to do, but if I don't have any active/valid session, then the service will return the 401 Unauthorized and in its payload (.error field) I will get something like this:

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <form action="..." ...

How do I tell my app to redirect me to this generated page?

As you can see, I tried writing a new HTML with window.document.write but it didn't work.
I understand that Angular Router can only redirect to components belonging to the app.

Thanks in advance.

Body:
Ok, so, I found a way to do this. It looks very hackish to me, but it is the first step.
If someone has any advice on this, please let me know.

I used Javascript the old way to append the content of the generated HTML to the <body> tag of my app. Since the HTML contains an unnamed form, I've done this:

(err: HttpErrorResponse) => {
                        if (err.status === 401){
                            document.body.innerHTML = err.error;
                            let form = <HTMLFormElement>document.getElementsByTagName('form')[0];
                            form.submit();
                        }
                    }

It looks ugly to me, but it is the best that I can get at this time. If someone has another approach to this, please let me know.
I'll mark this question as answered and if there is a better answer I'll be happy to mark it as the right answer.

Thanks


问:
Throw exception from Guava EventBus subscriber
I am using Guava EventBus in sync. How can I rollback the complete transaction if any of the subscribers throw an Exception? How can I throw an Exception which will not be caught by the EventBus Subscriber?</p>

答:
I solved it using java.lang.ThreadLocal variable across the publisher and the subscriber.

Publisher needs to be wrapped in a class which reads thread local exception and throws it

```<code>public void publish(Event event) {
  eventBus.post(event);
  if(threadLocalException != null) {
    Store threadLocalException in some variable say e
    Clear threadLocalException variable
    throw e;
  }
}
</code>```

Subscriber needs to be wrapped in a class to set the exception in thread local variable

```<code>public abstract class EventSubscriber<T extends Event> {

  @Subscribe
  public void invoke(T event) {
    try {
      handle(event);
    } catch (Exception e) {
      Set thread local variable to e
    }
  }

  protected abstract void handle(T event);

}
</code>```

Body:
I solved it using java.lang.ThreadLocal variable across the publisher and the subscriber.

Publisher needs to be wrapped in a class which reads thread local exception and throws it

public void publish(Event event) {
  eventBus.post(event);
  if(threadLocalException != null) {
    Store threadLocalException in some variable say e
    Clear threadLocalException variable
    throw e;
  }
}

Subscriber needs to be wrapped in a class to set the exception in thread local variable

public abstract class EventSubscriber<T extends Event> {

  @Subscribe
  public void invoke(T event) {
    try {
      handle(event);
    } catch (Exception e) {
      Set thread local variable to e
    }
  }

  protected abstract void handle(T event);

}


问:
How can I have carousel of basic cards in google actions app
I want to show a carousel with a list of  of basic cards (https://developers.google.com/actions/assistant/responses#basic_card) in google actions conversation response. I looked at the rich response(https://developers.google.com/actions/assistant/responses#rich-responses) and it allows only one basic card in it.

The reason I want to use basic card instead of carousel of option is simple. When I click on the carousel option it proceeds to next conversation, but with basic card I will be redirected to the external link, which is what I needed.

I'm using the code below to display a list of items(options) in carousel for a chat response currently. Any suggestions and help appreciated

```<code>        let carousel = app.buildCarousel()
        // carousel.addSimpleResponse();
        products_raw.forEach(function(item){
            console.log(item);
            carousel.addItems(
              app.buildOptionItem(item.title,)
              .setTitle(item.title)
              .setDescription(`Price: ${item.price}`)
              // .addButton('know more', item.url)
              .setImage(item.image, item.title)
              // .setImageDisplay('CROPPED')
            )
        });
        app.askWithCarousel(answerData.message_text, carousel)
</code>```

答:
You can't. The two are intended to serve different purposes.

Carousel cards are meant to advance the conversation and provide visual information as part of advancing it. It isn't really meant to provide a final result or to produce something that takes you out of the conversation.

The basic card is meant as part of a result that supplements the voice part of the conversation. It can be the "end result" of a conversation, although it doesn't need to be. As such, it makes sense that it allow linking out to a website.

If you have a number of results as part of the conversation, it may be that there is more you need to do to advance the conversation along still.

ContentLicense: CC BY-SA 4.0

Body:
I want to show a carousel with a list of  of basic cards (https://developers.google.com/actions/assistant/responses#basic_card) in google actions conversation response. I looked at the rich response(https://developers.google.com/actions/assistant/responses#rich-responses) and it allows only one basic card in it.

The reason I want to use basic card instead of carousel of option is simple. When I click on the carousel option it proceeds to next conversation, but with basic card I will be redirected to the external link, which is what I needed.

I'm using the code below to display a list of items(options) in carousel for a chat response currently. Any suggestions and help appreciated

        let carousel = app.buildCarousel()
        // carousel.addSimpleResponse();
        products_raw.forEach(function(item){
            console.log(item);
            carousel.addItems(
              app.buildOptionItem(item.title,)
              .setTitle(item.title)
              .setDescription(`Price: ${item.price}`)
              // .addButton('know more', item.url)
              .setImage(item.image, item.title)
              // .setImageDisplay('CROPPED')
            )
        });
        app.askWithCarousel(answerData.message_text, carousel)


问:
browser = webdriver.Chrome() not working
I am getting started with Selenium for python and have this:

```<code>from selenium import webdriver
browser = webdriver.Chrome()
</code>```

However it gives this error:

```<code>Traceback (most recent call last):
File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
 File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in
__init__
restore_signals, start_new_session)
File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in
_execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 3, in
 <module>
 browser = webdriver.Chrome()
  File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
  packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
 self.service.start()
 File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
 packages\selenium\webdriver\common\service.py", line 81, in start
 os.path.basename(self.path), self.start_error_message)
 selenium.common.exceptions.WebDriverException: Message: 'chromedriver'
 executable needs to be in PATH. Please see
 https://sites.google.com/a/chromium.org/chromedriver/home

[Finished in 1.0s]
</code>```

Anyone have any idea how to fix this? Thanks

答:
From the error message:

```<code>'chromedriver' executable needs to be in PATH.
</code>```

It's clear that you need to pass the path of Chrome web driver in webdriver.Chrome

```<code>driver_path = "/Users/amit/Downloads/chromedriver"
driver = webdriver.Chrome(driver_path)
</code>```

Body:
I am getting started with Selenium for python and have this:

from selenium import webdriver
browser = webdriver.Chrome()

However it gives this error:

Traceback (most recent call last):
File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
 File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in
__init__
restore_signals, start_new_session)
File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in
_execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 3, in
 <module>
 browser = webdriver.Chrome()
  File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
  packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
 self.service.start()
 File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
 packages\selenium\webdriver\common\service.py", line 81, in start
 os.path.basename(self.path), self.start_error_message)
 selenium.common.exceptions.WebDriverException: Message: 'chromedriver'
 executable needs to be in PATH. Please see
 https://sites.google.com/a/chromium.org/chromedriver/home

[Finished in 1.0s]

Anyone have any idea how to fix this? Thanks

Body:
From the error message:

'chromedriver' executable needs to be in PATH.

It's clear that you need to pass the path of Chrome web driver in webdriver.Chrome

driver_path = "/Users/amit/Downloads/chromedriver"
driver = webdriver.Chrome(driver_path)


问:
Is it possible to retrieve which attempt of an SNS message is running on lambda?
I have a topic at AWS SNS which sends messages to an AWS Lambda function. This function may sometimes fail and depending on which attempt is currently running I need to store some information about the failure. After looking for a while I didn't find any way to do that. Is it possible to retrieve which attempt is running?</p>

答:
I tried to use the delivery status feature and retrieve the attempt number using CloudWatch Events, but apparently SNS always deliver successfully its notifications to Lambda functions.

When a Lambda function fails it retries like explained here and not using delivery polices defined at the SNS topic (because it was delivered successfully).

In this particular case I guess it must be implemented mannually.


问:
Can't disable ONLY_FULL_GROUP_BY
I am having an issue with ONLY_FULL_GROUP_BY on MySQL 5.7.14 where I can't seem to disable it even though I've set the SQL mode.

I have set both @@sql_mode to remove ONLY_FULL_GROUP_BY by running this command:

```<code>SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
</code>```

and I've also updated the my.cnf file to exclude it by setting the sql-mode param.

If I run select @@sql_mode I can see that ONLY_FULL_GROUP_BY isn't set anymore.

However when I run my stored procedure I am still getting this error:

```<code>1055 Expression #1 of SELECT list is not in GROUP BY clause and contains
nonaggregated column 'product_id' which is not functionally dependent on
columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
</code>```

What am I missing here? Does the SP ignore the sql-mode?

I don't want to modify the SP code as it's been installed from a 3rd party module (for Magento) and that would cause issues if we wanted to upgrade.

This is on WAMP for my local dev server.

答: For anyone that comes into the same problem,  it turns out that the sql mode is stored along with the stored procedure, so even though I have changed the sql mode correctly it doesn't update the SP at all. To fix this I just deleted and recreated the stored procedures while the new sql mode is set. It now works fine!</p>

Title: Can't disable ONLY_FULL_GROUP_BY

Body:
I am having an issue with ONLY_FULL_GROUP_BY on MySQL 5.7.14 where I can't seem to disable it even though I've set the SQL mode.

I have set both @@sql_mode to remove ONLY_FULL_GROUP_BY by running this command:

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

and I've also updated the my.cnf file to exclude it by setting the sql-mode param.

If I run select @@sql_mode I can see that ONLY_FULL_GROUP_BY isn't set anymore.

However when I run my stored procedure I am still getting this error:

1055 Expression #1 of SELECT list is not in GROUP BY clause and contains
nonaggregated column 'product_id' which is not functionally dependent on
columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

What am I missing here? Does the SP ignore the sql-mode?

I don't want to modify the SP code as it's been installed from a 3rd party module (for Magento) and that would cause issues if we wanted to upgrade.

This is on WAMP for my local dev server.


问:
Remove %0D from variable in BASH
I'm trying this:

```<code>token=`curl -I --header "X-Auth-User: user@user.com" --header "X-Auth-Key: XXXXXXXXXXXXXXXXXXXXXX" api.server.com | grep -Fi X-Auth-Token | awk -F" " '{ print $2}'`

/usr/bin/wget --accept .jpg,.jpeg -p "https://api.server.com/v1/stats/1/graph?callback=jQuery171027000000144289315_1380000003353&mnum=1&res_type=cpu&g_type=6h&graph_type=img&full=1&w=515&h=150&X-Auth-Token=$token" -O "image.jpg" || rm "image.jpg"
</code>```

But my token result is:

```<code>https://api.server.com/v1/stats/1/graph?callback=jQuery171027000000144289315_1380000003353&mnum=1&res_type=cpu&g_type=6h&graph_type=img&full=1&w=515&h=150&X-Auth-Token=SERVER_018d8100000000001d1b817f7d58a6%0D
</code>```

Instead of:

```<code>https://api.server.com/v1/stats/1/graph?callback=jQuery171027000000144289315_1380000003353&mnum=1&res_type=cpu&g_type=6h&graph_type=img&full=1&w=515&h=150&X-Auth-Token=SERVER_018d8100000000001d1b817f7d58a6
</code>```

How to remove %0D (Carriage return)?

答:
I solved it by piping to sed. I was already using sed in my pipe so it made sense.

cmd | sed 's/\r//g'

Title: Remove %0D from variable in BASH

Body:
I'm trying this:

token=`curl -I --header "X-Auth-User: user@user.com" --header "X-Auth-Key: XXXXXXXXXXXXXXXXXXXXXX" api.server.com | grep -Fi X-Auth-Token | awk -F" " '{ print $2}'`

/usr/bin/wget --accept .jpg,.jpeg -p "https://api.server.com/v1/stats/1/graph?callback=jQuery171027000000144289315_1380000003353&mnum=1&res_type=cpu&g_type=6h&graph_type=img&full=1&w=515&h=150&X-Auth-Token=$token" -O "image.jpg" || rm "image.jpg"

But my token result is:

https://api.server.com/v1/stats/1/graph?callback=jQuery171027000000144289315_1380000003353&mnum=1&res_type=cpu&g_type=6h&graph_type=img&full=1&w=515&h=150&X-Auth-Token=SERVER_018d8100000000001d1b817f7d58a6%0D

Instead of:

https://api.server.com/v1/stats/1/graph?callback=jQuery171027000000144289315_1380000003353&mnum=1&res_type=cpu&g_type=6h&graph_type=img&full=1&w=515&h=150&X-Auth-Token=SERVER_018d8100000000001d1b817f7d58a6

How to remove %0D (Carriage return)?


问:
Wikipedia Graph Database Insertion
I am trying to create a database from dbpedia RDF triples. I have a table Categories which contains all the Categories in wikipedia. To store categorizations i have created a table with child and parent fields, both foreign keys to Categories table. To load categories from NTriples iam using the following SQL Query

```<code>INSERT INTO CatToCat (`child`, `parent`)
values((SELECT id FROM Categories WHERE BINARY identifier='Bar'),
       (SELECT id FROM Categories WHERE BINARY identifier='Bar'));
</code>```

But the insertion is very slow.. inserting 2.5Million relationships would take very long time.. is there better way to optimize the query, schema??

答: I solved the problem. Was some indexing issues. Made identifier in Categories unique and binary. I guess that sped up the two selects.</p>

Title: Wikipedia Graph Database Insertion

Body:
I am trying to create a database from dbpedia RDF triples. I have a table Categories which contains all the Categories in wikipedia. To store categorizations i have created a table with child and parent fields, both foreign keys to Categories table. To load categories from NTriples iam using the following SQL Query

INSERT INTO CatToCat (`child`, `parent`)
values((SELECT id FROM Categories WHERE BINARY identifier='Bar'),
       (SELECT id FROM Categories WHERE BINARY identifier='Bar'));

But the insertion is very slow.. inserting 2.5Million relationships would take very long time.. is there better way to optimize the query, schema??


问:
How to add "No Record Found" in PrimeNG Datatable When data is not there?
I searched on primeNG official site, and I found that there is no such attribute like emptyMessage= "No Record Found" for data table in PrimeNG
ref.http://www.primefaces.org/primeng/#/datatable

So when there was no data in my data table, It is not showing me any message.

```<code><p-dataTable  #datatable [value]="jobData" [rows]="20" [paginator]="true"
            [responsive]="true" selectionMode="single"><--emptyMessage="" not working here as attribute :(
    <p-column expander="true" styleClass="icon"></p-column>
            <p-column field="finOrVin" styleClass="vinfin" header="header" sortable="custom" (sortFunction)="sort($event)">
            <p-column field="state"  styleClass="status" header="Status"  sortable="custom" (sortFunction)="sort($event)">
            </p-column>
    </p-dataTable>
</code>```

答:
According to the official documentation this is now available as a template.

When there is no data, DataTable displays a message text defined using the emptyMessage property where as custom content can be provided using emptymessage template.

```<code><p-dataTable [value]="cars" [responsive]="true">
  <p-column field="vin" header="Vin"></p-column>
  <p-column field="year" header="Year"></p-column>
  <p-column field="brand" header="Brand"></p-column>
  <p-column field="color" header="Color"></p-column>
  <ng-template pTemplate="emptymessage">
    Custom content goes here
  </ng-template>
</p-dataTable>
</code>```

Body:
I searched on primeNG official site, and I found that there is no such attribute like emptyMessage= "No Record Found" for data table in PrimeNG
ref.http://www.primefaces.org/primeng/#/datatable

So when there was no data in my data table, It is not showing me any message.

<--emptyMessage="" not working here as attribute :(

Body:
According to the official documentation this is now available as a template.

When there is no data, DataTable displays a message text defined using the emptyMessage property where as custom content can be provided using emptymessage template.

<p-dataTable [value]="cars" [responsive]="true">
  <p-column field="vin" header="Vin"></p-column>
  <p-column field="year" header="Year"></p-column>
  <p-column field="brand" header="Brand"></p-column>
  <p-column field="color" header="Color"></p-column>
  <ng-template pTemplate="emptymessage">
    Custom content goes here
  </ng-template>
</p-dataTable>


问:
Set service Startup type in WiX installer
I am trying to set a pre-installed service's startup type to Automatic, using WiX. Another task was to start the service on install, which I achieved with:

```<code><ServiceControl
    Id="ServiceRunningState"
    Name="[Service Name]"
    Start="install"
    Stop="install"
    Wait="yes" />
</code>```

Now I would also like to set the startup type. I have tried the following (see answer):

```<code><ServiceConfig
    Id="ServiceStartup"
    ServiceName="[Service Name]"
    DelayedAutoStart="yes"
    OnInstall="yes"
    OnReinstall="yes" />
</code>```

But this didn't change the startup type of the service (tested from Manual startup type). And besides, I want the startup type to be Automatic, not Automatic (Delayed Start).

Please note that I am trying to modify an existing service, so there is no ServiceInstall element.

The two elements (ServiceControl and ServiceConfig) are children within a Component parent element.

Any help is appreciated :)

答:
MSI doesn't support changing the startup type of a service that the package doesn't install. ServiceConfig doesn't let you get around that:

Applies only to installed auto-start services or services installed by this package with SERVICE_AUTO_START in the StartType field of the ServiceInstall table.

Body:
I am trying to set a pre-installed service's startup type to Automatic, using WiX. Another task was to start the service on install, which I achieved with:

<ServiceControl
    Id="ServiceRunningState"
    Name="[Service Name]"
    Start="install"
    Stop="install"
    Wait="yes" />

Now I would also like to set the startup type. I have tried the following (see answer):

<ServiceConfig
    Id="ServiceStartup"
    ServiceName="[Service Name]"
    DelayedAutoStart="yes"
    OnInstall="yes"
    OnReinstall="yes" />

But this didn't change the startup type of the service (tested from Manual startup type). And besides, I want the startup type to be Automatic, not Automatic (Delayed Start).

Please note that I am trying to modify an existing service, so there is no ServiceInstall element.

The two elements (ServiceControl and ServiceConfig) are children within a Component parent element.

Any help is appreciated :)


问:
Loopback custom password validation
very simple question: if I try to validate a password in a User model it seems I can only validate the already encrypted password?
So for example if I use

```<code> Customer.validatesLengthOf('password', { min: 8, message: 'Too short' })
</code>```

Then the encrypted password is checked (which is always longer than 8 characters), so no good... If I try to use a custom validation, how can I get access to the original password (the original req.body.password basically)?

答:
Ok I guess the above answer is quite novel and obviously is accepted, but If you want a real easy solution with just some basic validations done and not much code then loopback-mixin-complexity is the solution for you.

If you don't want to create another dependency then you can go ahead with a custom mixin, that you can add into your user model or any other model where you need some kind of validation and it would do the validation for you.

Here's a sample code for how to create such mixin

```<code>module.exports = function(Model, options) {
  'use strict';
  Model.observe('before save', function event(ctx, next) { //Observe any insert/update event on Model
    if (ctx.instance) {
      if(!yourValidatorFn(ctx.instance.password) )
         next('password not valid');
      else
        next();
    }
    else {
      if(!yourValidatorFn(ctx.data.password) )
         next('password not valid');
      else
        next();
    }
  });
};
</code>```

Title: Loopback custom password validation

Body:
very simple question: if I try to validate a password in a User model it seems I can only validate the already encrypted password?
So for example if I use

 Customer.validatesLengthOf('password', { min: 8, message: 'Too short' })

Then the encrypted password is checked (which is always longer than 8 characters), so no good... If I try to use a custom validation, how can I get access to the original password (the original req.body.password basically)?

Body:
Ok I guess the above answer is quite novel and obviously is accepted, but If you want a real easy solution with just some basic validations done and not much code then loopback-mixin-complexity is the solution for you.

If you don't want to create another dependency then you can go ahead with a custom mixin, that you can add into your user model or any other model where you need some kind of validation and it would do the validation for you.

Here's a sample code for how to create such mixin

module.exports = function(Model, options) {
  'use strict';
  Model.observe('before save', function event(ctx, next) { //Observe any insert/update event on Model
    if (ctx.instance) {
      if(!yourValidatorFn(ctx.instance.password) )
         next('password not valid');
      else
        next();
    }
    else {
      if(!yourValidatorFn(ctx.data.password) )
         next('password not valid');
      else
        next();
    }
  });
};


问:
comparing sum of 2 column values in one table with another column value in second table sql server
I have two tables...

table1 ( id, item, price ) values:

```<code>id | item | price
-------------
10 | book | 20
20 | copy | 30
30 | pen  | 10
</code>```

....table2 ( id, item, price) values:

```<code>id | item | price
-------------
10 | book | 20
10 | book | 30
</code>```

now i if do not have a record with id-10,item-book and price-(20+30) in table 1 then i want to insert that row with sum(20+30) in  a new table ...

答:
If I haven't misunderstood your requirements, this should do it:

```<code> SELECT T2.ID, T2.ITEM,T2.SUMPRICE FROM
 (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM) AS T1
 INNER JOIN
 (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM) AS T2
 ON T1.ID = T2.id  AND T1.item = T2.item WHERE T1.SUMPRICE <> T2.SUMPRICE
</code>```

If your 3rd table is already created you could just use an INSERT INTO SELECT statement. Otherwise you could use a SELECT INTO  like this:

```<code>SELECT T2.ID, T2.ITEM,T2.SUMPRICE as price into table3 FROM
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM) AS
T1
INNER JOIN
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM) AS
T2
ON T1.ID = T2.id  AND T1.item = T2.item WHERE T1.SUMPRICE <> T2.SUMPRICE
</code>```

Hope it helps!

EDIT 1
In the case that you want to get all the unmatched rows, that is:

Rows from table 2 where the id, item or price don't match simultenously with a given row in table 1

Rows from table 2 where none of their columns match simultenously with a given row in table 1

You could use the EXCEPT statement, for example:

```<code>(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM)
 EXCEPT
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM)
</code>```

This returns:

```<code>ID   ITEM                 SUMPRICE
---- -------------------- -----------
10   book                 50
</code>```

Body:
I have two tables...

table1 ( id, item, price ) values:

id | item | price
-------------
10 | book | 20
20 | copy | 30
30 | pen  | 10

....table2 ( id, item, price) values:

id | item | price
-------------
10 | book | 20
10 | book | 30

now i if do not have a record with id-10,item-book and price-(20+30) in table 1 then i want to insert that row with sum(20+30) in  a new table ...

Body:
If I haven't misunderstood your requirements, this should do it:

 SELECT T2.ID, T2.ITEM,T2.SUMPRICE FROM
 (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM) AS T1
 INNER JOIN
 (SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM) AS T2
 ON T1.ID = T2.id  AND T1.item = T2.item WHERE T1.SUMPRICE <> T2.SUMPRICE

If your 3rd table is already created you could just use an INSERT INTO SELECT statement. Otherwise you could use a SELECT INTO  like this:

SELECT T2.ID, T2.ITEM,T2.SUMPRICE as price into table3 FROM
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM) AS
T1
INNER JOIN
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM) AS
T2
ON T1.ID = T2.id  AND T1.item = T2.item WHERE T1.SUMPRICE <> T2.SUMPRICE

Hope it helps!

EDIT 1
In the case that you want to get all the unmatched rows, that is:

Rows from table 2 where the id, item or price don't match simultenously with a given row in table 1

Rows from table 2 where none of their columns match simultenously with a given row in table 1

You could use the EXCEPT statement, for example:

(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table2 GROUP BY ID, ITEM)
 EXCEPT
(SELECT ID, ITEM, SUM(PRICE) AS SUMPRICE FROM table1 GROUP BY ID, ITEM)

This returns:

ID   ITEM                 SUMPRICE
---- -------------------- -----------
10   book                 50


问:
How can I send a fax for a pdf from a Windows Service using FAXCOMEXLib?
I've seen this question asked before, but I have not seen any definite answers, and definitely not any answers that solve my problem. I created a windows service to send faxes (semi-automatically) using the FAXCOMEXLib library. So far, my service has been successful at sending text files (.txt). But when I try to send pdf, jpg, or tif files, I get the "Operation failed" error. In SO, I've seen a lot of discussion about the permissions of the user that the service is running under. I've tried a lot of different options (Local Service, Local User, custom user with admin privileges, allow service to interact with desktop). But nothing seems to make a difference. It seems that the service does not have permissions to open the appropriate app to "print" the pdf, jpg, or tif file. But I am only speculating. Has anyone been successful in sending a fax through FAXCOMEXLib in a Windows service? Here is my code that sends the fax:

```<code>fileName = @"D:\temp\FaxTest.txt"; //THIS WORKS
//fileName = @"D:\temp\FaxTest.pdf"; //Operation failed
//fileName = @"D:\temp\FaxTest.tif"; //Operation failed
faxDoc.Sender.Name = faxRec.From;
faxDoc.Sender.Company = faxRec.From;
faxDoc.Body = fileName;
faxDoc.Subject = faxRec.ReferenceId;
faxDoc.DocumentName = faxRec.ReferenceId;
var to = "xxxxxxxxxx";
faxDoc.Recipients.Add(to, "Some Name");
var serverName = Environment.MachineName;
string[] returnVal = faxDoc.Submit(serverName);
</code>```

In case you're wondering, yes, those files do exist on the server with those names, and they are valid files (I can open them up in Adobe Reader and Picture Viewer). And this also works just fine if I run this locally on my dev machine. And of course, the appropriate viewer pops up before sending (on my local machine). My guess is that for some reason the service cannot open the viewer. Has anyone been successful sending a PDF this way in a Windows service?

答:
I want to give a complete answer to this. The previously posted answers had some of the solution, but they did not give a complete picture of everything we had to do to successfully send a pdf file through a fax line, using FAXCOMEXLib in our custom Windows service.

I want to start this off by saying that FAXCOMEXLib is made for a windows console app, not a windows service. You can even read this in the documentation. And I think that's why we had so much trouble getting it working.

However, we were able to get it to work (finally) after much trial and error. Most of the problems we faced were related to setting and permissions in Adobe Reader. What we found is that Adobe Reader was trying to do a lot of things behind the scenes when processing a PDf file. And those "things" it was trying to do required user interaction (clicking away alert boxes, etc). When running this under a Windows service, there is no user interaction from that service, which caused our process to hang indefinitely and eventually error out. But, we found that there is a way around all that. Here is how we did it:

Here is the snippet of code that we are using that works:

```<code>fileName = @"D:\temp\FaxTest.pdf";
faxDoc.Sender.Name = faxRec.From;
faxDoc.Sender.Company = faxRec.From;
faxDoc.Body = fileName;
faxDoc.Subject = faxRec.ReferenceId;
faxDoc.DocumentName = faxRec.ReferenceId;
var to = "xxxxxxxxxx";
faxDoc.Recipients.Add(to, "Some Name");
var serverName = Environment.MachineName;
var myProcesses = Process.GetProcessesByName("AcroRd32");
foreach (var myProcess in myProcesses)
{
    if (DateTime.Now.Ticks - myProcess.StartTime.Ticks > TimeSpan.FromSeconds(30).Ticks) {
        myProcess.Kill();
    }
}
string[] returnVal = faxDoc.Submit(serverName);
</code>```

There is more code than this in our service, of course. The other code does things like handle callback event handlers to track the status of sending/completed/failed faxes, etc. But this is the "heart" of the code that actually initiates the "send".

And here is a list of configuration changes we made to the server to make our custom Windows service properly decode, render, and send pdf files as faxes. Some of these are listed in some of the answers, but some are not, and I wanted this to be a complete answer.

Log on as admin to the server and install the Fax Server role on the server.

Make sure the fax modem device/card is installed properly on the server, and that the fax line is active. You might just try to send a couple test faxes with text files directly from the Windows Fax utility. (In our case we ran into problems because we had to dial "9" and a secret pass-code to get an outside, long-distance line).

Install Adobe Reader on the server.

Create a user on the server for your Windows service to run "as". We called our user "FaxServiceUser".

Log on to the server as this FaxServiceUser at least once. While logged in, set the "Adobe PDF" device as the default printer.

Also while logged in as this user, open a PDF file using Adobe and click through the EULA's.

While logged in as this user, and while you have Adobe Reader open, change these settings:

If checked, un-check "Show me messages when I launch Reader" (Under "General")

Un-check the "Enable Protected Mode" at startup check box (This might only apply to Acrobat 10. In Acrobat 11, this option was moved to Security (Enhanced) and is titled Enable Protected Mode at startup. Just make sure you un-check this option)

Un-check the "Enable Enhanced Security" (Under "Security(Enhanced)" - this might only apply to Acrobat 11 and higher)

Select the Updater option and disable Automatic Download and Install Updates.

Un-check "Create links from URLs" (Under "General")

Un-check "Make Hand tool read articles" (Under "General")

Un-check "Show me messages when I launch Reader" (Under "General")

Un-check "Automatically calculate field values" (Under "Forms")

Un-check "Show focus rectangles" (Under "Forms")

Un-check "Show text field overflow indicator" (Under "Forms")

Un-check "Enable Acrobat JavaScript" (Under "Javascript")

Un-check "Show welcome dialog" (Under "Reviewing")

Un-check "Show server connection warning dialog when opening file" (Under "Reviewing")

If needed, consult this link for assistance with the Adobe Reader settings: http://kb.faxback.com/How+To+Configure+Adobe+XI+for+Use+with+NET+SatisFAXtion

After building, deploying, and installing your Windows service, change the properties of your service to run "as" the user you created earlier ("FaxServiceUser" in our case).

Add permissions for that FaxServiceUser to any of the folders it needs to read/write/delete from/to.

Since Adobe is meant to be run as a desktop app, add some code in your service to release memory used by Adobe Reader (You can see how we did this in the myProcess.Kill() function in the sample code).

And that should do it. It's a little bit cumbersome, but I hope this gives a complete example of how to set up Adobe Reader in conjunction with your custom Windows service to send faxes from pdf files on a Windows server. We've been doing it for a couple months now with no issues. Our client does a low volume of faxes, so I cannot speak to how this works with a high volume of faxes. So, if you are looking for a "free" way to send faxes, without paying for something like Interfax, this could be a viable option, at least for low volume.

Body:
I've seen this question asked before, but I have not seen any definite answers, and definitely not any answers that solve my problem. I created a windows service to send faxes (semi-automatically) using the FAXCOMEXLib library. So far, my service has been successful at sending text files (.txt). But when I try to send pdf, jpg, or tif files, I get the "Operation failed" error. In SO, I've seen a lot of discussion about the permissions of the user that the service is running under. I've tried a lot of different options (Local Service, Local User, custom user with admin privileges, allow service to interact with desktop). But nothing seems to make a difference. It seems that the service does not have permissions to open the appropriate app to "print" the pdf, jpg, or tif file. But I am only speculating. Has anyone been successful in sending a fax through FAXCOMEXLib in a Windows service? Here is my code that sends the fax:

fileName = @"D:\temp\FaxTest.txt"; //THIS WORKS
//fileName = @"D:\temp\FaxTest.pdf"; //Operation failed
//fileName = @"D:\temp\FaxTest.tif"; //Operation failed
faxDoc.Sender.Name = faxRec.From;
faxDoc.Sender.Company = faxRec.From;
faxDoc.Body = fileName;
faxDoc.Subject = faxRec.ReferenceId;
faxDoc.DocumentName = faxRec.ReferenceId;
var to = "xxxxxxxxxx";
faxDoc.Recipients.Add(to, "Some Name");
var serverName = Environment.MachineName;
string[] returnVal = faxDoc.Submit(serverName);

In case you're wondering, yes, those files do exist on the server with those names, and they are valid files (I can open them up in Adobe Reader and Picture Viewer). And this also works just fine if I run this locally on my dev machine. And of course, the appropriate viewer pops up before sending (on my local machine). My guess is that for some reason the service cannot open the viewer. Has anyone been successful sending a PDF this way in a Windows service?

Body:
I want to give a complete answer to this. The previously posted answers had some of the solution, but they did not give a complete picture of everything we had to do to successfully send a pdf file through a fax line, using FAXCOMEXLib in our custom Windows service.

I want to start this off by saying that FAXCOMEXLib is made for a windows console app, not a windows service. You can even read this in the documentation. And I think that's why we had so much trouble getting it working.

However, we were able to get it to work (finally) after much trial and error. Most of the problems we faced were related to setting and permissions in Adobe Reader. What we found is that Adobe Reader was trying to do a lot of things behind the scenes when processing a PDf file. And those "things" it was trying to do required user interaction (clicking away alert boxes, etc). When running this under a Windows service, there is no user interaction from that service, which caused our process to hang indefinitely and eventually error out. But, we found that there is a way around all that. Here is how we did it:

Here is the snippet of code that we are using that works:

fileName = @"D:\temp\FaxTest.pdf";
faxDoc.Sender.Name = faxRec.From;
faxDoc.Sender.Company = faxRec.From;
faxDoc.Body = fileName;
faxDoc.Subject = faxRec.ReferenceId;
faxDoc.DocumentName = faxRec.ReferenceId;
var to = "xxxxxxxxxx";
faxDoc.Recipients.Add(to, "Some Name");
var serverName = Environment.MachineName;
var myProcesses = Process.GetProcessesByName("AcroRd32");
foreach (var myProcess in myProcesses)
{
    if (DateTime.Now.Ticks - myProcess.StartTime.Ticks > TimeSpan.FromSeconds(30).Ticks) {
        myProcess.Kill();
    }
}
string[] returnVal = faxDoc.Submit(serverName);

There is more code than this in our service, of course. The other code does things like handle callback event handlers to track the status of sending/completed/failed faxes, etc. But this is the "heart" of the code that actually initiates the "send".

And here is a list of configuration changes we made to the server to make our custom Windows service properly decode, render, and send pdf files as faxes. Some of these are listed in some of the answers, but some are not, and I wanted this to be a complete answer.

Log on as admin to the server and install the Fax Server role on the server.

Make sure the fax modem device/card is installed properly on the server, and that the fax line is active. You might just try to send a couple test faxes with text files directly from the Windows Fax utility. (In our case we ran into problems because we had to dial "9" and a secret pass-code to get an outside, long-distance line).

Install Adobe Reader on the server.

Create a user on the server for your Windows service to run "as". We called our user "FaxServiceUser".

Log on to the server as this FaxServiceUser at least once. While logged in, set the "Adobe PDF" device as the default printer.

Also while logged in as this user, open a PDF file using Adobe and click through the EULA's.

While logged in as this user, and while you have Adobe Reader open, change these settings:

If checked, un-check "Show me messages when I launch Reader" (Under "General")

Un-check the "Enable Protected Mode" at startup check box (This might only apply to Acrobat 10. In Acrobat 11, this option was moved to Security (Enhanced) and is titled Enable Protected Mode at startup. Just make sure you un-check this option)

Un-check the "Enable Enhanced Security" (Under "Security(Enhanced)" - this might only apply to Acrobat 11 and higher)

Select the Updater option and disable Automatic Download and Install Updates.

Un-check "Create links from URLs" (Under "General")

Un-check "Make Hand tool read articles" (Under "General")

Un-check "Show me messages when I launch Reader" (Under "General")

Un-check "Automatically calculate field values" (Under "Forms")

Un-check "Show focus rectangles" (Under "Forms")

Un-check "Show text field overflow indicator" (Under "Forms")

Un-check "Enable Acrobat JavaScript" (Under "Javascript")

Un-check "Show welcome dialog" (Under "Reviewing")

Un-check "Show server connection warning dialog when opening file" (Under "Reviewing")

If needed, consult this link for assistance with the Adobe Reader settings: http://kb.faxback.com/How+To+Configure+Adobe+XI+for+Use+with+NET+SatisFAXtion

After building, deploying, and installing your Windows service, change the properties of your service to run "as" the user you created earlier ("FaxServiceUser" in our case).

Add permissions for that FaxServiceUser to any of the folders it needs to read/write/delete from/to.

Since Adobe is meant to be run as a desktop app, add some code in your service to release memory used by Adobe Reader (You can see how we did this in the myProcess.Kill() function in the sample code).

And that should do it. It's a little bit cumbersome, but I hope this gives a complete example of how to set up Adobe Reader in conjunction with your custom Windows service to send faxes from pdf files on a Windows server. We've been doing it for a couple months now with no issues. Our client does a low volume of faxes, so I cannot speak to how this works with a high volume of faxes. So, if you are looking for a "free" way to send faxes, without paying for something like Interfax, this could be a viable option, at least for low volume.


问:
Twig: Working internationalization (i18n) example
I am looking for a working i18n example for Twig (the template engine).

Documentation is a bit sparse when it comes to language files. Where should they go, how should they look and what should they be named? I have been trying with .po/.mo files, no luck.

If someone could point me in the right direction...

See: the i18n extension example which does not really tell me much about the language files themselves.

Note: I want to use Twig on its own, not as part of Symfony.

Here is my php-file:

```<code> <?php
header('Content-Type: text/html; charset=utf-8');

$vars = array();
foreach($_POST as $key => $value) {
    $vars[$key] = json_decode(utf8_encode(urldecode($value)));
}

/* Prepare Twig template enginge */
require_once './lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
    //'cache' => './cache',
    'cache' => false
));

/* i18n */
$twig->addExtension(new Twig_Extensions_Extension_I18n());

$availableLanguages = array(
    'en' => 'en_EN',
    'de' => 'de_DE',
    'default' => 'de_DE'
);

// Set language
$locale = array_key_exists($_GET['lang'], $availableLanguages) ? $availableLanguages[$_GET['lang']] : $availableLanguages['default'];
putenv('LC_ALL='.$locale);
setlocale(LC_ALL, $locale);

// Specify the location of the translation tables
bindtextdomain('kalkulator', 'includes/locale');
bind_textdomain_codeset('kalkulator', 'UTF-8');

// Choose domain
textdomain('kalkulator');

$template = $twig->loadTemplate('print.tpl');

$html = $template->render($vars);

switch($_GET['action']) {
    case 'mail':

    break;
    default:
        echo $html;
    break;
}

?>
</code>```

And inside includes/locale I have the following files:

```<code>-rw-r--r--  1 user group  670 Jul 28 10:17 kalkulator-de_DE.mo
-rw-r--r--  1 user group  982 Jul 28 10:22 kalkulator-de_DE.po
-rw-r--r--  1 user group  688 Jul 28 10:38 kalkulator-en_EN.mo
-rw-r--r--  1 user group 1004 Jul 28 10:38 kalkulator-en_EN.po
</code>```

And inside the print.tpl file I am using tags to specify which parts are to be translated:

```<code>{% trans %}
Text to be translated
{% endtrans %}
</code>```

答: I've tried everything possible in slim 3 but nothing was working, only slim 2, so I've created my own way. Basically the system detects the language from the browser and load the correct translation file, more details in the picture:

Body:
I am looking for a working i18n example for Twig (the template engine).

Documentation is a bit sparse when it comes to language files. Where should they go, how should they look and what should they be named? I have been trying with .po/.mo files, no luck.

If someone could point me in the right direction...

See: the i18n extension example which does not really tell me much about the language files themselves.

Note: I want to use Twig on its own, not as part of Symfony.

Here is my php-file:

 <?php
header('Content-Type: text/html; charset=utf-8');

$vars = array();
foreach($_POST as $key => $value) {
    $vars[$key] = json_decode(utf8_encode(urldecode($value)));
}

/* Prepare Twig template enginge */
require_once './lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
    //'cache' => './cache',
    'cache' => false
));

/* i18n */
$twig->addExtension(new Twig_Extensions_Extension_I18n());

$availableLanguages = array(
    'en' => 'en_EN',
    'de' => 'de_DE',
    'default' => 'de_DE'
);

// Set language
$locale = array_key_exists($_GET['lang'], $availableLanguages) ? $availableLanguages[$_GET['lang']] : $availableLanguages['default'];
putenv('LC_ALL='.$locale);
setlocale(LC_ALL, $locale);

// Specify the location of the translation tables
bindtextdomain('kalkulator', 'includes/locale');
bind_textdomain_codeset('kalkulator', 'UTF-8');

// Choose domain
textdomain('kalkulator');

$template = $twig->loadTemplate('print.tpl');

$html = $template->render($vars);

switch($_GET['action']) {
    case 'mail':

    break;
    default:
        echo $html;
    break;
}

?>

And inside includes/locale I have the following files:

-rw-r--r--  1 user group  670 Jul 28 10:17 kalkulator-de_DE.mo
-rw-r--r--  1 user group  982 Jul 28 10:22 kalkulator-de_DE.po
-rw-r--r--  1 user group  688 Jul 28 10:38 kalkulator-en_EN.mo
-rw-r--r--  1 user group 1004 Jul 28 10:38 kalkulator-en_EN.po

And inside the print.tpl file I am using tags to specify which parts are to be translated:

{% trans %}
Text to be translated
{% endtrans %}


问:
Installing iPhone app OTA through server
Generally in order to test the iPhone app before going live in app store, we get the app file for iPhone and along with provisioning profile, we should be able to install the app in iPhone.

My query is "Is there a way to install the iPhone app over the air through server similar to Black berry?" If yes, how can it be done? Please let me know.

Thanks,
Naresh Krishna Kumar. K

答: Check out Test Flight. It allows you to upload ipa files and send a url to your beta testers where they can install it over the air (OTA).</p>


问:
Reject String If Contains Any Non-Alpha Numeric Character
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

```<code>Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^
</code>```

Here is my applicable code:

```<code>while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}
</code>```

答:
Stop reinventing the wheel.

Read this: Apache StringUtils,
Focus on isAlpha,
isAlphanumeric,
and isAlphanumericSpace

One of those is likely to provide the functionality you want.

Body:
I am writing a program and want the program to not loop and request another search pattern if the search pattern (word) contains any non alpha numeric characters.

I have setup a Boolean word to false and an if statement to change the Boolean to true if the word contains letters or numbers. Then another if statement to allow the program to execute if the Boolean is true.

My logic must be off because it is still executing through the search pattern if I simply enter "/". The search pattern cannot contain any non alpha numeric characters to include spaces. I am trying to use Regex to solve this problem.

Sample problematic output:

Please enter a search pattern: /
Line number 1
this.a 2test/austin
            ^

Line number 8
ra charity Charityis 4 times a day/a.a-A
                                  ^

Here is my applicable code:

while (again) {

   boolean found = false;
   System.out.printf("%n%s", "Please enter a search pattern: ", "%n");
   String wordToSearch = input.next();

   if (wordToSearch.equals("EINPUT")) {
      System.out.printf("%s", "Bye!");
      System.exit(0);
   }

   Pattern p = Pattern.compile("\\W*");
   Matcher m = p.matcher(wordToSearch);

   if (m.find())
      found = true;

   String data;
   int lineCount = 1;

   if (found = true) {
      try (FileInputStream fis =
                 new FileInputStream(this.inputPath.getPath())) {
         File file1 = this.inputPath;
         byte[] buffer2 = new byte[fis.available()];
         fis.read(buffer2);
         data = new String(buffer2);
         Scanner in = new Scanner(data).useDelimiter("\\\\|[^a-zA-z0-9]+");
         while (in.hasNextLine()) {

            String line = in.nextLine();

            Pattern pattern = Pattern.compile("\\b" + wordToSearch + "\\b");
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
               System.out.println("Line number " + lineCount);
               String stringToFile = f.findWords(line, wordToSearch);
               System.out.println();
            }
            lineCount++;
         }
      }
   }
}


问:
how to call functions of child component from appcomponent dynamically in angular5?
I have a save button on navigation bar which is in app.component.html and when I click on save, form of the current page should get saved.

Problem is that I was not able to link the save icon in App component to save() method in child components. Can someone please help me on this?

I already tried using @ViewChild but I need save() call to happen dynamically as there are many child components.

答:
There are a couple of approaches that you can use.

The most different would be to use a redux based approach in your app using Ngrx. I highly recommend this approach as it will lead to a cleaner application.

Alternatively, you can use a service that houses the submit code that is can be injected into any child component. An example Plunkr can be found here https://plnkr.co/edit/IOMT14ObtUk0jLSutlHK?p=preview


问:
android - Retrofit call void using Kotlin
I'm with a problem with Retrofit 2. I want to use the Call<Void> to make a call without handle the response body, but it doesnt work with Kotlin.

What I need to use instead of Void?

答:
I want to use the Call to make a call without handle the response body, but it doesnt work with Kotlin

That is not true, it does work.

Something different must be wrong with your setup, or your test case is ill defined if you don't get the expected result.

A very simple example:

```<code>interface GitHub {

    @GET("/users/{username}/repos")
    fun getUserRepos(@Path("username") username: String): Call<Void>
}

val github = Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build()
        .create(GitHub::class.java)

github.getUserRepos("maciekjanusz")
        .enqueue(object : Callback<Void> {
            override fun onFailure(call: Call<Void>?, t: Throwable?) {
                // failure
            }

            override fun onResponse(call: Call<Void>?, response: Response<Void>?) {
                // success
            }
        })
</code>```

I tried the above snippets in an Android example, using Kotlin 1.1.61 and Retrofit 2.3.0 and it works correctly - the call is executed and depending on the network availability and the overall setup, the correct Callback method is called.

Body:
I want to use the Call to make a call without handle the response body, but it doesnt work with Kotlin

That is not true, it does work.

Something different must be wrong with your setup, or your test case is ill defined if you don't get the expected result.

A very simple example:

interface GitHub {

    @GET("/users/{username}/repos")
    fun getUserRepos(@Path("username") username: String): Call<Void>
}

val github = Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build()
        .create(GitHub::class.java)

github.getUserRepos("maciekjanusz")
        .enqueue(object : Callback<Void> {
            override fun onFailure(call: Call<Void>?, t: Throwable?) {
                // failure
            }

            override fun onResponse(call: Call<Void>?, response: Response<Void>?) {
                // success
            }
        })

I tried the above snippets in an Android example, using Kotlin 1.1.61 and Retrofit 2.3.0 and it works correctly - the call is executed and depending on the network availability and the overall setup, the correct Callback method is called.


问:
Increase textarea width space evenly inside container, when over its width limit - css
I'm trying to increase the size of this textarea evenly. But when I change it from 100% width to higher than that, it increases only to the right. I tried margin auto and display block but doesnt work.
Here is my css:

```<code>textarea[form="chform"] {

  width: 100%;
  height: 230px;
  background: transparent;
  border: 1px solid rgba(255,255,255,0.6);
  border-radius: 2px;
  color: grey;
  font-family: 'Exo', sans-serif;
  font-size: 16px;
  font-weight: 400;
  padding: 4px;
  margin-top: 10px;
  resize:none;
}

.profile__form{
  padding: 15px;
  margin: auto;
  border-radius: 50%;

}
.profile_container {
  width: 400px;
  margin: 120px auto 120px;
  /*background: linear-gradient(270deg, rgba(223,190,106,0.8), rgba(146,111,52,0.8), #f0f0f0, rgba(223,190,106,0.7));*/
  padding: 0 20px 20px;
  border-radius: 6px;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.075);
  -webkit-box-shadow: 0 2px 5px rgba(0,0,0,0.075);
  -moz-box-shadow: 0 2px 5px rgba(0,0,0,0.075);
  text-align: center;
}
</code>```

jade:

```<code>    extends layout
block content
 body(style='background-color:black')
    link(href='http://fonts.googleapis.com/css?family=Great+Vibes', rel='stylesheet', type='text/css')
    div.right
        if(user)
            a Welcome #{user.name}
            | &nbsp
            a(href='/main') Home
            | &nbsp
            a(href='/profile') Profile
            | &nbsp
            a(href='/logout') Logout
        else
            a(href='/main') Home
            | &nbsp
            a(href='/register') Register
            | &nbsp
            a(href='/login') Login

    div.profile_container
        form.profile__form(role='form', action="/add-chapters",id="chform" method="post", style='max-width: 800px;')
            .profile__form-heading Add Chapter
            input.form-control(type='number', min="1" name="chapterNumber", id="inputChapterNumber" placeholder='Chapter Number')
            br
            input.form-control(type='text', name="chapterTitle", id="inputChapterTitle", placeholder='Title')

        textarea(name='chapterStory', cols='30', rows='5', form="chform", placeholder="Enter Story")
        br
        button.chform(type='submit') Save
</code>```

HERE IS IMAGE of what I see so far after increasing width. I just want a bigger textarea and centered:

https://i.stack.imgur.com/xSBdL.jpg

Edit: ok added parent css

答:
IMAGE NOW FIXED:
https://i.stack.imgur.com/dbtiY.jpg

So I fixed it by increasing width of parent container the profile form and profile container. Then position relative, display block, and margin auto. Simple!

```<code>textarea[form="chform"] {

  width: 70%;
  height: 500px;
  background: transparent;
  border: 1px solid rgba(255,255,255,0.6);
  border-radius: 2px;
  color: grey;
  font-family: 'Exo', sans-serif;
  font-size: 16px;
  font-weight: 400;
  padding: 4px;
  resize:none;
  position: relative;
  display:block;
  margin:auto;
  margin-top: 10px;

}
</code>```

Body:
I'm trying to increase the size of this textarea evenly. But when I change it from 100% width to higher than that, it increases only to the right. I tried margin auto and display block but doesnt work.
Here is my css:

textarea[form="chform"] {

  width: 100%;
  height: 230px;
  background: transparent;
  border: 1px solid rgba(255,255,255,0.6);
  border-radius: 2px;
  color: grey;
  font-family: 'Exo', sans-serif;
  font-size: 16px;
  font-weight: 400;
  padding: 4px;
  margin-top: 10px;
  resize:none;
}

.profile__form{
  padding: 15px;
  margin: auto;
  border-radius: 50%;

}
.profile_container {
  width: 400px;
  margin: 120px auto 120px;
  /*background: linear-gradient(270deg, rgba(223,190,106,0.8), rgba(146,111,52,0.8), #f0f0f0, rgba(223,190,106,0.7));*/
  padding: 0 20px 20px;
  border-radius: 6px;
  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.075);
  -webkit-box-shadow: 0 2px 5px rgba(0,0,0,0.075);
  -moz-box-shadow: 0 2px 5px rgba(0,0,0,0.075);
  text-align: center;
}

jade:

    extends layout
block content
 body(style='background-color:black')
    link(href='http://fonts.googleapis.com/css?family=Great+Vibes', rel='stylesheet', type='text/css')
    div.right
        if(user)
            a Welcome #{user.name}
            | &nbsp
            a(href='/main') Home
            | &nbsp
            a(href='/profile') Profile
            | &nbsp
            a(href='/logout') Logout
        else
            a(href='/main') Home
            | &nbsp
            a(href='/register') Register
            | &nbsp
            a(href='/login') Login

    div.profile_container
        form.profile__form(role='form', action="/add-chapters",id="chform" method="post", style='max-width: 800px;')
            .profile__form-heading Add Chapter
            input.form-control(type='number', min="1" name="chapterNumber", id="inputChapterNumber" placeholder='Chapter Number')
            br
            input.form-control(type='text', name="chapterTitle", id="inputChapterTitle", placeholder='Title')

        textarea(name='chapterStory', cols='30', rows='5', form="chform", placeholder="Enter Story")
        br
        button.chform(type='submit') Save

HERE IS IMAGE of what I see so far after increasing width. I just want a bigger textarea and centered:

https://i.stack.imgur.com/xSBdL.jpg

Edit: ok added parent css

Body:
IMAGE NOW FIXED:
https://i.stack.imgur.com/dbtiY.jpg

So I fixed it by increasing width of parent container the profile form and profile container. Then position relative, display block, and margin auto. Simple!

textarea[form="chform"] {

  width: 70%;
  height: 500px;
  background: transparent;
  border: 1px solid rgba(255,255,255,0.6);
  border-radius: 2px;
  color: grey;
  font-family: 'Exo', sans-serif;
  font-size: 16px;
  font-weight: 400;
  padding: 4px;
  resize:none;
  position: relative;
  display:block;
  margin:auto;
  margin-top: 10px;

}


问:
Angular pluralization with @ngx-translate and ngx-translate-messageformat-compiler doesn’t initialize properly
I performed the following steps

(1) Created a new angular-cli project (angular-cli 1.5.0)

(2) Added dependencies:

```<code>npm i @ngx-translate/core @ngx-translate/http-loader messageformat ngx-translate-messageformat-compiler --save
</code>```

(3) Added JSON files with translations:

asserts/i18n/en.json

```<code>{
    "translation": "translation",
    "things": "{count, plural, =0{Nothing} one{One thing} other{Lots of things}}"
}
</code>```

asserts/i18n/de.json)

```<code>{
    "translation": "Übersetzung",
    "things": "{count, plural, =0{Nichts} one{Ein Ding} other{Viele Dinge}}"
}
</code>```

(4) AppModule

```<code>import { AppComponent } from './app.component';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      compiler: {
        provide: TranslateCompiler,
        useClass: TranslateMessageFormatCompiler
      }
    }),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

(5) AppComponent

```<code>import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  template: `
    <h1 translate>translation</h1>
    <p>{{'things' | translate:"{ count: 2 }"}}</p>
    <button (click)="selectLang('de')">De</button>
    <button (click)="selectLang('en')">En</button>
  `
})
export class AppComponent {

  constructor(private translate: TranslateService) {
    translate.setDefaultLang('de');
    this.translate.use('de');
    translate.addLangs(['en']);
  }

  selectLang(lang: string)  {
    this.translate.use(lang);
  }

}
</code>```

The page loads without a problem and shows the simple translations properly ("Überschrift") but the pluralization is not working.

Curious, changing the language to en by clicking the button “En” has the desired result:

Now, switching back to “De” shows the desired result in german language too.

答:
Any updates on this?
The work around that I use is to wait until the language finishes setting before displaying my template.  For example, in my appComponent, I'll set:

```<code>  langReady= false;

  constructor(private translate: TranslateService) {
    translate.setDefaultLang('de')
    translate.addLangs(['en']);
    this.translate.use('de').subscribe(()=>{
      this.langReady= true;
    });
  }
</code>```

And in my template, I'll set an *ngIf that waits until the language is ready to be displayed as follow:

```<code><p *ngIf="timeElapsed">{{'things' | translate:"{ count: 1 }"}}</p>
</code>```

This is not a very elegant solution but it works. Have you found a better way of setting up the message compiler?

Body:
I performed the following steps

(1) Created a new angular-cli project (angular-cli 1.5.0)

(2) Added dependencies:

npm i @ngx-translate/core @ngx-translate/http-loader messageformat ngx-translate-messageformat-compiler --save

(3) Added JSON files with translations:

asserts/i18n/en.json

{
    "translation": "translation",
    "things": "{count, plural, =0{Nothing} one{One thing} other{Lots of things}}"
}

asserts/i18n/de.json)

{
    "translation": "Übersetzung",
    "things": "{count, plural, =0{Nichts} one{Ein Ding} other{Viele Dinge}}"
}

(4) AppModule

import { AppComponent } from './app.component';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      compiler: {
        provide: TranslateCompiler,
        useClass: TranslateMessageFormatCompiler
      }
    }),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

(5) AppComponent

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  template: `

translation

{{'things' | translate:"{ count: 2 }"}}

    <button (click)="selectLang('de')">De</button>
    <button (click)="selectLang('en')">En</button>
  `
})
export class AppComponent {

  constructor(private translate: TranslateService) {
    translate.setDefaultLang('de');
    this.translate.use('de');
    translate.addLangs(['en']);
  }

  selectLang(lang: string)  {
    this.translate.use(lang);
  }

}

The page loads without a problem and shows the simple translations properly ("Überschrift") but the pluralization is not working.

Curious, changing the language to en by clicking the button “En” has the desired result:

Now, switching back to “De” shows the desired result in german language too.

Body:
Any updates on this?
The work around that I use is to wait until the language finishes setting before displaying my template.  For example, in my appComponent, I'll set:

  langReady= false;

  constructor(private translate: TranslateService) {
    translate.setDefaultLang('de')
    translate.addLangs(['en']);
    this.translate.use('de').subscribe(()=>{
      this.langReady= true;
    });
  }

And in my template, I'll set an *ngIf that waits until the language is ready to be displayed as follow:

<p *ngIf="timeElapsed">{{'things' | translate:"{ count: 1 }"}}</p>

This is not a very elegant solution but it works. Have you found a better way of setting up the message compiler?