问:
Unexpected output from URLEncoder in Java
I am trying to encode a URL parameter.

For example when I am encoding

qOddENxeLxL+13drGKYUgA==\n

using URL Encoder tool

It gives the following output which works when I request API

qOddENxeLxL%2B13drGKYUgA%3D%3D%5Cn

But when I am encoding URL from my Java code (Android) using URLEncoder.encode("qOddENxeLxL+13drGKYUgA==\n", "UTF-8");

It gives me the following result

qOddENxeLxL%252B13drGKYUgA%253D%253D%250A

I tried using other Encoding schemes too but could not produce the same result.

答:
Figured out the issue, here string was getting encoded two times.

While passing parameter to Retrofit call it is getting encoded automatically by retrofit and I was passing encoded parameter to retrofit so it got encoded again.

BTW thanks for the explanations. :)


来源: stackexchange

问:
How to respond via an JsonResult from Asp.Net Core middleware?
I would like to respond via a JsonResult from a piece of Asp.Net Core middleware but it's not obvious how to accomplish that.  I have googled around alot but with little success.  I can respond via a JsonResult from a global IActionFilter by setting the ActionExecutedContext.Result to the JsonResult and that's cool.  But in this case I want to effectively return a JsonResult from my middleware.  How can that be accomplished?

I framed the question with regard to the JsonResult IActionResult but ideally the solution would work for using any IActionResult to write the response from the middleware.

答:
Middleware is a really low-level component of ASP.NET Core. Writing out JSON (efficiently) is implemented in the MVC repository. Specifically, in the JSON formatters component.

It basically boils down to writing JSON on the response stream. In its simplest form, it can be implemented in middleware like this:

```<code>using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

// ...

public async Task Invoke(HttpContext context)
{
    var result = new SomeResultObject();
    var json = JsonConvert.SerializeObject(result);
    await context.Response.WriteAsync(json);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Middleware is a really low-level component of ASP.NET Core. Writing out JSON (efficiently) is implemented in the MVC repository. Specifically, in the JSON formatters component.

It basically boils down to writing JSON on the response stream. In its simplest form, it can be implemented in middleware like this:

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

// ...

public async Task Invoke(HttpContext context)
{
    var result = new SomeResultObject();
    var json = JsonConvert.SerializeObject(result);
    await context.Response.WriteAsync(json);
}


问:
spark-How can I retrieve item-pair after calculating similarity using RowMatrix
I have encountered the "all-pairs similarity" problem in my recommendation system. Thanks to this databricks blog, it seems RowMatrix may come to help.

However, RowMatrix is a matrix type without meaningful row indices, thereby I don't know how to retrieve the similarity result after invoking columnSimilarities(threshold) for specific item i and j

Below is some details about what I am doing:

1) My data file comes from Movielens with format like this:

```<code>user::item::rating
</code>```

2) I build up a RowMatrix in which each sparse vector i represents the ratings of all users to this item i

```<code>val dataPath = ...
val ratings: RDD[Rating] = sc.textFile(dataPath).map(_.split("::") match {
  case Array(user, item, rate) => Rating(user.toInt, item.toInt, rate.toDouble)
})
val rows = ratings.map(rating=>(rating.product, (rating.user, rating.rating)))
  .groupByKey()
  .map(p => Vectors.sparse(userAmount, p._2.map(r=>(r._1-1, r._2)).toSeq))

val mat = new RowMatrix(rows)

val similarities = mat.columnSimilarities(0.5)
</code>```

Now I get a CoordinateMatrix similarities. How can I get the similarity of specific item i and j? Although it can be used to retrieve a RDD[MatrixEntry], I am not sure whether the row i and column j correspond to item i and j.

答: If threshold is not so desirable in your case, you can use columnSimilarities on IndexedRowMatrix. That works for me very well. In this way, you have a better way to manage the row indices. </p>

Body:
I have encountered the "all-pairs similarity" problem in my recommendation system. Thanks to this databricks blog, it seems RowMatrix may come to help.

However, RowMatrix is a matrix type without meaningful row indices, thereby I don't know how to retrieve the similarity result after invoking columnSimilarities(threshold) for specific item i and j

Below is some details about what I am doing:

1) My data file comes from Movielens with format like this:

user::item::rating

2) I build up a RowMatrix in which each sparse vector i represents the ratings of all users to this item i

val dataPath = ...
val ratings: RDD[Rating] = sc.textFile(dataPath).map(_.split("::") match {
  case Array(user, item, rate) => Rating(user.toInt, item.toInt, rate.toDouble)
})
val rows = ratings.map(rating=>(rating.product, (rating.user, rating.rating)))
  .groupByKey()
  .map(p => Vectors.sparse(userAmount, p._2.map(r=>(r._1-1, r._2)).toSeq))

val mat = new RowMatrix(rows)

val similarities = mat.columnSimilarities(0.5)

Now I get a CoordinateMatrix similarities. How can I get the similarity of specific item i and j? Although it can be used to retrieve a RDD[MatrixEntry], I am not sure whether the row i and column j correspond to item i and j.


问:
convert string to date object give sunday web, GMT 00+ time i need in date formate dd/mm/yyyy
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is </p>

```<code> String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
</code>```

<p>I need same formate in date object not string . </p>

答:
You need to format it again after parsing

```<code>new SimpleDateFormat("yyyy/dd/MM").format(date);
</code>```

Body:
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is

 String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }

I need same formate in date object not string .

Body:
You need to format it again after parsing

new SimpleDateFormat("yyyy/dd/MM").format(date);


问:
How to understand linear partitioning in dynamic programming
a couple days ago I learned about linear partitioning problem, here is my code for it, is this code right and I don't understand the formula behind it, why is it like that, if you are able please explain me why the formula works.

```<code>for(int i=1;i<=n;i++) {
    rsq[i]=rsq[i-1]+arr[i];
}

int dp[n+1][k+1];
for(int i=0;i<=n;i++) {
    for(int j=0;j<=k;j++) {
        dp[i][j]=987654321;
    }
}
dp[0][0]=0;
for(int i=1;i<=n;i++) {
    dp[i][1]=rsq[i];
}
for(int i=1;i<=k;i++) {
    dp[1][i]=arr[1];
}

for(int i=2;i<=n;i++) {
    for(int j=2;j<=k;j++) {
        for(int x=1;x<i;x++) {
            int s=max(dp[x][j-1], rsq[i]-rsq[x]);
            if(dp[i][j]>s) dp[i][j]=s;
        }
    }
}
cout<<dp[n][k];
</code>```

Thanks in advance.

答:
Following this explanation, apparently the semantics of the state space dp as follows; apparently arr contains the sizes of the items to process and rsq contains the partial sums needed below to circumvent their recalculation.

```<code>dp[i][j] = minimum possible cost over all partitions of
           arr[1],...arr[i] into j ranges
           where i in {1,...,n} and j in {1,...k} or positive
           infinity if such a partition does not exist
</code>```

Apparently in the implementation 987654321 is used to model the value of positive infinity. Note that in the explanation, the axes of the state space are exchanged compared to the implementation in the original question. Based on this definition, we obtain the following recurrence relation for the values of the states.

```<code>dp[i,j] = min{ max{ dp[i-1,j'], sum_{i'=j'+1}^{n} arr[i']} : j' in {1,...,j} }
</code>```

In the implementation, the sum above is precalculated in rsq. The recurrence relation can be interpreted as follows. Given all values of dp[i-1][*] for some specific value of i (which means that all cost values for items 1 up to i-1 are known), all values dp[i][*] (for items 1 up to i) can be obtained by taking all items from j'+1 to n' (j' ranges from j to j, all possibilies are considered) and summing up the remainig items (which then consitute a partition); for the optimal partition of the first items, the precalculated value is used. The maximum of these values is the cost of the choice.

Intuitively, this can be seen as partitioning the items arr[1],...,arr[n] at an arbitrary split point. The items to the right are considered as one partition (the cost of which is the sum of their members, as they are placed together into one partition), the items to the left are recursively partitioned optimally into one partition less. The dynamic programming algorithm (besides the precalculation of the partial sums) initializes some base cases which corrspond to placing every item in a single partition and organizes the order of evaluation of the states in such a way that all values needed for the next larger value j of the second axis are always calculated when needed.

Body:
a couple days ago I learned about linear partitioning problem, here is my code for it, is this code right and I don't understand the formula behind it, why is it like that, if you are able please explain me why the formula works.

for(int i=1;i<=n;i++) {
    rsq[i]=rsq[i-1]+arr[i];
}

int dp[n+1][k+1];
for(int i=0;i<=n;i++) {
    for(int j=0;j<=k;j++) {
        dp[i][j]=987654321;
    }
}
dp[0][0]=0;
for(int i=1;i<=n;i++) {
    dp[i][1]=rsq[i];
}
for(int i=1;i<=k;i++) {
    dp[1][i]=arr[1];
}

for(int i=2;i<=n;i++) {
    for(int j=2;j<=k;j++) {
        for(int x=1;xs) dp[i][j]=s;
        }
    }
}
cout<<dp[n][k];

Thanks in advance.

Body:
Following this explanation, apparently the semantics of the state space dp as follows; apparently arr contains the sizes of the items to process and rsq contains the partial sums needed below to circumvent their recalculation.

dp[i][j] = minimum possible cost over all partitions of
           arr[1],...arr[i] into j ranges
           where i in {1,...,n} and j in {1,...k} or positive
           infinity if such a partition does not exist

Apparently in the implementation 987654321 is used to model the value of positive infinity. Note that in the explanation, the axes of the state space are exchanged compared to the implementation in the original question. Based on this definition, we obtain the following recurrence relation for the values of the states.

dp[i,j] = min{ max{ dp[i-1,j'], sum_{i'=j'+1}^{n} arr[i']} : j' in {1,...,j} }

In the implementation, the sum above is precalculated in rsq. The recurrence relation can be interpreted as follows. Given all values of dp[i-1][*] for some specific value of i (which means that all cost values for items 1 up to i-1 are known), all values dp[i][*] (for items 1 up to i) can be obtained by taking all items from j'+1 to n' (j' ranges from j to j, all possibilies are considered) and summing up the remainig items (which then consitute a partition); for the optimal partition of the first items, the precalculated value is used. The maximum of these values is the cost of the choice.

Intuitively, this can be seen as partitioning the items arr[1],...,arr[n] at an arbitrary split point. The items to the right are considered as one partition (the cost of which is the sum of their members, as they are placed together into one partition), the items to the left are recursively partitioned optimally into one partition less. The dynamic programming algorithm (besides the precalculation of the partial sums) initializes some base cases which corrspond to placing every item in a single partition and organizes the order of evaluation of the states in such a way that all values needed for the next larger value j of the second axis are always calculated when needed.


问:
Stop/Start Kafka Consumer/Producer Stream in Local Execution Mode
Setup:

Java 8

Flink 1.2 (Mac OSX)

Kafka 0.10.0 (VirtualBox/Ubuntu)

FlinkKafkaConsumer010

FlinkKafkaProducer010

Created a simple example program to consume 1M message from one Kafka topic and produce to another - running in local execution mode.  Both topics have 32 partitions.

When I let run from start to finish, it consumes and produces all message.  If I start and then stop (SIGINT) before it is completed, then restart again the producer only receives a subset of the original 1M messages.

I have confirmed my offsets for the consumer and it read all 1M messages.

```<code>final StreamExecutionEnvironment env =
    StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(32);
env.enableCheckpointing(1000L, CheckpointingMode.EXACTLY_ONCE);
</code>```

--

```<code>producer.setFlushOnCheckpoint(true);
producer.setLogFailuresOnly(false);
</code>```

In local execution mode is this expected?  Do I need to enable savepoints to stop and restart a stream job?  I appears the producer is not committing all the messages when this happens.

Thanks in advance!

答:
First of all, on subsequent runs, it only receives a subset of the messages because the FlinkKafkaConsumer is using the committed offsets in Kafka as the starting positions. Currently, the only way to avoid this right now in the releases (up to 1.2.0 as of now) is to always assign a new group.id. In the next release, there will be new options for this: https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/connectors/kafka.html#kafka-consumers-start-position-configuration.

As a side note, please also note that the committed offsets in Kafka are not used at all for the exactly-once processing guarantees in Flink. Flink only relies on the checkpointed offsets for that. More details on this can be found in the Flink Kafka connector docs in the link above.

Body:
Setup:

Java 8

Flink 1.2 (Mac OSX)

Kafka 0.10.0 (VirtualBox/Ubuntu)

FlinkKafkaConsumer010

FlinkKafkaProducer010

Created a simple example program to consume 1M message from one Kafka topic and produce to another - running in local execution mode.  Both topics have 32 partitions.

When I let run from start to finish, it consumes and produces all message.  If I start and then stop (SIGINT) before it is completed, then restart again the producer only receives a subset of the original 1M messages.

I have confirmed my offsets for the consumer and it read all 1M messages.

final StreamExecutionEnvironment env =
    StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(32);
env.enableCheckpointing(1000L, CheckpointingMode.EXACTLY_ONCE);

--

producer.setFlushOnCheckpoint(true);
producer.setLogFailuresOnly(false);

In local execution mode is this expected?  Do I need to enable savepoints to stop and restart a stream job?  I appears the producer is not committing all the messages when this happens.

Thanks in advance!


问:
converting sql to Django ORM
How to convert this SQL to Django ORM

```<code>SELECT
  `table1`.*,
  `tabl2`.*
FROM `table1`
INNER JOIN `table2` ON (`table1`.`table2_id` = `table2`.`id`)
INNER JOIN
(SELECT
   table2_id,
   MAX(date) AS max_date
FROM table1
WHERE date <= CURRENT_DATE
GROUP BY table2_id) grouped
  ON table1.table2_id = grouped.table2_id
     AND table1.date = grouped.max_date
WHERE `table1`.`table2_id` IN (73, 74)
ORDER BY `table1`.`date` ASC
</code>```

I tried with annotate, but unsuccessful

答:
Simply, you need to have the models defined for the tables i.e. 'table1' and 'table2' - the point of using ORM is define your tables as models (once for all) and make queries with ease.

If you have schema defined, translate it into Django models (all the fields). And, if you already have the DB setup, use the inspectdb command to auto-generate the models from a DB.

You can generate models for specific DB tables - inspectdb.

inspectdb

django-admin inspectdb [table [table ...]]

Introspects the database
  tables in the database pointed-to by the NAME setting and outputs a
  Django model module (a models.py file) to standard output. You may
  choose what tables to inspect by passing their names as arguments.

Use this if you have a legacy database with which you’d like to use
  Django. The script will inspect the database and create a model for
  each table within it.

As you might expect, the created models will have an attribute for
  every field in the table. Note that inspectdb has a few special cases
  in its field-name output:

If inspectdb cannot map a column’s type to a model field type, it’ll
  use TextField and will insert the Python comment 'This field type is a
  guess.' next to the field in the generated model.

If the database
  column name is a Python reserved word (such as 'pass', 'class' or
  'for'), inspectdb will append '_field' to the attribute name. For
  example, if a table has a column 'for', the generated model will have
  a field 'for_field', with the db_column attribute set to 'for'.
  inspectdb will insert the Python comment 'Field renamed because it was
  a Python reserved word.' next to the field.

But you must manually verify the auto-generated models:

This feature is meant as a shortcut, not as definitive model
  generation. After you run it, you’ll want to look over the generated
  models yourself to make customizations. In particular, you’ll need to
  rearrange models’ order, so that models that refer to other models are
  ordered properly.

Title: converting sql to Django ORM

Body:
How to convert this SQL to Django ORM

SELECT
  `table1`.*,
  `tabl2`.*
FROM `table1`
INNER JOIN `table2` ON (`table1`.`table2_id` = `table2`.`id`)
INNER JOIN
(SELECT
   table2_id,
   MAX(date) AS max_date
FROM table1
WHERE date <= CURRENT_DATE
GROUP BY table2_id) grouped
  ON table1.table2_id = grouped.table2_id
     AND table1.date = grouped.max_date
WHERE `table1`.`table2_id` IN (73, 74)
ORDER BY `table1`.`date` ASC

I tried with annotate, but unsuccessful


问:
punctuation marks in javascript
can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...</p>

```<code>function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,”/”);
  imgname = imgname.replace(/\’/g,”\\’”);
  content = “<img src=\”" + String(imgname) + “\” border=\”0\” height=\”150\” weight=\”150\”>”;
  eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
  document.getElementById.imagepreview.style.visibility =’visible’;
}
</code>```

答: You seem to use wrong quote characters (” or ‘). Replace them with " or ' and you'll be good. Use an ascii text editor, not a word processor for typing.

ContentLicense: CC BY-SA 2.5

Title: punctuation marks in javascript

Body:
can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...

function showLocalImage(imgname) {
  imgname = imgname.replace(/\\/g,”/”);
  imgname = imgname.replace(/\’/g,”\\’”);
  content = “”;
  eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
  document.getElementById.imagepreview.style.visibility =’visible’;
}


问:
DBF file parallel reading
A foxpro software reads , writes and updates records in a DBF file. I parallely read that same DBF in a c++ application. Will there be any issues if I keep my c++ applications reading DBF file for a long time ?</p>

答:
Yes, the DBF format is multi-user -- nearly every real-world application that uses them is multi-user; we have apps used by hundreds of users for example.

There may be a problem in that your C++ application does not respect the locking mechanism that FoxPro would use, but that's not the same thing. If you use Microsoft Visual FoxPro OLEDB driver properly on the C++ side you won't have an issue, but yes as with anything like this open and close the DBF as quickly as you can.

Title: DBF file parallel reading

ContentLicense: CC BY-SA 4.0


问:
Can't get QSslSocket to work
I'm attempting to write a simple client-server application in Qt that would comunicate over SSL. I tried using QSslSockets, but I keep having variuos problems.

Take a look at this:

Client:

```<code>#define dumpvar(x) qDebug()<<#x<<'='<<x

int main(int argc, char** argv)
{
    QApplication a(argc, argv);

    QSslSocket s;
    auto cert = QSslCertificate::fromPath("/home/piotrek/cert.pem");
    Q_ASSERT(!cert.isEmpty());
    s.setCaCertificates({cert});
    s.connectToHostEncrypted("localhost", 1234);
    qDebug()<<"waiting for encrypted";
    if (!s.waitForEncrypted(10000)){
        dumpvar(s.errorString());
        dumpvar(s.sslErrors());
        return 0;
    }

    qDebug()<<"client connected";
}
</code>```

Server:

```<code>#define dumpvar(x) qDebug()<<#x<<'='<<x

class SslServer: public QTcpServer
{
    // QTcpServer interface
protected:
    void incomingConnection(qintptr handle) override
    {
        QSslSocket s;
        if (!s.setSocketDescriptor(handle)){
            dumpvar(s.errorString());
            return;
        }
        s.setLocalCertificate("/home/piotrek/cert.pem");
        s.setPrivateKey("/home/piotrek/pkey.pem", QSsl::Rsa, QSsl::Pem, "test");
        s.startServerEncryption();
        qDebug()<<"waiting for encrypted";
        if(!s.waitForEncrypted(10000)){
            dumpvar(s.errorString());
            dumpvar(s.sslErrors());
            return;
        }

        qDebug()<<"server encrypted";

        handleConnection(&s);
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    SslServer s;

    s.listen(QHostAddress::Any, 1234);
    return a.exec();
}
</code>```

The client prints:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
<10 second pause>
s.errorString() = "Network operation timed out"
s.sslErrors() = ()
</code>```

The server prints:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
<10 second pause>
s.errorString() = "The remote host closed the connection"
s.sslErrors() = (
</code>```

What am I doing wrong?

答:
Explanation for the warnings is that OpenSSL in Ubuntu is compiled without insecure sslv2 but Qt 5.8 tries to load those functions in runtime. Qt uses only secure protocols by default so these warnings don't affect you unless you explicitly call QSslSocket::setProtocol with QSsl::SslV2 (which of course doesn't work with your openssl).

Obviously something is wrong with your self-signed? certificate. Also, connection would fail anyway with self-signed certificate unless hostname mismatch is ignored explicitly.

In case, you are using self-signed certificates you could re-generate them with the instructions found here.

Please, find below the working code example. Tested on similar environment (surprise!) Ubuntu 16.10, OpenSSL 1.0.2g 1 Mar 2016, Qt 5.8.0.

Server

```<code>class SslServer: public QTcpServer
{
    // QTcpServer interface
protected:
    void incomingConnection(qintptr handle) override
    {
        QSslSocket s;
        if (!s.setSocketDescriptor(handle)){
            dumpvar(s.errorString());
            return;
        }
        const QString serverCertPath("/path/to/server1.pem");
        const QString serverKeyPath("/path/to/server1.key");
        s.setLocalCertificate(serverCertPath);
        s.setPrivateKey(serverKeyPath, QSsl::Rsa, QSsl::Pem, "test");
        s.startServerEncryption();
        qDebug()<<"waiting for encrypted";
        if(!s.waitForEncrypted(10000)){
            dumpvar(s.errorString());
            dumpvar(s.sslErrors());
            return;
        }
        qDebug()<<"server encrypted";
        s.write("Hello client");
        s.flush();
        s.waitForBytesWritten(3000);
        s.close();
    }
};
</code>```

Client

```<code>int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);

    QSslSocket s;
    const QString rootCAPath("/path/to/rootCA.pem");
    auto rootCACert = QSslCertificate::fromPath(rootCAPath);
    Q_ASSERT(!rootCACert.isEmpty());
    s.setCaCertificates(rootCACert);

    // ignore SSL host name mismatch error for server certificate
    QList<QSslError> errorsToIgnore;
    const QString serverCertPath("/path/to/server1.pem");
    auto serverCert = QSslCertificate::fromPath(serverCertPath);
    Q_ASSERT(!serverCert.isEmpty());
    errorsToIgnore<<QSslError(QSslError::HostNameMismatch, serverCert.at(0));
    s.ignoreSslErrors(errorsToIgnore);

    s.connectToHostEncrypted("localhost", 1234);
    qDebug()<<"waiting for encrypted";
    if (!s.waitForEncrypted(10000)){
        dumpvar(s.errorString());
        dumpvar(s.sslErrors());
        return 0;
    }
    qDebug()<<"client connected";
    s.waitForReadyRead(3000);
    qDebug() << "Reading: " << s.bytesAvailable();
    qDebug() << s.readAll();
    s.close();
}
</code>```

Server output:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
server encrypted
</code>```

Client output:

```<code>qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
client connected
Reading:  12
"Hello client"
Press <RETURN> to close this window...
</code>```

Title: Can't get QSslSocket to work

Body:
I'm attempting to write a simple client-server application in Qt that would comunicate over SSL. I tried using QSslSockets, but I keep having variuos problems.

Take a look at this:

Client:

#define dumpvar(x) qDebug()<<#x<<'='<<x

int main(int argc, char** argv)
{
    QApplication a(argc, argv);

    QSslSocket s;
    auto cert = QSslCertificate::fromPath("/home/piotrek/cert.pem");
    Q_ASSERT(!cert.isEmpty());
    s.setCaCertificates({cert});
    s.connectToHostEncrypted("localhost", 1234);
    qDebug()<<"waiting for encrypted";
    if (!s.waitForEncrypted(10000)){
        dumpvar(s.errorString());
        dumpvar(s.sslErrors());
        return 0;
    }

    qDebug()<<"client connected";
}

Server:

#define dumpvar(x) qDebug()<<#x<<'='<<x

class SslServer: public QTcpServer
{
    // QTcpServer interface
protected:
    void incomingConnection(qintptr handle) override
    {
        QSslSocket s;
        if (!s.setSocketDescriptor(handle)){
            dumpvar(s.errorString());
            return;
        }
        s.setLocalCertificate("/home/piotrek/cert.pem");
        s.setPrivateKey("/home/piotrek/pkey.pem", QSsl::Rsa, QSsl::Pem, "test");
        s.startServerEncryption();
        qDebug()<<"waiting for encrypted";
        if(!s.waitForEncrypted(10000)){
            dumpvar(s.errorString());
            dumpvar(s.sslErrors());
            return;
        }

        qDebug()<<"server encrypted";

        handleConnection(&s);
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    SslServer s;

    s.listen(QHostAddress::Any, 1234);
    return a.exec();
}

The client prints:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
<10 second pause>
s.errorString() = "Network operation timed out"
s.sslErrors() = ()

The server prints:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
<10 second pause>
s.errorString() = "The remote host closed the connection"
s.sslErrors() = (

What am I doing wrong?

Body:
Explanation for the warnings is that OpenSSL in Ubuntu is compiled without insecure sslv2 but Qt 5.8 tries to load those functions in runtime. Qt uses only secure protocols by default so these warnings don't affect you unless you explicitly call QSslSocket::setProtocol with QSsl::SslV2 (which of course doesn't work with your openssl).

Obviously something is wrong with your self-signed? certificate. Also, connection would fail anyway with self-signed certificate unless hostname mismatch is ignored explicitly.

In case, you are using self-signed certificates you could re-generate them with the instructions found here.

Please, find below the working code example. Tested on similar environment (surprise!) Ubuntu 16.10, OpenSSL 1.0.2g 1 Mar 2016, Qt 5.8.0.

Server

class SslServer: public QTcpServer
{
    // QTcpServer interface
protected:
    void incomingConnection(qintptr handle) override
    {
        QSslSocket s;
        if (!s.setSocketDescriptor(handle)){
            dumpvar(s.errorString());
            return;
        }
        const QString serverCertPath("/path/to/server1.pem");
        const QString serverKeyPath("/path/to/server1.key");
        s.setLocalCertificate(serverCertPath);
        s.setPrivateKey(serverKeyPath, QSsl::Rsa, QSsl::Pem, "test");
        s.startServerEncryption();
        qDebug()<<"waiting for encrypted";
        if(!s.waitForEncrypted(10000)){
            dumpvar(s.errorString());
            dumpvar(s.sslErrors());
            return;
        }
        qDebug()<<"server encrypted";
        s.write("Hello client");
        s.flush();
        s.waitForBytesWritten(3000);
        s.close();
    }
};

Client

int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);

    QSslSocket s;
    const QString rootCAPath("/path/to/rootCA.pem");
    auto rootCACert = QSslCertificate::fromPath(rootCAPath);
    Q_ASSERT(!rootCACert.isEmpty());
    s.setCaCertificates(rootCACert);

    // ignore SSL host name mismatch error for server certificate
    QList<QSslError> errorsToIgnore;
    const QString serverCertPath("/path/to/server1.pem");
    auto serverCert = QSslCertificate::fromPath(serverCertPath);
    Q_ASSERT(!serverCert.isEmpty());
    errorsToIgnore<<QSslError(QSslError::HostNameMismatch, serverCert.at(0));
    s.ignoreSslErrors(errorsToIgnore);

    s.connectToHostEncrypted("localhost", 1234);
    qDebug()<<"waiting for encrypted";
    if (!s.waitForEncrypted(10000)){
        dumpvar(s.errorString());
        dumpvar(s.sslErrors());
        return 0;
    }
    qDebug()<<"client connected";
    s.waitForReadyRead(3000);
    qDebug() << "Reading: " << s.bytesAvailable();
    qDebug() << s.readAll();
    s.close();
}

Server output:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
server encrypted

Client output:

qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
waiting for encrypted
client connected
Reading:  12
"Hello client"
Press <RETURN> to close this window...


问:
How to detect a mobile device using jQuery
Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the browser is on a handheld device.

The jQuery $.browser function is not what I am looking for.

答:
I would be suggesting to use following combo of strings, to check if device type being used.

As per Mozilla documentation string Mobi is recommended. But, some of the old tablets doesn't return true if only Mobi is used, hence we should use Tablet string too.

Similarly, for being on the safe side iPad and iPhone strings could also be used to check the device type.

Most of the new devices would return true for Mobi string alone.

```<code>if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
    // do something
}
</code>```

Body:
I would be suggesting to use following combo of strings, to check if device type being used.

As per Mozilla documentation string Mobi is recommended. But, some of the old tablets doesn't return true if only Mobi is used, hence we should use Tablet string too.

Similarly, for being on the safe side iPad and iPhone strings could also be used to check the device type.

Most of the new devices would return true for Mobi string alone.

if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
    // do something
}


问:
What pattern is this using?
In order to add some behavior into onScroll event of ListView，I added some code by subclass ListView like this:

```<code>class MyListView extends ListView{
      public void setOnScrollListener(OnScrollListener listener){
            final OnScrollListener lis = new OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listener.onScrollStateChanged(view, scrollState);
                //below is added behavior of my Listview
                }
            }

        super.setOnScrollListener(lis);
      }
}
</code>```

and the usage of it is simple:

```<code>MyListView myList = new MyListView(...);
myList.setOnScrollListener(new OnScrollListener(){...});//here is the old logic
</code>```

this sounds like Decorator pattern but it is not, because there is no composite but only inheritance(in facto I do not need composite here).

So the problem is what should I call it?

答:
It is simply OOP concept which extends ListView class to acquire its functionality and can not be considered as Decorator Design Pattern.

We use Decorator design pattern to add/modify functionality of an object at run time.

Decorator design pattern consists of four component namely:

1. Component Interface

Example

```<code>   public interface Car
   {
      public void assemble();
   }
</code>```

2. Component Implementation

Example

```<code>public class BasicCar implements Car
{
    @Override
    public void assemble()
    {
       System.out.print("Basic Car.");
    }
}
</code>```

3. Decorator

Example

```<code>public class CarDecorator implements Car
{
    protected Car car;
    public CarDecorator(Car c)
    {
        this.car=c;
    }

    @Override
    public void assemble()
    {
         this.car.assemble();
    }
}
</code>```

3. Concrete Decorator

Example

```<code> // Adding feature at runtime using decorator pattern to SportsCar
 public class SportsCar extends CarDecorator
 {
      public SportsCar(Car c)
      {
          super(c);
      }

       @Override
       public void assemble()
       {
          car.assemble();
           System.out.print(" Adding features of Sports Car.");
       }
 }

 // Adding feature at runtime using decorator pattern to LuxuaryCar
 public class LuxuaryCar extends CarDecorator
 {
      public LuxuaryCar(Car c)
      {
          super(c);
      }

       @Override
       public void assemble()
       {
          car.assemble();
           System.out.print(" Adding features of Luxuary Car.");
       }
 }
</code>```

How to use it?

```<code>Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();
</code>```

In above we are adding Sports car feature to BasicCar at runtime using Decorator Design Pattern

Title: What pattern is this using?

Body:
In order to add some behavior into onScroll event of ListView，I added some code by subclass ListView like this:

class MyListView extends ListView{
      public void setOnScrollListener(OnScrollListener listener){
            final OnScrollListener lis = new OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listener.onScrollStateChanged(view, scrollState);
                //below is added behavior of my Listview
                }
            }

        super.setOnScrollListener(lis);
      }
}

and the usage of it is simple:

MyListView myList = new MyListView(...);
myList.setOnScrollListener(new OnScrollListener(){...});//here is the old logic

this sounds like Decorator pattern but it is not, because there is no composite but only inheritance(in facto I do not need composite here).

So the problem is what should I call it?

Body:
It is simply OOP concept which extends ListView class to acquire its functionality and can not be considered as Decorator Design Pattern.

We use Decorator design pattern to add/modify functionality of an object at run time.

Decorator design pattern consists of four component namely:

1. Component Interface

Example

   public interface Car
   {
      public void assemble();
   }

2. Component Implementation

Example

public class BasicCar implements Car
{
    @Override
    public void assemble()
    {
       System.out.print("Basic Car.");
    }
}

3. Decorator

Example

public class CarDecorator implements Car
{
    protected Car car;
    public CarDecorator(Car c)
    {
        this.car=c;
    }

    @Override
    public void assemble()
    {
         this.car.assemble();
    }
}

3. Concrete Decorator

Example

 // Adding feature at runtime using decorator pattern to SportsCar
 public class SportsCar extends CarDecorator
 {
      public SportsCar(Car c)
      {
          super(c);
      }

       @Override
       public void assemble()
       {
          car.assemble();
           System.out.print(" Adding features of Sports Car.");
       }
 }

 // Adding feature at runtime using decorator pattern to LuxuaryCar
 public class LuxuaryCar extends CarDecorator
 {
      public LuxuaryCar(Car c)
      {
          super(c);
      }

       @Override
       public void assemble()
       {
          car.assemble();
           System.out.print(" Adding features of Luxuary Car.");
       }
 }

How to use it?

Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();

In above we are adding Sports car feature to BasicCar at runtime using Decorator Design Pattern


问:
How can I refresh the activity?
I want to refresh the activity as i want thatwithout firing any event some work gets performed and activity calls  by itself. So, i want to know is there any option in android to refresh the activity by itself.</p>

答:
You can do this by yourself through a Handler on which you call postDelayed(..)

http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long)

Put this in your class:

```<code>private final Handler handler = new Handler();
</code>```

make a function called: doTheAutoRefresh() that does:

```<code>private void doTheAutoRefresh() {
    handler.postDelayed(new Runnable() {
             @Override
             public void run() {
                 doRefreshingStuff(); // this is where you put your refresh code
                 doTheAutoRefresh();
             }
         }, 1000);
}
</code>```

Call this function in your onCreate.

NOTE: this is the basic approach. consider stopping this after onPause has been called and to resume it after onResume. Look at the handler class to see how to remove.

Title: How can I refresh the activity?

Body:
You can do this by yourself through a Handler on which you call postDelayed(..)

http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long)

Put this in your class:

private final Handler handler = new Handler();

make a function called: doTheAutoRefresh() that does:

private void doTheAutoRefresh() {
    handler.postDelayed(new Runnable() {
             @Override
             public void run() {
                 doRefreshingStuff(); // this is where you put your refresh code
                 doTheAutoRefresh();
             }
         }, 1000);
}

Call this function in your onCreate.

NOTE: this is the basic approach. consider stopping this after onPause has been called and to resume it after onResume. Look at the handler class to see how to remove.


问:
unable to generate automail on daily bases
I am unable to generate auto mail on daily bases. The issue is it is not able to generate it automatically. Where as i have a same sort of code which does generates it everyday. With all the same details. The code is exactly same except the database query.

Here is my code:

```<code>    <?php
session_start();
require("../connect.php");

/* require files for MAIL */
require("class.phpmailer.php");
require("class.smtp.php");
/* require files for MAIL ENDS */

/******** Get the list of audits done in week risk category falls under High Risk and during the previous visit also the location was under High risk category ----mail on every Saturday**********/

    $current_date = date('Y-m-d');
    //$current_date ='2015-08-22';;
    /*$start_time = time() - (6*86400);
    $start_dt = date('Y-m-d',$start_time);*/

      $pagent_array = array();
     $query="Select * from `location_details` ld
    Left Join `answer_general_qc` ans_general on ans_general.lid=ld.id
    Left Join `audit_general` general on general.qtno = ans_general.qt
    Left Join `audit_general_option` general_opt on general_opt.opt_id = ans_general.ans_remark
    where ld.completed ='1' and ld.priority != 'qc' and general.qtno ='1' and ans_general.opt = 'no'  and
    STR_TO_DATE(ld.`date_audited`,'%d-%m-%Y') = '".$current_date."'";
    $result=mysql_query($query);

    $th_style="border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #dedede";
    $td_style="border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #ffffff";
    $table_result .="<table  align='center' rules='all' style='font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #666666;border-collapse: collapse;' border='1';>
            <thead>
            <tr>
            <th style='".$th_style."'>Sr No</th>
            <th style='".$th_style."'>Location Code</th>
            <th style='".$th_style."'>Location Name</th>
            <th style='".$th_style."'>PAgent</th>
            <th style='".$th_style."'>Address 1</th>
            <th style='".$th_style."'>Address 2</th>
            <th style='".$th_style."'>District</th>
            <th style='".$th_style."'>State</th>
            <th style='".$th_style."'>Priority</th>
            <th style='".$th_style."'>Remark by TO</th>
            <th style='".$th_style."'>Remark by TO</th>
            </tr>
            </thead>
            <tbody>";
            $sr_no=1;
    if(mysql_num_rows($result) != 0)
    {
    while($row=mysql_fetch_array($result))
    {

            if($row['option_text'] == "")
            {
              $option_text="Other";
            }
            else
            {
              $option_text=$row['option_text'];
            }
            $table_result .= "
            <tr>
            <td style='".$td_style."'>".$sr_no."</td>
            <td style='".$td_style."'>".$row['location']."</td>
            <td style='".$td_style."'>".$row['agent']."</td>
            <td style='".$td_style."'>".$row['pagent']."</td>
            <td style='".$td_style."'>".$row['address1']."</td>
            <td style='".$td_style."'>".$row['address2']."</td>
            <td style='".$td_style."'>".$row['district']."</td>
            <td style='".$td_style."'>".$row['state']."</td>
            <td style='".$td_style."'>".$row['priority']."</td>
            <td style='".$td_style."'>".$option_text."</td>
            <td style='".$td_style."'>".$row['qc_remark']."</td>
            </tr>";
            $sr_no++;
    }
    }
    else
    {
     $table_result .="<tr><td colspan='9' align='center'>No Locations Found</td></tr>";
    }
     $table_result .="</tbody>
                     </table>";

    //  echo $table_result;     exit;

        /* Code to send MAIL */
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Host = "host";

        $mail->SMTPAuth = true;
        //$mail->SMTPSecure = "ssl";
        $mail->Port = 25;
        $mail->Username = "Username";
        $mail->Password = "Password";

        $mail->From = "From";
        $mail->FromName = "Name";

        $mail->AddAddress("Email");

        $mail->AddBCC("Email CC");

        $body = "Dear All,<br /><br />For the review conducted on ".date('d-m-Y',strtotime($current_date))." in the following locations we have found deviation in question 1.1 (ie Does this location exist exactly at the address provided?) <br /><br /><br /><br />";
        $body .= $table_result;
        $body .= "<br /><br />Warm Regards <br /><br />

Note : Please do not reply to this email as this is an automated mail generated
";

        //end body

        $mail->IsHTML(true);
        //$mail->Subject = "Ref : RC1/HR/".strtoupper($pa)."/".date('F Y',(time()-(5*86400)));
        $mail->Subject = "Ref : Lrr 1.1 deviation";
        $mail->Body = $body;
        //$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

        if(!$mail->Send())
        {
            echo "Message could not be sent. <p>";
            echo "Mailer Error: " . $mail->ErrorInfo;
            exit;
        }

        /* Code to send MAIL Ends */

        //mail($to,$subject,$message,$headers);
        echo 'Mail sent to '.$pa.'<br /><br />';

    /****** END of sending mail **********/

?>
</code>```

答:
If you want to send mails on a regular or daily basis the ideal way to do that would be to use cron job for sending the mails.By using cron you can specify what application do you want the cron to run on.Also you will be able to specify what time exactly do you want the mail to be sent.
Refer here https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job .
Hope it helps. </p>

Body:
I am unable to generate auto mail on daily bases. The issue is it is not able to generate it automatically. Where as i have a same sort of code which does generates it everyday. With all the same details. The code is exactly same except the database query.

Here is my code:

    <?php
session_start();
require("../connect.php");

/* require files for MAIL */
require("class.phpmailer.php");
require("class.smtp.php");
/* require files for MAIL ENDS */

/******** Get the list of audits done in week risk category falls under High Risk and during the previous visit also the location was under High risk category ----mail on every Saturday**********/

    $current_date = date('Y-m-d');
    //$current_date ='2015-08-22';;
    /*$start_time = time() - (6*86400);
    $start_dt = date('Y-m-d',$start_time);*/

      $pagent_array = array();
     $query="Select * from `location_details` ld
    Left Join `answer_general_qc` ans_general on ans_general.lid=ld.id
    Left Join `audit_general` general on general.qtno = ans_general.qt
    Left Join `audit_general_option` general_opt on general_opt.opt_id = ans_general.ans_remark
    where ld.completed ='1' and ld.priority != 'qc' and general.qtno ='1' and ans_general.opt = 'no'  and
    STR_TO_DATE(ld.`date_audited`,'%d-%m-%Y') = '".$current_date."'";
    $result=mysql_query($query);

    $th_style="border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #dedede";
    $td_style="border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #ffffff";
    $table_result .="

            Sr No
            Location Code
            Location Name
            PAgent
            Address 1
            Address 2
            District
            State
            Priority
            Remark by TO
            Remark by TO

";
            $sr_no=1;
    if(mysql_num_rows($result) != 0)
    {
    while($row=mysql_fetch_array($result))
    {

            if($row['option_text'] == "")
            {
              $option_text="Other";
            }
            else
            {
              $option_text=$row['option_text'];
            }
            $table_result .= "

            ".$sr_no."
            ".$row['location']."
            ".$row['agent']."
            ".$row['pagent']."
            ".$row['address1']."
            ".$row['address2']."
            ".$row['district']."
            ".$row['state']."
            ".$row['priority']."
            ".$option_text."
            ".$row['qc_remark']."

";
            $sr_no++;
    }
    }
    else
    {
     $table_result .="
No Locations Found
";
    }
     $table_result .="

";

    //  echo $table_result;     exit;

        /* Code to send MAIL */
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Host = "host";

        $mail->SMTPAuth = true;
        //$mail->SMTPSecure = "ssl";
        $mail->Port = 25;
        $mail->Username = "Username";
        $mail->Password = "Password";

        $mail->From = "From";
        $mail->FromName = "Name";

        $mail->AddAddress("Email");

        $mail->AddBCC("Email CC");

        $body = "Dear All,

For the review conducted on ".date('d-m-Y',strtotime($current_date))." in the following locations we have found deviation in question 1.1 (ie Does this location exist exactly at the address provided?)

";
        $body .= $table_result;
        $body .= "

Warm Regards

Note : Please do not reply to this email as this is an automated mail generated
";

        //end body

        $mail->IsHTML(true);
        //$mail->Subject = "Ref : RC1/HR/".strtoupper($pa)."/".date('F Y',(time()-(5*86400)));
        $mail->Subject = "Ref : Lrr 1.1 deviation";
        $mail->Body = $body;
        //$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

        if(!$mail->Send())
        {
            echo "Message could not be sent.
";
            echo "Mailer Error: " . $mail->ErrorInfo;
            exit;
        }

        /* Code to send MAIL Ends */

        //mail($to,$subject,$message,$headers);
        echo 'Mail sent to '.$pa.'

';

    /****** END of sending mail **********/

?>


问:
SweetAlert prompt with two input fields
Currently working on a personal project. I want the user to click a button and a SweetAlert prompt would be presented for the user to verify their credential. However, the code I see on the SweetAlert website only allows one input field. Here is the code I have:

```<code>swal({
  title: "Authenicating for continuation",
  text: "Test",
  type: "input",
  showCancelButton: true,
  closeOnConfirm: false,
  animation: "slide-from-top",
  inputPlaceholder: "Write something"
}, function(inputValue) {
  if (inputValue === false) return false;
  if (inputValue === "") {
    swal.showInputError("You need to write something!");
    return false
  }
  // swal("Nice!", "You wrote: " + inputValue, "success");
});
</code>```

So, is there a way I can get two input fields? One input field for the password and the other input field for text.

答:
Now SweetAlert2 is available:
https://sweetalert2.github.io

As per their info on bottom:

Multiple inputs aren't supported, you can achieve them by using html
  and preConfirm parameters. Inside the preConfirm() function you can
  pass the custom result to the resolve() function as a parameter:

```<code>swal({
  title: 'Multiple inputs',
  html:
    '<input id="swal-input1" class="swal2-input">' +
    '<input id="swal-input2" class="swal2-input">',
  preConfirm: function () {
    return new Promise(function (resolve) {
      resolve([
        $('#swal-input1').val(),
        $('#swal-input2').val()
      ])
    })
  },
  onOpen: function () {
    $('#swal-input1').focus()
  }
}).then(function (result) {
  swal(JSON.stringify(result))
}).catch(swal.noop)
</code>```

Title: SweetAlert prompt with two input fields

Body:
Currently working on a personal project. I want the user to click a button and a SweetAlert prompt would be presented for the user to verify their credential. However, the code I see on the SweetAlert website only allows one input field. Here is the code I have:

swal({
  title: "Authenicating for continuation",
  text: "Test",
  type: "input",
  showCancelButton: true,
  closeOnConfirm: false,
  animation: "slide-from-top",
  inputPlaceholder: "Write something"
}, function(inputValue) {
  if (inputValue === false) return false;
  if (inputValue === "") {
    swal.showInputError("You need to write something!");
    return false
  }
  // swal("Nice!", "You wrote: " + inputValue, "success");
});

So, is there a way I can get two input fields? One input field for the password and the other input field for text.

Body:
Now SweetAlert2 is available:
https://sweetalert2.github.io

As per their info on bottom:

Multiple inputs aren't supported, you can achieve them by using html
  and preConfirm parameters. Inside the preConfirm() function you can
  pass the custom result to the resolve() function as a parameter:

swal({
  title: 'Multiple inputs',
  html:
    '<input id="swal-input1" class="swal2-input">' +
    '<input id="swal-input2" class="swal2-input">',
  preConfirm: function () {
    return new Promise(function (resolve) {
      resolve([
        $('#swal-input1').val(),
        $('#swal-input2').val()
      ])
    })
  },
  onOpen: function () {
    $('#swal-input1').focus()
  }
}).then(function (result) {
  swal(JSON.stringify(result))
}).catch(swal.noop)


问:
I want to use image upload box with hiding input field . when i hide the input field it can't work properly .. any suggesition?
i am less experienced plz help me out to resolve this problem . i want just image upload box by clicking on it input field work. thanks in advance

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#picker')
        .attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  max-width: 180px;
}

input[type=file] {
  padding: 0px;
  position: absolute;
  display: ;
  background: ;
}

.card-1 {
  width: 180px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}

.card-1:hover {
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
}</code>```

  <input type='file' onchange="readURL(this);" />

```

答:
You can call .click() on this.previousElementSibling.click() at onclick at  element that is next element sibling of <input type="file"> element.

Note file at input[type=file] should be surrounded by quotes at css input[type="file"].  Set display set to none at input[type="file"] element if element should not be displayed.

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#picker')
        .attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  max-width: 180px;
}

input[type="file"] {
  padding: 0px;
  position: absolute;
  display: none;
}

.card-1 {
  width: 180px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}

.card-1:hover {
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
}</code>```

  <input type='file' onchange="readURL(this);" />

```

Body:
i am less experienced plz help me out to resolve this problem . i want just image upload box by clicking on it input field work. thanks in advance

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#picker')
        .attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
}

img {
  max-width: 180px;
}

input[type=file] {
  padding: 0px;
  position: absolute;
  display: ;
  background: ;
}

.card-1 {
  width: 180px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}

.card-1:hover {
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
}

  <input type='file' onchange="readURL(this);" />

Body:
You can call .click() on this.previousElementSibling.click() at onclick at <img> element that is next element sibling of <input type="file"> element.

Note file at input[type=file] should be surrounded by quotes at css input[type="file"].  Set display set to none at input[type="file"] element if element should not be displayed.

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#picker')
        .attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
}

img {
  max-width: 180px;
}

input[type="file"] {
  padding: 0px;
  position: absolute;
  display: none;
}

.card-1 {
  width: 180px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}

.card-1:hover {
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card card-1">
  <input type='file' onchange="readURL(this);" />
  <img onclick="this.previousElementSibling.click()" id="picker" src="http://placehold.it/180" alt="your image" />
</div>


问:
Bind data for BLOB in POCO framework using SQLite wrapper
I am trying to bind a binary data to save the data in a BLOB column of SQLite using POCO framework, however, I can not figure out, how to achieve the desired results.

My code:

```<code>#include <Poco/Data/Session.h>
#include <Poco/Data/SessionPool.h>
#include <Poco/Data/SQLite/Connector.h>
</code>```

.
.
.

```<code>const std::string dbSchemeDemo =
    "CREATE TABLE IF NOT EXISTS `demo` ("
    "\n\t`key`\tTEXT NOT NULL,"
    "\n\t`value`\tINTEGER DEFAULT NULL,"
    "\n\t`data`\tBLOB DEFAULT NULL,"
    "\n\tPRIMARY KEY(`key`)"
    "\n);"
    "\nCREATE INDEX IF NOT EXISTS idx_key ON demo(key);";

std::string sqlQueryDemo =
    "INSERT INTO demo"
    " (key, value, data)"
    " VALUES(?, ?, ?)";

auto dbPoolDemo = std::make_unique<Poco::Data::SessionPool>(Poco::Data::SQLite::Connector::KEY, "demo.db3");

Poco::Data::SQLite::Connector::registerConnector();

Poco::Data::Session dbDemo(dbPoolDemo->get());
dbDemo.setConnectionTimeout(2);
dbDemo << "PRAGMA foreign_keys = ON;", Poco::Data::Keywords::now;
dbDemo << dbSchemeDemo, Poco::Data::Keywords::now;

std::vector<unsigned char> data{ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };

Poco::Data::Statement insertDemo(dbDemo);
insertDemo << sqlQueryDemo,
    Poco::Data::Keywords::bind("ABCD"),
    Poco::Data::Keywords::bind(Poco::Nullable<int>(1)),
    Poco::Data::Keywords::bind(Poco::Nullable<std::vector<unsigned char>>(data)),
    Poco::Data::Keywords::now;
</code>```

The exception "Not implemented" is thown. Any idea, how to bind a binary data from vector? Thanks a lot!

答:
With a beautiful mind, I have found a simple solution - wrap the data by Poco::Data::BLOB template class:

```<code>Poco::Data::BLOB data(std::vector<unsigned char>({ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' }));
</code>```

and later bind

```<code>Poco::Data::Keywords::bind(Poco::Nullable<Poco::Data::BLOB>(data)),
</code>```

To store NULL can be used empty vector (wrapped by Poco::Nullable).
So the solution is:

```<code>    Poco::Data::BLOB data(std::vector<unsigned char>({ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' }));

    Poco::Data::Statement insertDemo(dbDemo);
    insertDemo << sqlQueryDemo,
        Poco::Data::Keywords::bind("ABCDEFG"),
        Poco::Data::Keywords::bind(Poco::Nullable<int>(1)),
        Poco::Data::Keywords::bind(Poco::Nullable<Poco::Data::BLOB>(data)),
        Poco::Data::Keywords::now;
</code>```

Body:
I am trying to bind a binary data to save the data in a BLOB column of SQLite using POCO framework, however, I can not figure out, how to achieve the desired results.

My code:

#include <Poco/Data/Session.h>
#include <Poco/Data/SessionPool.h>
#include <Poco/Data/SQLite/Connector.h>

.
.
.

const std::string dbSchemeDemo =
    "CREATE TABLE IF NOT EXISTS `demo` ("
    "\n\t`key`\tTEXT NOT NULL,"
    "\n\t`value`\tINTEGER DEFAULT NULL,"
    "\n\t`data`\tBLOB DEFAULT NULL,"
    "\n\tPRIMARY KEY(`key`)"
    "\n);"
    "\nCREATE INDEX IF NOT EXISTS idx_key ON demo(key);";

std::string sqlQueryDemo =
    "INSERT INTO demo"
    " (key, value, data)"
    " VALUES(?, ?, ?)";

auto dbPoolDemo = std::make_unique<Poco::Data::SessionPool>(Poco::Data::SQLite::Connector::KEY, "demo.db3");

Poco::Data::SQLite::Connector::registerConnector();

Poco::Data::Session dbDemo(dbPoolDemo->get());
dbDemo.setConnectionTimeout(2);
dbDemo << "PRAGMA foreign_keys = ON;", Poco::Data::Keywords::now;
dbDemo << dbSchemeDemo, Poco::Data::Keywords::now;

std::vector<unsigned char> data{ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };

Poco::Data::Statement insertDemo(dbDemo);
insertDemo << sqlQueryDemo,
    Poco::Data::Keywords::bind("ABCD"),
    Poco::Data::Keywords::bind(Poco::Nullable<int>(1)),
    Poco::Data::Keywords::bind(Poco::Nullable<std::vector<unsigned char>>(data)),
    Poco::Data::Keywords::now;

The exception "Not implemented" is thown. Any idea, how to bind a binary data from vector? Thanks a lot!

Body:
With a beautiful mind, I have found a simple solution - wrap the data by Poco::Data::BLOB template class:

Poco::Data::BLOB data(std::vector<unsigned char>({ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' }));

and later bind

Poco::Data::Keywords::bind(Poco::Nullable<Poco::Data::BLOB>(data)),

To store NULL can be used empty vector (wrapped by Poco::Nullable).
So the solution is:

    Poco::Data::BLOB data(std::vector<unsigned char>({ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' }));

    Poco::Data::Statement insertDemo(dbDemo);
    insertDemo << sqlQueryDemo,
        Poco::Data::Keywords::bind("ABCDEFG"),
        Poco::Data::Keywords::bind(Poco::Nullable<int>(1)),
        Poco::Data::Keywords::bind(Poco::Nullable<Poco::Data::BLOB>(data)),
        Poco::Data::Keywords::now;


问:
angular 2 pass variable from injectable to component
I wrote an http interceptor in order to catch all 5xx errors from server. The idea is that in app.component.html I have component (bad-response) which must be displayed if there is an 5xx error. In an interceptor I can check whether there is an error. But how can I pass this information to "bad-response" component?

I've tried to create another service, which will be injected in component for getting variable value and in interceptor for setting it, but no luck.

app.component.html

```<code><top-nav></top-nav>

<router-outlet></router-outlet>

<bad-response></bad-response> //need to pass info about 5xx error here
</code>```

interceptor.ts

```<code>@Injectable()
export class InterceptedHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
   super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    super.get(url, this.getRequestOptionArgs(options)).subscribe((res: Response) => {
     // here I can get to response status code via res.status
   });
   return super.get(url, this.getRequestOptionArgs(options));
  }

  ...other code
}
</code>```

bad-response.component.html

```<code><div *ngIf="isBadResponse">
  Sorry, there are connection problems
</div>
</code>```

bad-response.component.ts

```<code>import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'bad-response',
  templateUrl: './bad-response.component.html'
})

export class BadResponseComponent implements OnInit {

  isBadResponse: boolean;

  constructor() {
  }

  ngOnInit() {
  }
}
</code>```

答: Found out that it could be done via another service which connects component and injectable and uses static property

Body:
I wrote an http interceptor in order to catch all 5xx errors from server. The idea is that in app.component.html I have component (bad-response) which must be displayed if there is an 5xx error. In an interceptor I can check whether there is an error. But how can I pass this information to "bad-response" component?

I've tried to create another service, which will be injected in component for getting variable value and in interceptor for setting it, but no luck.

app.component.html

<top-nav></top-nav>

<router-outlet></router-outlet>

<bad-response></bad-response> //need to pass info about 5xx error here

interceptor.ts

@Injectable()
export class InterceptedHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
   super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    super.get(url, this.getRequestOptionArgs(options)).subscribe((res: Response) => {
     // here I can get to response status code via res.status
   });
   return super.get(url, this.getRequestOptionArgs(options));
  }

  ...other code
}

bad-response.component.html

  Sorry, there are connection problems

bad-response.component.ts

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'bad-response',
  templateUrl: './bad-response.component.html'
})

export class BadResponseComponent implements OnInit {

  isBadResponse: boolean;

  constructor() {
  }

  ngOnInit() {
  }
}


问:
Dojo context menu - set menu item status dynamically
I am trying to implement a context menu on a dijit tree, and the context menu should display different contents and enable/disable the menu items based on which tree node I right-clicked on. Basically what I need is a pre-processing function that gets called before the context menu is displayed where I can run some logic to determine which menu items to show/hide, enable/disable, etc. I feel like this is a very basic functionality for context menus but wasn't able to find the solution, so I'm asking people for help.

Any help would be appreciated. Thanks!

答:
Dijit Tree has no built-in support for context menus, but you can use the Menu widget in conjunction with the Tree. The Menu widget is used for context menus, with right-click which can really suite your use-case.

Documentation and examples here:

https://dojotoolkit.org/reference-guide/1.10/dijit/Tree.html#context-menu
https://dojotoolkit.org/reference-guide/1.10/dijit/Menu.html


问:
Is md5 value language dependent?
If I generate md5 of a file in java and javascript -Will both the values be same?
I have to generate md5 in javascript and send it to the server and the server matches it. I am getting a hash mismatch error.

Actually, I need 'base64 encoded 128-bit MD5 digest' to send to S3 using javascript.

Thanks

答:
MD5 is just an hashing algorithm and hence can be implemented in any language. Result will be the same, as long as you don't make any mistake in the implementation.

Some areas to take care of, while implementing in different languages, which could unintentionally introduce errors in implementation, could be: range/Truncating/promotion of integer values, operators precedence etc.

Title: Is md5 value language dependent?


问:
Laravel 5.4: Change DB according to sub domain in laravel
I am creating a SAAS application with a single laravel installation and multi tenant database.
So i have a main DB that is connected to laravel by default. the client can access the application through their sub-domain like: client1.example.com and client2.example.com

I am saving all info fo the client like domain and db name in the main db.

How can change the DB according to the subdomain

I tried with the following Code

in routes/web.php

```<code>Route::group(['domain' => '{account}'], function() {
    Route::get('/', function($account) {
        // This will return {account}, which you can pass along to what you'd like
        return $account;
    });

});
</code>```

in app/Providers\RouteServiceProvieder.php

```<code> public function boot(Router $router)
    {
        parent::boot($router);

        $router->bind('domain', function ($value) {
            //$hst=$request->getHost();
            $domain= Customer::where('sub_domain',$value)->first();
            if ($domain) {
                return $domain;
            }
            throw new Exception('error message');
        });

    }
</code>```

Then i have created a ServiceProvider ConfigServiceProvider

```<code><?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class ConfigServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register(Request $request)
    {
        $customer=$request->route('domain');
        //$customer = Request::route('domain');  // there are multiple ways of doing this
        //$customer = $request->route()->domain;
        config([
            'database.mysql.database' => $customer->customer_database,  //this is because I have same username and password for all the databases. If you have different username and passwords set them too.
        ]);
        DB::reconnect(); // this will help in reconnecting the database if the connection is already established. and import the DB facade.
    }
}
</code>```

But the code is not working?

The Error i am getting is

```<code>FatalThrowableError in ConfigServiceProvider.php line 25:
Type error: Too few arguments to function App\Providers\ConfigServiceProvider::register(), 0 passed in C:\xampp\htdocs\main\vendor\laravel\framework\src\Illuminate\Foundation\Application.php on line 568 and exactly 1 expected
</code>```

I am using Laravel 5.4. Can any one guide me how to do it correctly?

答:
well there are some issues here:

First the register() method of a service provider should not accept a Request instance as argument. Its better to write it like that:

```<code>public function register()
</code>```

Second, dont use config() in the register() method, from the laravel docs:

within the register method, you should only bind things into the
  service container. You should never attempt to register any event
  listeners, routes, or any other piece of functionality within the
  register method. Otherwise, you may accidentally use a service that is
  provided by a service provider which has not loaded yet.

IMHO I would use a middleware to change the database configuration like you tried in a service provider, i.e:

```<code>public function handle($request, Closure $next)
{
    $customer=$request->route('domain');
    if($customer)
    {
        config(['database.mysql.database' => $customer->customer_database]);
        DB::reconnect();
    }
    return $next($request);
}
</code>```

If you take care of loading the middleware in the right place (look in app/Http/Kernel.php) you will have database changed before any query.

Body:
I am creating a SAAS application with a single laravel installation and multi tenant database.
So i have a main DB that is connected to laravel by default. the client can access the application through their sub-domain like: client1.example.com and client2.example.com

I am saving all info fo the client like domain and db name in the main db.

How can change the DB according to the subdomain

I tried with the following Code

in routes/web.php

Route::group(['domain' => '{account}'], function() {
    Route::get('/', function($account) {
        // This will return {account}, which you can pass along to what you'd like
        return $account;
    });

});

in app/Providers\RouteServiceProvieder.php

 public function boot(Router $router)
    {
        parent::boot($router);

        $router->bind('domain', function ($value) {
            //$hst=$request->getHost();
            $domain= Customer::where('sub_domain',$value)->first();
            if ($domain) {
                return $domain;
            }
            throw new Exception('error message');
        });

    }

Then i have created a ServiceProvider ConfigServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class ConfigServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register(Request $request)
    {
        $customer=$request->route('domain');
        //$customer = Request::route('domain');  // there are multiple ways of doing this
        //$customer = $request->route()->domain;
        config([
            'database.mysql.database' => $customer->customer_database,  //this is because I have same username and password for all the databases. If you have different username and passwords set them too.
        ]);
        DB::reconnect(); // this will help in reconnecting the database if the connection is already established. and import the DB facade.
    }
}

But the code is not working?

The Error i am getting is

FatalThrowableError in ConfigServiceProvider.php line 25:
Type error: Too few arguments to function App\Providers\ConfigServiceProvider::register(), 0 passed in C:\xampp\htdocs\main\vendor\laravel\framework\src\Illuminate\Foundation\Application.php on line 568 and exactly 1 expected

I am using Laravel 5.4. Can any one guide me how to do it correctly?

Body:
well there are some issues here:

First the register() method of a service provider should not accept a Request instance as argument. Its better to write it like that:

public function register()

Second, dont use config() in the register() method, from the laravel docs:

within the register method, you should only bind things into the
  service container. You should never attempt to register any event
  listeners, routes, or any other piece of functionality within the
  register method. Otherwise, you may accidentally use a service that is
  provided by a service provider which has not loaded yet.

IMHO I would use a middleware to change the database configuration like you tried in a service provider, i.e:

public function handle($request, Closure $next)
{
    $customer=$request->route('domain');
    if($customer)
    {
        config(['database.mysql.database' => $customer->customer_database]);
        DB::reconnect();
    }
    return $next($request);
}

If you take care of loading the middleware in the right place (look in app/Http/Kernel.php) you will have database changed before any query.


问:
How to give a name to docker image?
I use this tutorial to start working with docker on windows.
Everything was fine, but when I build my Dockerfile, image created without a name.
screen from PowerShell </p>

<p>How to name this image? </p>

答:
It's not a name or tag of the image.

You can add tag to image.

```<code>docker tag [imageid] [tag]
</code>```

where [imageid] is the your image ID (85d1607990cd - from your screenshot) and [tag] - is the image tag ("name") for example iis. And as result the full command is:

```<code>docker tag 85d1607990cd iis
</code>```

You can read more about the image tagging here

Title: How to give a name to docker image?

Body:
I use this tutorial to start working with docker on windows.
Everything was fine, but when I build my Dockerfile, image created without a name.
screen from PowerShell

How to name this image?

Body:
It's not a name or tag of the image.

You can add tag to image.

docker tag [imageid] [tag]

where [imageid] is the your image ID (85d1607990cd - from your screenshot) and [tag] - is the image tag ("name") for example iis. And as result the full command is:

docker tag 85d1607990cd iis

You can read more about the image tagging here


问:
Ajax success function not working in laravel
My blade view-

```<code>@foreach ($songs as $song)
     <a href="{{asset('/audio/' . $song->song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           <i class="glyphicon glyphicon-download">Download</i>
        </button>
     </a>
 @endforeach
</code>```

My ajax success function does not work. it doesn't show alert. Therefore I cannot update my database. Here is my ajax:

```<code>$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   },
success: function(data)
                        {
                            alert("ok");
                        }
  });
});
    });
</code>```

So, Whats wrong with my ajax call? I want to click on link and pass the the id to my controller.

答:
```<code>    Add a meta-tag to each page (or master layout):
 <meta name="csrf-token" content="{{ csrf_token() }}">

    And add to your javascript-file (or section within the page):

    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });
</code>```

Body:
My blade view-

@foreach ($songs as $song)
     song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           Download
        </button>

 @endforeach

My ajax success function does not work. it doesn't show alert. Therefore I cannot update my database. Here is my ajax:

$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   },
success: function(data)
                        {
                            alert("ok");
                        }
  });
});
    });

So, Whats wrong with my ajax call? I want to click on link and pass the the id to my controller.


Title: Ruby 2 dimensional array finding max value and sort array

Body:
I have an array of arrays with coordinates which represent a polyline:

array = [
  [3004.9999999999986, -500.0],
  [5733.5, -500.0],
  [5733.5, 300.0],
  [8462.0, 300.0],
  [8462.0, 1026.163313244362],
  [7254.568694406579, 1026.163313244362],
  [7254.568694406579, 1500.0],
  [3004.9999999999914, 1500.0],
  [3004.9999999999914, 1224.9602566586254],
  [5.0, 1224.9602566586254],
  [5.00000000000015, 300.0],
  [3004.9999999999986, 300.0]
]

I have to find the coordinate with the lowest x-value and highest y-value where a lower x-value has priority over a higher y-value.

For the above array the expected result is as follows (lowest x and then highest y):

[5.0, 1224.9602566586254]

Body:
You can use Enumerable#min_by:

array.min_by { |x, y| [x, -y] }
#=> [5.0, 1224.9602566586254]

or Enumerable#max_by:

array.max_by { |x, y| [-x, y] }
#=> [5.0, 1224.9602566586254]


问:
SQL - add days to a date in a loop
I have a table with this fields:

```<code>Id int(11) pk,
Start_date date,
End_date date,
type tinyint(1),
Frequency int.
</code>```

I want to do a select on this table where start_date+frequency = @date(a variable date) until end_date(loop).

How do this with sql?

Thanks in advance.

EDIT:
Variable date is (for example):

```<code>SET @date = '2017-03-30'
</code>```

type can be 0 or 1:

if type = 0 my query is :

```<code> select * from table
 where type = 0 and start_date <= @date AND end_date>=@date
</code>```

if type = 1, frequency is a field with an integer number(a interval of days). So I have to check if adding this value to start_date is equals to @date.

if yes, I have to return the current record

if no, I have to iterate this operation

```<code>Date current = start_date + interval of 'frequency' days
while(current < end_date){
if(current == @date)
(this is the record I want)
else
current+=frequency
}
</code>```

The result of query of type 1 can be more than one record. And finally I want to UNION the result of type 0 and 1 in unique select.

答:
Based on a comment/confirmation below the question:

So, to put it in less focussed on the wrong solution terms, you want to determine whether the difference between start_date and @date, in days, is an integer multiple of frequency? –

Looks like you want something like:

```<code>select * from table
where
   start_date <= @date AND
   end_date>=@date AND
   (
     type = 0 OR
     (
        type = 1 AND
        mod(datediff(@date,start_date),frequency) = 0
     )
   )
</code>```

Once we determined the actual requirement, above, and it was clear we just need to find out if one number is a multiple of another, we use mod to compute that. The rest of the structure of the WHERE clause essentially follows the bullet-pointed section of the question.

Title: SQL - add days to a date in a loop

Body:
I have a table with this fields:

Id int(11) pk,
Start_date date,
End_date date,
type tinyint(1),
Frequency int.

I want to do a select on this table where start_date+frequency = @date(a variable date) until end_date(loop).

How do this with sql?

Thanks in advance.

EDIT:
Variable date is (for example):

SET @date = '2017-03-30'

type can be 0 or 1:

if type = 0 my query is :

 select * from table
 where type = 0 and start_date <= @date AND end_date>=@date

if type = 1, frequency is a field with an integer number(a interval of days). So I have to check if adding this value to start_date is equals to @date.

if yes, I have to return the current record

if no, I have to iterate this operation

Date current = start_date + interval of 'frequency' days
while(current < end_date){
if(current == @date)
(this is the record I want)
else
current+=frequency
}

The result of query of type 1 can be more than one record. And finally I want to UNION the result of type 0 and 1 in unique select.

Body:
Based on a comment/confirmation below the question:

So, to put it in less focussed on the wrong solution terms, you want to determine whether the difference between start_date and @date, in days, is an integer multiple of frequency? –

Looks like you want something like:

select * from table
where
   start_date <= @date AND
   end_date>=@date AND
   (
     type = 0 OR
     (
        type = 1 AND
        mod(datediff(@date,start_date),frequency) = 0
     )
   )

Once we determined the actual requirement, above, and it was clear we just need to find out if one number is a multiple of another, we use mod to compute that. The rest of the structure of the WHERE clause essentially follows the bullet-pointed section of the question.


问:
Error while sending email with credentials from web.config
I'm developing a website by ASP.NET MVC.
I have this function in my IdentityConfig.cs:

```<code>public Task SendAsync(IdentityMessage message)
{
    SmtpClient client = new SmtpClient();
    var msg = new MailMessage();
    msg.From = new MailAddress("info@mywebsite.com");
    msg.To.Add(message.Destination);
    msg.Subject = message.Subject;
    msg.Body = message.Body;
    client.Host = "mywebsite.com";
    client.Port = 25;
    client.Credentials = new
        System.Net.NetworkCredential("info@mywebsite.com", "mypassword");
    return client.SendMailAsync(msg);
}
</code>```

I set up SMTP Service in IIS 8 and this function works fine.
The problem is when I config SMTP credentials inside Web.config and try to send an email. MailSettings part of Web.config is as follows:

```<code><system.net>
    <mailSettings>
      <smtp>
        <network host="mywebsite.com"
                 port="25" userName="info@mywebsite.com" password="mypassword" />
      </smtp>
    </mailSettings>
</system.net>
</code>```

and the new SendAsync function is:

```<code>public Task SendAsync(IdentityMessage message)
{
    SmtpClient client = new SmtpClient();
    var msg = new MailMessage();
    msg.From = new MailAddress("info@mywebsite.com");
    msg.To.Add(message.Destination);
    msg.Subject = message.Subject;
    msg.Body = message.Body;
    return client.SendMailAsync(msg);
}
</code>```

But when running this inside my controller, the following error occurs:

Bad sequence of commands.
  The server response was:
  This mail server requires authentication when attempting to send to a non-local e-mail address.
  Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.

What could be the cause?

答:
try adding defaultCredentials to false

```<code>  <network
          clientDomain="mywebsite.com"
          defaultCredentials="false"
          enableSsl="true"
          host="smtp.gmail.com"
          port="587"
          userName="sender@mywebsite.it" password="xxxxxxx"
        />
</code>```

Note that for some servers (like gmail) the message.From needs to match with the username

Body:
I'm developing a website by ASP.NET MVC.
I have this function in my IdentityConfig.cs:

public Task SendAsync(IdentityMessage message)
{
    SmtpClient client = new SmtpClient();
    var msg = new MailMessage();
    msg.From = new MailAddress("info@mywebsite.com");
    msg.To.Add(message.Destination);
    msg.Subject = message.Subject;
    msg.Body = message.Body;
    client.Host = "mywebsite.com";
    client.Port = 25;
    client.Credentials = new
        System.Net.NetworkCredential("info@mywebsite.com", "mypassword");
    return client.SendMailAsync(msg);
}

I set up SMTP Service in IIS 8 and this function works fine.
The problem is when I config SMTP credentials inside Web.config and try to send an email. MailSettings part of Web.config is as follows:

<system.net>
    <mailSettings>
      <smtp>
        <network host="mywebsite.com"
                 port="25" userName="info@mywebsite.com" password="mypassword" />
      </smtp>
    </mailSettings>
</system.net>

and the new SendAsync function is:

public Task SendAsync(IdentityMessage message)
{
    SmtpClient client = new SmtpClient();
    var msg = new MailMessage();
    msg.From = new MailAddress("info@mywebsite.com");
    msg.To.Add(message.Destination);
    msg.Subject = message.Subject;
    msg.Body = message.Body;
    return client.SendMailAsync(msg);
}

But when running this inside my controller, the following error occurs:

Bad sequence of commands.
  The server response was:
  This mail server requires authentication when attempting to send to a non-local e-mail address.
  Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.

What could be the cause?

Body:
try adding defaultCredentials to false

  <network
          clientDomain="mywebsite.com"
          defaultCredentials="false"
          enableSsl="true"
          host="smtp.gmail.com"
          port="587"
          userName="sender@mywebsite.it" password="xxxxxxx"
        />

Note that for some servers (like gmail) the message.From needs to match with the username


问:
Type conversion error in VB when accessing a HTML table
I have a HTML table where I am allowing dynamic adding/deleting rows (that contain text-input's in the cells) using some JavaScript. I am not using ASP.NET TextBox controls, just traditional HTML, as I don't think rows containing ASP.NET controls can be added/deleted without a postback.

When the user clicks an ASP:Button, I am using VB to loop through the table rows in server-code, and ultimately use LINQ to write to a database. I have "Imports System.Web.UI.HtmlControls" in the file.

The code where I am getting problems is:

```<code>Dim name As HtmlInputText

name = row.Cells(0).Controls(0)
</code>```

The error is: "Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.HtmlControls.HtmlInputText'." On the 2nd line above.

There is only one input control in each cell, so I am assuming I can use "Controls(0)" to access it. I have read solutions that use "FindControl", but I don't think this works with standard HTML "inputs", but also, as the rows are dynamically added/deleted, it's near-impossible to know the "ID" to search for.

Any ideas? Cheers.

答: Figured out the problem. Just needed to add runat="server" to the input tags. Thanks every one for the replies.</p>

Body:
I have a HTML table where I am allowing dynamic adding/deleting rows (that contain text-input's in the cells) using some JavaScript. I am not using ASP.NET TextBox controls, just traditional HTML, as I don't think rows containing ASP.NET controls can be added/deleted without a postback.

When the user clicks an ASP:Button, I am using VB to loop through the table rows in server-code, and ultimately use LINQ to write to a database. I have "Imports System.Web.UI.HtmlControls" in the file.

The code where I am getting problems is:

Dim name As HtmlInputText

name = row.Cells(0).Controls(0)

The error is: "Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.HtmlControls.HtmlInputText'." On the 2nd line above.

There is only one input control in each cell, so I am assuming I can use "Controls(0)" to access it. I have read solutions that use "FindControl", but I don't think this works with standard HTML "inputs", but also, as the rows are dynamically added/deleted, it's near-impossible to know the "ID" to search for.

Any ideas? Cheers.


问:
No content to map due to end-of-input when parsing json
I was using the play JSON library tools to parse a JSON data in Spark, and got the following error message. Does anyone have any clue about possible cause of this error? If this is due to a bad JSON record, how can I identify the bad record? Thanks!

Here is the major script I used to parse the JSON data:

```<code>import play.api.libs.json._
val jsonData = distdata.map(line => Json.parse(line)) //line 194 of script parseJson_v14.scala
val filteredData = jsonData.map(json => (json \ "QueryStringParameters" \ "pr").asOpt[String].orNull).countByValue()
</code>```

Variable distdata is a rdd of text format JSON data, variable jsonData is a rdd of JsValue data. Since Spark transformation is lazy, the error didn't jump out until the 2nd command is executed to create the variable filteredData, and according to the error message, the error comes from the the 1st command where I create the variable jsonData.

```</p>

<code>[2017-03-29 14:55:39.616]-[Logging$class.logWarning]-[WARN]: Lost task 42.0 in stage 1.0 (TID 90, 10.119.126.114): com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
     at [Source: ; line: 1, column: 1]
            at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
            at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3110)
            at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3024)
            at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1652)
            at play.api.libs.json.jackson.JacksonJson$.parseJsValue(JacksonJson.scala:226)
            at play.api.libs.json.Json$.parse(Json.scala:21)
            at parseJson_v14$$anonfun$1$$anonfun$3$$anonfun$apply$1.apply(parseJson_v14.scala:194)
            at parseJson_v14$$anonfun$1$$anonfun$3$$anonfun$apply$1.apply(parseJson_v14.scala:194)
            at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
            at scala.collection.Iterator$$anon$14.hasNext(Iterator.scala:389)
            at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
            at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
            at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13$$anonfun$apply$6.apply$mcV$sp(PairRDDFunctions.scala:1197)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13$$anonfun$apply$6.apply(PairRDDFunctions.scala:1197)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13$$anonfun$apply$6.apply(PairRDDFunctions.scala:1197)
            at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1250)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13.apply(PairRDDFunctions.scala:1205)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13.apply(PairRDDFunctions.scala:1185)
            at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
            at org.apache.spark.scheduler.Task.run(Task.scala:89)
            at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at java.lang.Thread.run(Thread.java:745)
</code>```

答:
Check if you have no blank lines in distdata and that you have all JSON object in one line, like

```<code>{"id":"121", "name":"robot 1"}
{"id":"122", "name":"robot 2"}
</code>```

opposite to

```<code>{"id":"121", "name":
"robot 1"}
{"id":"122", "name":
"robot 2"}
</code>```

Body:
I was using the play JSON library tools to parse a JSON data in Spark, and got the following error message. Does anyone have any clue about possible cause of this error? If this is due to a bad JSON record, how can I identify the bad record? Thanks!

Here is the major script I used to parse the JSON data:

import play.api.libs.json._
val jsonData = distdata.map(line => Json.parse(line)) //line 194 of script parseJson_v14.scala
val filteredData = jsonData.map(json => (json \ "QueryStringParameters" \ "pr").asOpt[String].orNull).countByValue()

Variable distdata is a rdd of text format JSON data, variable jsonData is a rdd of JsValue data. Since Spark transformation is lazy, the error didn't jump out until the 2nd command is executed to create the variable filteredData, and according to the error message, the error comes from the the 1st command where I create the variable jsonData.

[2017-03-29 14:55:39.616]-[Logging$class.logWarning]-[WARN]: Lost task 42.0 in stage 1.0 (TID 90, 10.119.126.114): com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
     at [Source: ; line: 1, column: 1]
            at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
            at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3110)
            at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3024)
            at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1652)
            at play.api.libs.json.jackson.JacksonJson$.parseJsValue(JacksonJson.scala:226)
            at play.api.libs.json.Json$.parse(Json.scala:21)
            at parseJson_v14$$anonfun$1$$anonfun$3$$anonfun$apply$1.apply(parseJson_v14.scala:194)
            at parseJson_v14$$anonfun$1$$anonfun$3$$anonfun$apply$1.apply(parseJson_v14.scala:194)
            at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
            at scala.collection.Iterator$$anon$14.hasNext(Iterator.scala:389)
            at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
            at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
            at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13$$anonfun$apply$6.apply$mcV$sp(PairRDDFunctions.scala:1197)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13$$anonfun$apply$6.apply(PairRDDFunctions.scala:1197)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13$$anonfun$apply$6.apply(PairRDDFunctions.scala:1197)
            at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1250)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13.apply(PairRDDFunctions.scala:1205)
            at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsHadoopDataset$1$$anonfun$13.apply(PairRDDFunctions.scala:1185)
            at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
            at org.apache.spark.scheduler.Task.run(Task.scala:89)
            at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at java.lang.Thread.run(Thread.java:745)

Body:
Check if you have no blank lines in distdata and that you have all JSON object in one line, like

{"id":"121", "name":"robot 1"}
{"id":"122", "name":"robot 2"}

opposite to

{"id":"121", "name":
"robot 1"}
{"id":"122", "name":
"robot 2"}