问:
as_json ignoring second part of .where() clause
I'm trying to produce a json structure from an existing database that contains 5 tables:
:users
:resources
:quiz_questions
:quiz_answers
:quiz_responses

A resource has many quiz_questions, which has many quiz_answers, and in turn have many quiz_responses. users also has_many quiz_responses. (The idea is that a user takes a multiple choice quiz and they select existing answers which in turn creates a new row in quiz_responses.

So I have two lines of code:

```<code>questions = QuizQuestion.includes(:quiz_answers, :quiz_responses).where(resource_id: 623, quiz_responses: {user_id: 18276})
</code>```

which produces this query:

```<code>SELECT
  `quiz_questions`.`id` AS t0_r0,
  `quiz_questions`.`question` AS t0_r1
  `quiz_questions`.`resource_id` AS t0_r2,
  `quiz_questions`.`created_at` AS t0_r3,
  `quiz_questions`.`updated_at` AS t0_r4,
  `quiz_questions`.`question_type` AS t0_r5,
  `quiz_questions`.`url` AS t0_r6,
  `quiz_questions`.`auto_next` AS t0_r7,
  `quiz_questions`.`show_correct` AS t0_r8,
  `quiz_questions`.`answer_type` AS t0_r9,
  `quiz_answers`.`id` AS t1_r0,
  `quiz_answers`.`answer` AS t1_r1,
  `quiz_answers`.`quiz_question_id` AS t1_r2,
  `quiz_answers`.`correct` AS t1_r3,
  `quiz_answers`.`created_at` AS t1_r4,
  `quiz_answers`.`updated_at` AS t1_r5,
  `quiz_answers`.`answer_immediately` AS t1_r6,
  `quiz_answers`.`time_limit` AS t1_r7,
  `quiz_responses`.`id` AS t2_r0,
  `quiz_responses`.`user_id` AS t2_r1,
  `quiz_responses`.`quiz_answer_id` AS t2_r2,
  `quiz_responses`.`created_at` AS t2_r3,
  `quiz_responses`.`updated_at` AS t2_r4,
  `quiz_responses`.`attempt_id` AS t2_r5,
  `quiz_responses`.`video_url` AS t2_r6,
  `quiz_responses`.`correct` AS t2_r7,
  `quiz_responses`.`group_id` AS t2_r8
FROM `quiz_questions`
  LEFT OUTER JOIN `quiz_answers` ON `quiz_answers`.`quiz_question_id` = `quiz_questions`.`id`
  LEFT OUTER JOIN `quiz_answers` `quiz_answers_quiz_questions_join` ON `quiz_answers_quiz_questions_join`.`quiz_question_id` = `quiz_questions`.`id`
  LEFT OUTER JOIN `quiz_responses` ON `quiz_responses`.`quiz_answer_id` = `quiz_answers_quiz_questions_join`.`id`
WHERE
  `quiz_questions`.`resource_id` = 623
  AND `quiz_responses`.`user_id` = 18276
</code>```

The second line of code:

```<code>questions.as_json(include: { quiz_answers: { include: [:quiz_responses]}})
</code>```

invokes these additional queries:

```<code>  QuizResponse Load (0.8ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 755

  QuizResponse Load (0.8ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 756

  QuizResponse Load (1.5ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 757

  QuizResponse Load (0.7ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 758

  QuizResponse Load (0.6ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 759

  QuizResponse Load (0.7ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 760

  QuizResponse Load (0.6ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 761

  QuizResponse Load (0.6ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 764

  QuizResponse Load (0.8ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 765
</code>```

The intended goal of this code is to get all questions related to resource 867 and then return the possible answers as well as the responses related to a particular user (in this case 18276)

The problem is that while only questions related to resource 867 are returned as_json, all users responses are returned in spite of the where clause in the first line, not just user 18276's responses. Why is this? is there some way I can tell as_json to just use what it receives and return the quiz_responses selected in the initial query? What is the 'rails way' to go about this?

答:
Update: New solution

Rails does not allow to preload parameterised associations. But it's possible to load all necessary data by two queries and parse it to json:

```<code># load data
questions = QuizQuestion.preload(:quiz_answers)
answers_ids = questions.collect{ |question| question.quiz_answers.collect(&:id) }.flatten
responses = QuizResponse.where(quiz_answer_id: answers_ids).group_by(&:quiz_answer_id)

# making json
json_string = Jbuilder.encode do |json|
  json.array! questions do |question|
    json.merge! question.attributes

    json.quiz_answers question.quiz_answers do |answer|
      json.merge! answer.attributes

      json.quiz_responses responses[answer.id] do |response|
        json.merge! response.attributes
      end
    end
  end
end
</code>```

This code will not omit quiz_answer from result, if it has not quiz_response for the user in a question.

First version:

The data structure has two quiz_responses associations:

QuizQuestion has_many :quiz_responses, through: :quiz_answers
QuizAnswer has_many :quiz_responses
The query includes quiz_responses as a relation of QuizQuestion. But as_json uses quiz_responses as a relation of QuizAnswer. And Rails are not smart enough to understand that necessary quiz_responses already loaded.

All you need to do is to rewrite includes in a nested way, same as you want to use it:

```<code>questions = QuizQuestion.includes(quiz_answers: :quiz_responses)
</code>```

Body:
I'm trying to produce a json structure from an existing database that contains 5 tables:
:users
:resources
:quiz_questions
:quiz_answers
:quiz_responses

A resource has many quiz_questions, which has many quiz_answers, and in turn have many quiz_responses. users also has_many quiz_responses. (The idea is that a user takes a multiple choice quiz and they select existing answers which in turn creates a new row in quiz_responses.

So I have two lines of code:

questions = QuizQuestion.includes(:quiz_answers, :quiz_responses).where(resource_id: 623, quiz_responses: {user_id: 18276})

which produces this query:

SELECT
  `quiz_questions`.`id` AS t0_r0,
  `quiz_questions`.`question` AS t0_r1
  `quiz_questions`.`resource_id` AS t0_r2,
  `quiz_questions`.`created_at` AS t0_r3,
  `quiz_questions`.`updated_at` AS t0_r4,
  `quiz_questions`.`question_type` AS t0_r5,
  `quiz_questions`.`url` AS t0_r6,
  `quiz_questions`.`auto_next` AS t0_r7,
  `quiz_questions`.`show_correct` AS t0_r8,
  `quiz_questions`.`answer_type` AS t0_r9,
  `quiz_answers`.`id` AS t1_r0,
  `quiz_answers`.`answer` AS t1_r1,
  `quiz_answers`.`quiz_question_id` AS t1_r2,
  `quiz_answers`.`correct` AS t1_r3,
  `quiz_answers`.`created_at` AS t1_r4,
  `quiz_answers`.`updated_at` AS t1_r5,
  `quiz_answers`.`answer_immediately` AS t1_r6,
  `quiz_answers`.`time_limit` AS t1_r7,
  `quiz_responses`.`id` AS t2_r0,
  `quiz_responses`.`user_id` AS t2_r1,
  `quiz_responses`.`quiz_answer_id` AS t2_r2,
  `quiz_responses`.`created_at` AS t2_r3,
  `quiz_responses`.`updated_at` AS t2_r4,
  `quiz_responses`.`attempt_id` AS t2_r5,
  `quiz_responses`.`video_url` AS t2_r6,
  `quiz_responses`.`correct` AS t2_r7,
  `quiz_responses`.`group_id` AS t2_r8
FROM `quiz_questions`
  LEFT OUTER JOIN `quiz_answers` ON `quiz_answers`.`quiz_question_id` = `quiz_questions`.`id`
  LEFT OUTER JOIN `quiz_answers` `quiz_answers_quiz_questions_join` ON `quiz_answers_quiz_questions_join`.`quiz_question_id` = `quiz_questions`.`id`
  LEFT OUTER JOIN `quiz_responses` ON `quiz_responses`.`quiz_answer_id` = `quiz_answers_quiz_questions_join`.`id`
WHERE
  `quiz_questions`.`resource_id` = 623
  AND `quiz_responses`.`user_id` = 18276

The second line of code:

questions.as_json(include: { quiz_answers: { include: [:quiz_responses]}})

invokes these additional queries:

  QuizResponse Load (0.8ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 755

  QuizResponse Load (0.8ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 756

  QuizResponse Load (1.5ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 757

  QuizResponse Load (0.7ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 758

  QuizResponse Load (0.6ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 759

  QuizResponse Load (0.7ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 760

  QuizResponse Load (0.6ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 761

  QuizResponse Load (0.6ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 764

  QuizResponse Load (0.8ms)  SELECT `quiz_responses`.* FROM `quiz_responses`  WHERE `quiz_responses`.`quiz_answer_id` = 765

The intended goal of this code is to get all questions related to resource 867 and then return the possible answers as well as the responses related to a particular user (in this case 18276)

The problem is that while only questions related to resource 867 are returned as_json, all users responses are returned in spite of the where clause in the first line, not just user 18276's responses. Why is this? is there some way I can tell as_json to just use what it receives and return the quiz_responses selected in the initial query? What is the 'rails way' to go about this?

Body:
Update: New solution

Rails does not allow to preload parameterised associations. But it's possible to load all necessary data by two queries and parse it to json:

# load data
questions = QuizQuestion.preload(:quiz_answers)
answers_ids = questions.collect{ |question| question.quiz_answers.collect(&:id) }.flatten
responses = QuizResponse.where(quiz_answer_id: answers_ids).group_by(&:quiz_answer_id)

# making json
json_string = Jbuilder.encode do |json|
  json.array! questions do |question|
    json.merge! question.attributes

    json.quiz_answers question.quiz_answers do |answer|
      json.merge! answer.attributes

      json.quiz_responses responses[answer.id] do |response|
        json.merge! response.attributes
      end
    end
  end
end

This code will not omit quiz_answer from result, if it has not quiz_response for the user in a question.

First version:

The data structure has two quiz_responses associations:

QuizQuestion has_many :quiz_responses, through: :quiz_answers
QuizAnswer has_many :quiz_responses
The query includes quiz_responses as a relation of QuizQuestion. But as_json uses quiz_responses as a relation of QuizAnswer. And Rails are not smart enough to understand that necessary quiz_responses already loaded.

All you need to do is to rewrite includes in a nested way, same as you want to use it:

questions = QuizQuestion.includes(quiz_answers: :quiz_responses)


来源: stackexchange

问:
Connection pool with single connection vs connection for infrequent queries
I am building a Java application which queries my SQL server once a minute. Right now, the application is using a connection pool with a single connection (min pool size 1, max pool size 1).

I figured that a pool size of 1 would be enough because of the infrequent queries (once a minute, as mentioned before).

Do I need a connection pool at all, and if the answer is yes, is 1 connection enough? Or should I just not use a pool and open a new connection every minute?

答:
using a connection pool with a single connection (min pool size 1, max
  pool size 1).

In such case don't see any need or benefit of using connection pool since at any point in time there will be only one connection object and if it's in use then other request has to wait (or) create a non-pooled connection object.

Connection pooling is generally used to save time/resource from creation/tearing-up the connection object.

In your specific case, you can probably create a connection instance and dispose it off once done with your work.

ContentLicense: CC BY-SA 3.0


问:
Unable to import SparkContext
I'm working on CentOS, I've setup $SPARK_HOME and also added path to bin in $PATH.

I can run pyspark from anywhere.

But when I try to create python file and uses this statement;

```<code>from pyspark import SparkConf, SparkContext
</code>```

it throws following error

```<code>python pysparktask.py
    Traceback (most recent call last):
    File "pysparktask.py", line 1, in <module>
      from pyspark import SparkConf, SparkContext
    ModuleNotFoundError: No module named 'pyspark'
</code>```

I tried to install it again using pip.

```<code>pip install pyspark
</code>```

and it gives this error too.

Could not find a version that satisfies the requirement pyspark (from versions: )
  No matching distribution found for pyspark

EDIT

based on answer, I updated the code.

error is

```<code>Traceback (most recent call last):
  File "pysparktask.py", line 6, in <module>
    from pyspark import SparkConf, SparkContext
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/__init__.py", line 44, in <module>
    from pyspark.context import SparkContext
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/context.py", line 33, in <module>
    from pyspark.java_gateway import launch_gateway
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/java_gateway.py", line 31, in <module>
    from py4j.java_gateway import java_import, JavaGateway, GatewayClient
ModuleNotFoundError: No module named 'py4j'
</code>```

答:
Add the following environment variable and also append spark's lib path to sys.path</p>

```<code>import os
import sys

os.environ['SPARK_HOME'] = "/usr/lib/spark/"
sys.path.append("/usr/lib/spark/python/")

from pyspark import SparkConf, SparkContext # And then try to import SparkContext.
</code>```

Title: Unable to import SparkContext

Body:
I'm working on CentOS, I've setup $SPARK_HOME and also added path to bin in $PATH.

I can run pyspark from anywhere.

But when I try to create python file and uses this statement;

from pyspark import SparkConf, SparkContext

it throws following error

python pysparktask.py
    Traceback (most recent call last):
    File "pysparktask.py", line 1, in <module>
      from pyspark import SparkConf, SparkContext
    ModuleNotFoundError: No module named 'pyspark'

I tried to install it again using pip.

pip install pyspark

and it gives this error too.

Could not find a version that satisfies the requirement pyspark (from versions: )
  No matching distribution found for pyspark

EDIT

based on answer, I updated the code.

error is

Traceback (most recent call last):
  File "pysparktask.py", line 6, in <module>
    from pyspark import SparkConf, SparkContext
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/__init__.py", line 44, in <module>
    from pyspark.context import SparkContext
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/context.py", line 33, in <module>
    from pyspark.java_gateway import launch_gateway
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/java_gateway.py", line 31, in <module>
    from py4j.java_gateway import java_import, JavaGateway, GatewayClient
ModuleNotFoundError: No module named 'py4j'

Body:
Add the following environment variable and also append spark's lib path to sys.path

import os
import sys

os.environ['SPARK_HOME'] = "/usr/lib/spark/"
sys.path.append("/usr/lib/spark/python/")

from pyspark import SparkConf, SparkContext # And then try to import SparkContext.


问:
Can I run a query, using BQ command line tool, from a file in Windows command prompt?
I saw this question, but the answer given was applicable only to Linux/Mac. I know this works in Powershell. Is there a way to do this same thing on Windows using the Command Prompt? </p>

答:
Try as below

```<code>C:\Program Files (x86)\Google\Cloud SDK>echo SELECT 'Hello' > qq.txt

C:\Program Files (x86)\Google\Cloud SDK>bq query < qq.txt
Waiting on bqjob_r56213d80_0000015b20a3b653_1 ... (0s) Current status: DONE
+-------+
|  f0_  |
+-------+
| Hello |
+-------+

C:\Program Files (x86)\Google\Cloud SDK>
</code>```

This was run in Google Cloud SDK Shell on Win

Body:
Try as below

C:\Program Files (x86)\Google\Cloud SDK>echo SELECT 'Hello' > qq.txt

C:\Program Files (x86)\Google\Cloud SDK>bq query < qq.txt
Waiting on bqjob_r56213d80_0000015b20a3b653_1 ... (0s) Current status: DONE
+-------+
|  f0_  |
+-------+
| Hello |
+-------+

C:\Program Files (x86)\Google\Cloud SDK>

This was run in Google Cloud SDK Shell on Win


问:
overriding httpclient version
I am building a spark application using aws sdk to access an S3 source. I am getting the below error:

java.lang.NoSuchMethodError:
  org.apache.http.conn.ssl.SSLConnectionSocketFactory.(Ljavax/net/ssl/SSLContext;Ljavax/net/ssl/HostnameVerifier;)V

Looked up online for solution and it appears my spark application is using a wrong httpclient. The following thread seems to offer a solution but not sure how I can override the default default httpclient.

What version of httpclient is compatible with the Amazon SDK v 1.11.5?

Here are the different httpclients that I have in my system.

```<code>./Applications/IBM Notes.app/Contents/MacOS/shared/eclipse/plugins/org.apache.wink_1.1.2.20150826-0855/lib/httpclient-4.0.1.jar
./Users/XXXXX/.ivy2/cache/org.apache.httpcomponents/httpclient/jars/httpclient-4.1.2.jar
./Users/XXXXX/.ivy2/cache/org.apache.httpcomponents/httpclient/jars/httpclient-4.5.1.jar
./Users/XXXXX/.m2/repository/org/apache/httpcomponents/httpclient/4.0.2/httpclient-4.0.2.jar
./Users/XXXXX/.m2/repository/org/apache/httpcomponents/httpclient/4.3.6/httpclient-4.3.6.jar
./Users/XXXXX/Downloads/aws-java-sdk-1.11.110/third-party/lib/httpclient-4.5.2.jar
./usr/local/aws-java/aws-java-sdk-1.11.109/third-party/lib/httpclient-4.5.2.jar
./usr/local/spark/spark-2.1.0-bin-hadoop2.7/jars/httpclient-4.5.2.jar
./usr/local/zeppelin/interpreter/alluxio/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/bqsql/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/elasticsearch/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/hbase/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/kylin/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/lens/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/livy/httpclient-4.3.4.jar
./usr/local/zeppelin/interpreter/pig/httpclient-4.3.6.jar
./usr/local/zeppelin/lib/httpclient-4.3.6.jar
./usr/local/zeppelin/lib/interpreter/httpclient-4.3.6.jar
</code>```

I do not have classpath specified, so I am not sure which httpclient it is picking. How do I override such that it always picks up ./usr/local/aws-java/aws-java-sdk-1.11.109/third-party/lib/httpclient-4.5.2.jar?

答: Copying httpclient-4.5.2.jar and  httpcore-4.4.4.jar into the zeppelin/interpreter/spark folder got rid of this error.</p>

Title: overriding httpclient version

Body:
I am building a spark application using aws sdk to access an S3 source. I am getting the below error:

java.lang.NoSuchMethodError:
  org.apache.http.conn.ssl.SSLConnectionSocketFactory.(Ljavax/net/ssl/SSLContext;Ljavax/net/ssl/HostnameVerifier;)V

Looked up online for solution and it appears my spark application is using a wrong httpclient. The following thread seems to offer a solution but not sure how I can override the default default httpclient.

What version of httpclient is compatible with the Amazon SDK v 1.11.5?

Here are the different httpclients that I have in my system.

./Applications/IBM Notes.app/Contents/MacOS/shared/eclipse/plugins/org.apache.wink_1.1.2.20150826-0855/lib/httpclient-4.0.1.jar
./Users/XXXXX/.ivy2/cache/org.apache.httpcomponents/httpclient/jars/httpclient-4.1.2.jar
./Users/XXXXX/.ivy2/cache/org.apache.httpcomponents/httpclient/jars/httpclient-4.5.1.jar
./Users/XXXXX/.m2/repository/org/apache/httpcomponents/httpclient/4.0.2/httpclient-4.0.2.jar
./Users/XXXXX/.m2/repository/org/apache/httpcomponents/httpclient/4.3.6/httpclient-4.3.6.jar
./Users/XXXXX/Downloads/aws-java-sdk-1.11.110/third-party/lib/httpclient-4.5.2.jar
./usr/local/aws-java/aws-java-sdk-1.11.109/third-party/lib/httpclient-4.5.2.jar
./usr/local/spark/spark-2.1.0-bin-hadoop2.7/jars/httpclient-4.5.2.jar
./usr/local/zeppelin/interpreter/alluxio/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/bqsql/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/elasticsearch/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/hbase/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/kylin/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/lens/httpclient-4.3.6.jar
./usr/local/zeppelin/interpreter/livy/httpclient-4.3.4.jar
./usr/local/zeppelin/interpreter/pig/httpclient-4.3.6.jar
./usr/local/zeppelin/lib/httpclient-4.3.6.jar
./usr/local/zeppelin/lib/interpreter/httpclient-4.3.6.jar

I do not have classpath specified, so I am not sure which httpclient it is picking. How do I override such that it always picks up ./usr/local/aws-java/aws-java-sdk-1.11.109/third-party/lib/httpclient-4.5.2.jar?


问:
Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY
I'm fairly new to JSON parsing, I'm using the Retrofit library of Square and ran into this problem.

I'm trying to parse this JSON reponse:

```<code>[
      {
        "id": 3,
        "username": "jezer",
        "regid": "oiqwueoiwqueoiwqueoiwq",
        "url": "http:\/\/192.168.63.175:3000\/users\/3.json"
      },
      {
        "id": 4,
        "username": "emulator",
        "regid": "qwoiuewqoiueoiwqueoq",
        "url": "http:\/\/192.168.63.175:3000\/users\/4.json"
      },
      {
        "id": 7,
        "username": "test",
        "regid": "ksadqowueqiaksj",
        "url": "http:\/\/192.168.63.175:3000\/users\/7.json"
      }
]
</code>```

Here are my models:

```<code>public class Contacts {

    public List<User> contacts;

}
</code>```

...

```<code>public class User {

    String username;
    String regid;

    @Override
    public String toString(){
        return(username);
    }

}
</code>```

my Interface:

```<code>public interface ContactsInterface {

    @GET("/users.json")
    void contacts(Callback<Contacts> cb);

}
</code>```

my success method:

```<code>@Override
public void success(Contacts c, Response r) {
    List<String> names = new ArrayList<String>();
    for (int i = 0; i < c.contacts.size(); i++) {
        String name = c.contacts.get(i).toString();
        Log.d("Names", "" + name);
        names.add(name);
    }
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, names);
    mSentTo.setAdapter(spinnerAdapter);
}
</code>```

When I use it on my success method it throws the error

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column2

What is wrong here?

答:
in your interface
replace

```<code>@GET("/users.json")
void contacts(Callback<Contacts> cb);
</code>```

By this code

```<code>@GET("/users.json")
void contacts(Callback<List<Contacts>> cb);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm fairly new to JSON parsing, I'm using the Retrofit library of Square and ran into this problem.

I'm trying to parse this JSON reponse:

[
      {
        "id": 3,
        "username": "jezer",
        "regid": "oiqwueoiwqueoiwqueoiwq",
        "url": "http:\/\/192.168.63.175:3000\/users\/3.json"
      },
      {
        "id": 4,
        "username": "emulator",
        "regid": "qwoiuewqoiueoiwqueoq",
        "url": "http:\/\/192.168.63.175:3000\/users\/4.json"
      },
      {
        "id": 7,
        "username": "test",
        "regid": "ksadqowueqiaksj",
        "url": "http:\/\/192.168.63.175:3000\/users\/7.json"
      }
]

Here are my models:

public class Contacts {

    public List<User> contacts;

}

...

public class User {

    String username;
    String regid;

    @Override
    public String toString(){
        return(username);
    }

}

my Interface:

public interface ContactsInterface {

    @GET("/users.json")
    void contacts(Callback<Contacts> cb);

}

my success method:

@Override
public void success(Contacts c, Response r) {
    List<String> names = new ArrayList<String>();
    for (int i = 0; i < c.contacts.size(); i++) {
        String name = c.contacts.get(i).toString();
        Log.d("Names", "" + name);
        names.add(name);
    }
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, names);
    mSentTo.setAdapter(spinnerAdapter);
}

When I use it on my success method it throws the error

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column2

What is wrong here?

Body:
in your interface
replace

@GET("/users.json")
void contacts(Callback<Contacts> cb);

By this code

@GET("/users.json")
void contacts(Callback<List<Contacts>> cb);


问:
Best practices if your Build is taking too long in Visual Studio
I have moderate size solution in Visual Studio which takes around 5 minutes to build (It take that long because of FxCop and other post build steps).
My problem is, Visual Studio stops responding while it's building. You can't continue working as VS almost hangs. I tried using two VS instances, just using one for build, but it keeps crashing every now and then.

My question is, How to not waste time looking at Visual Studio building your large/moderate project. Are there any best practices for this?

答:
You certainly don't need to run a
static code analysis each time you
build your solution.

Reduce the number of your project by
merging some could also helps a lot.

What other post build tasks have you put in place ?

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Romain Verdier


问:
A Sales RepMIN, MAX, and AVG
I am trying to find a SalesReps Lowest Cost Order, their average cost and their highest cost. I am expecting the output to be something like.

```<code>[SalesRep]     [Max]     [AVG]     [Min]
 #12121         12         6         2
</code>```

The Code I currently have is

```<code>SELECT DISTINCT REP, MAX(Amount), AVG(Amount), MIN(Amount)
FROM Orders
WHERE OrderDate BETWEEN '1990-01-01' AND '1999-12-30';
</code>```

I understand the Select statement is wrong I just don't know where to go from here. Any help would be greatly appreciated.

答:
Add the missing group by:

```<code>select REP,
    MAX(Amount),
    AVG(Amount),
    MIN(Amount)
from Orders
where OrderDate between '1990-01-01' and '1999-12-30'
group by REP --<-- here
</code>```

Title: A Sales RepMIN, MAX, and AVG

Body:
I am trying to find a SalesReps Lowest Cost Order, their average cost and their highest cost. I am expecting the output to be something like.

[SalesRep]     [Max]     [AVG]     [Min]
 #12121         12         6         2

The Code I currently have is

SELECT DISTINCT REP, MAX(Amount), AVG(Amount), MIN(Amount)
FROM Orders
WHERE OrderDate BETWEEN '1990-01-01' AND '1999-12-30';

I understand the Select statement is wrong I just don't know where to go from here. Any help would be greatly appreciated.

Body:
Add the missing group by:

select REP,
    MAX(Amount),
    AVG(Amount),
    MIN(Amount)
from Orders
where OrderDate between '1990-01-01' and '1999-12-30'
group by REP --<-- here


问:
Java Tree Recursion parameter issues
I am attempting to give a void function to a Tree. It calculates some parameters and uses Ids  to reference some coordinates and the distance between them. The problem I have is that every recursion call returns me 0 on both parameters I use, I thought in Java every variable was a reference so this would work, but  I seem to be missing something. Here is the code:

```<code>public void volumeandcost(Integer  volume,Float cost){
    if(children().equals(0)){//children() returns the number of children our tree has
        volume=volume+getCapacidad(this.root);//root is the Id
    }
    else{//recursive call
        ArrayList<Integer> myvol= new ArrayList();
        ArrayList<Float> mycost=new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Integer(0));
            mycost.add(new Float(0.0));
            children.get(i).volumeandcost(myvol.get(i), mycost.get(i));
            cost=cost+mycost.get(i)+myvol.get(i)*
                  square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId()));
        }
        //this calculates our volume in case we have children
        volume=min(getCapacidad(root)*3,mysum(myvol)+getCapacidad(root));
    }
}
</code>```

I call this function with both parameters initially set at 0, and they come back in the same way after the call to volumeandcost.

After following some advice I implemented a new class Pair like this:

```<code>public class Pair {
Integer vol;Float cost;
public Pair (){this.vol=new Integer(0);this.cost=new Float(0);}
Integer getVol(){ return this.vol;}
Float getCost(){ return this.cost;}
void setVol(Integer x){this.vol=x ;}
void setCost(Float x){this.cost=x ;}
void addVol(Integer x){this.vol=this.vol+x;}
    void addCost(Float x){this.cost=this.cost+x;}
}
</code>```

and modified the function so that it's like this:

```<code>    public void volumeandcostp(Pair p){
    if(children().equals(0)){
        p.setVol(p.getVol() + getCapacidad(this.root));//tenemos el volumen
    }
    else{//recursion
        ArrayList<Pair> myvol= new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Pair());
            children.get(i).volumeandcostp(myvol.get(i));
            myvol.get(i).getCost());
            p.addCost(myvol.get(i).getCost()+ myvol.get(i).getVol()*                            square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId())));
        }              p.setVol(min(getCapacidad(root)*3,mysump(myvol)+getCapacidad(root)));
    }
}
</code>```

But all the getters from Pair keep giving me 0 as answer.

答:
As provided in other answers, you can only alter the state of the objects when you pass them to a method- Java is call by value.
Consider this instead of Integers :

```<code>List<Integer> list = new ArrayList<Integer>();
System.out.println( "Before adding size is " + list.size() );
modifyList(list);
System.out.println( "After adding size is " + list.size() );

public void modifyList( List<Integer> list )
{
   list.add( 5 );
}
</code>```

Why do you see the list.size() modified ? Because list's state is modified not the original reference to list itself, the copied reference that passed to method played with a method called add and modified the state of object it refers to. So when you call size() using original reference , you will get the updated state of the object.

Now, to tackle your problem, you could do it with devising your own class, some thing like :

```<code>class Metrics
{
   Integer volume;
   Float cost;
}
</code>```

Pass Metrics to your new method and update the fields volume, cost inside your method.

Title: Java Tree Recursion parameter issues

Body:
I am attempting to give a void function to a Tree. It calculates some parameters and uses Ids  to reference some coordinates and the distance between them. The problem I have is that every recursion call returns me 0 on both parameters I use, I thought in Java every variable was a reference so this would work, but  I seem to be missing something. Here is the code:

public void volumeandcost(Integer  volume,Float cost){
    if(children().equals(0)){//children() returns the number of children our tree has
        volume=volume+getCapacidad(this.root);//root is the Id
    }
    else{//recursive call
        ArrayList<Integer> myvol= new ArrayList();
        ArrayList<Float> mycost=new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Integer(0));
            mycost.add(new Float(0.0));
            children.get(i).volumeandcost(myvol.get(i), mycost.get(i));
            cost=cost+mycost.get(i)+myvol.get(i)*
                  square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId()));
        }
        //this calculates our volume in case we have children
        volume=min(getCapacidad(root)*3,mysum(myvol)+getCapacidad(root));
    }
}

I call this function with both parameters initially set at 0, and they come back in the same way after the call to volumeandcost.

After following some advice I implemented a new class Pair like this:

public class Pair {
Integer vol;Float cost;
public Pair (){this.vol=new Integer(0);this.cost=new Float(0);}
Integer getVol(){ return this.vol;}
Float getCost(){ return this.cost;}
void setVol(Integer x){this.vol=x ;}
void setCost(Float x){this.cost=x ;}
void addVol(Integer x){this.vol=this.vol+x;}
    void addCost(Float x){this.cost=this.cost+x;}
}

and modified the function so that it's like this:

    public void volumeandcostp(Pair p){
    if(children().equals(0)){
        p.setVol(p.getVol() + getCapacidad(this.root));//tenemos el volumen
    }
    else{//recursion
        ArrayList<Pair> myvol= new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Pair());
            children.get(i).volumeandcostp(myvol.get(i));
            myvol.get(i).getCost());
            p.addCost(myvol.get(i).getCost()+ myvol.get(i).getVol()*                            square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId())));
        }              p.setVol(min(getCapacidad(root)*3,mysump(myvol)+getCapacidad(root)));
    }
}

But all the getters from Pair keep giving me 0 as answer.

Body:
As provided in other answers, you can only alter the state of the objects when you pass them to a method- Java is call by value.
Consider this instead of Integers :

List<Integer> list = new ArrayList<Integer>();
System.out.println( "Before adding size is " + list.size() );
modifyList(list);
System.out.println( "After adding size is " + list.size() );

public void modifyList( List<Integer> list )
{
   list.add( 5 );
}

Why do you see the list.size() modified ? Because list's state is modified not the original reference to list itself, the copied reference that passed to method played with a method called add and modified the state of object it refers to. So when you call size() using original reference , you will get the updated state of the object.

Now, to tackle your problem, you could do it with devising your own class, some thing like :

class Metrics
{
   Integer volume;
   Float cost;
}

Pass Metrics to your new method and update the fields volume, cost inside your method.


问:
Golang route not working
I just started to get into golang and as I plan to host at least two websites, I chose to use Mux to display different routes by "filtering" domains. Whenever I try to access my main route, it just gives me an 404 error. (Also, the fact that the "www" part is absent is perfectly normal. I don't type that to access the site).

But if I launch the server as a file server, I can access my files, so the server in itself is working I guess

```<code>func redirect(w http.ResponseWriter, req *http.Request) {
    target := "https://" + req.Host + req.URL.Path
    http.Redirect(w, req, target,
        http.StatusTemporaryRedirect)
}

func main() {
    go http.ListenAndServe(":80", http.HandlerFunc(redirect)) // Redirection

    // Serveur sécurisé

    r := mux.NewRouter()
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("/root/go/src/web/static/"))))
    s := r.Host("echecderi.me").Subrouter()
    s.HandleFunc("/", indexEchec)

    http.ListenAndServeTLS(":443", "domain-crt.pem", "domain-key.pem", nil)
}

func indexEchec(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<h1>Echec de rime</h1> </br> <img src=\"/static/echecderime/echec.gif\">")
}
</code>```

答: I think you need to give r as the last parameter to http.ListenAndServeTLS.

Title: Golang route not working

Body:
I just started to get into golang and as I plan to host at least two websites, I chose to use Mux to display different routes by "filtering" domains. Whenever I try to access my main route, it just gives me an 404 error. (Also, the fact that the "www" part is absent is perfectly normal. I don't type that to access the site).

But if I launch the server as a file server, I can access my files, so the server in itself is working I guess

func redirect(w http.ResponseWriter, req *http.Request) {
    target := "https://" + req.Host + req.URL.Path
    http.Redirect(w, req, target,
        http.StatusTemporaryRedirect)
}

func main() {
    go http.ListenAndServe(":80", http.HandlerFunc(redirect)) // Redirection

    // Serveur sécurisé

    r := mux.NewRouter()
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("/root/go/src/web/static/"))))
    s := r.Host("echecderi.me").Subrouter()
    s.HandleFunc("/", indexEchec)

    http.ListenAndServeTLS(":443", "domain-crt.pem", "domain-key.pem", nil)
}

func indexEchec(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "
Echec de rime

 ")
}


问:
How to hide default artisan commands from "php artisan list" of commands?
I am working on a CLI application based on Laravel 5.4.

I have created my custom commands and they are working as expected.

The issue, I am facing is, whenever I run php artisan list, it shows all commands - my custom commands and default artisan commands.

I need to show only my custom commands in packaged app.

Is there any way to solve this?

I have already checked https://laracasts.com/discuss/channels/general-discussion/remove-default-commands-from-artisan and solution given there is not working for Laravel 5.4.

I have checked Remove command from php artisan list but it asks for specific commands. I want to remove all built-in commands from php artisan list.

Update

I have found a dirty way:

If I comment out line #58 from framework/src/Illuminate/Console/Application.php

```<code>$this->bootstrap();
</code>```

i.e. https://github.com/laravel/framework/blob/5.4/src/Illuminate/Console/Application.php#L58 output is as expected.

Now I am looking for a way to stop/control bootstrap() function/process.

答:
To hide a command from php artisan list -this will only hide the command and won't disable it-

before going into how to hide it, let's take a look at the property $hidden inside the the Illuminate\Console\Command object , by default it's a false , when you set it to true , you will get all of your artisan list hidden.

and to hide a specific command , you will need to set this property to hidden inside each class you want to hide it's command ,

for example , when you hit php artisan list will prompt a list as follows :

```<code>.....
cache
  cache:clear          Flush the application cache
  cache:forget         Remove an item from the cache
  cache:table          Create a migration for the cache database table
.....
</code>```

this means that , the object which is responsible about clearing the cache is located into Illuminate\Cache\Console.

now to hide the cache:clear command , inside Illuminate\Cache\Console you will get ClearCommand.php object .

update it and set the property $hidden to true , as follows :

```<code>protected $hidden = true;
</code>```

Body:
I am working on a CLI application based on Laravel 5.4.

I have created my custom commands and they are working as expected.

The issue, I am facing is, whenever I run php artisan list, it shows all commands - my custom commands and default artisan commands.

I need to show only my custom commands in packaged app.

Is there any way to solve this?

I have already checked https://laracasts.com/discuss/channels/general-discussion/remove-default-commands-from-artisan and solution given there is not working for Laravel 5.4.

I have checked Remove command from php artisan list but it asks for specific commands. I want to remove all built-in commands from php artisan list.

Update

I have found a dirty way:

If I comment out line #58 from framework/src/Illuminate/Console/Application.php

$this->bootstrap();

i.e. https://github.com/laravel/framework/blob/5.4/src/Illuminate/Console/Application.php#L58 output is as expected.

Now I am looking for a way to stop/control bootstrap() function/process.

Body:
To hide a command from php artisan list -this will only hide the command and won't disable it-

before going into how to hide it, let's take a look at the property $hidden inside the the Illuminate\Console\Command object , by default it's a false , when you set it to true , you will get all of your artisan list hidden.

and to hide a specific command , you will need to set this property to hidden inside each class you want to hide it's command ,

for example , when you hit php artisan list will prompt a list as follows :

.....
cache
  cache:clear          Flush the application cache
  cache:forget         Remove an item from the cache
  cache:table          Create a migration for the cache database table
.....

this means that , the object which is responsible about clearing the cache is located into Illuminate\Cache\Console.

now to hide the cache:clear command , inside Illuminate\Cache\Console you will get ClearCommand.php object .

update it and set the property $hidden to true , as follows :

protected $hidden = true;


问:
Django: order by field of many-to-many relation
Given django models A and B:

```<code>class A(models.Model):
    things = models.ManyToManyField('B')

class B(models.Model):
    score = models.FloatField()
    text = models.CharField(max_length=100)
</code>```

How do I get a list of A entities ordered by the text of the highest-scoring B in things?

答:
This sort of thing is really hard. Aggregation can help you if you want to sort by the score:

```<code>from django.db.models import Max
A.objects.annotate(highest_b=Max(B__score)).order_by('highest_b')
</code>```

But in effect you want to do two operations: aggregate by the highest score, then sort by the text of the item with that score. That's tricky no matter what language you do it in. I've written about this issue on my blog - for your purposes, I think doing it in SQL via the .raw() method is probably the easiest.

Body:
Given django models A and B:

class A(models.Model):
    things = models.ManyToManyField('B')

class B(models.Model):
    score = models.FloatField()
    text = models.CharField(max_length=100)

How do I get a list of A entities ordered by the text of the highest-scoring B in things?

Body:
This sort of thing is really hard. Aggregation can help you if you want to sort by the score:

from django.db.models import Max
A.objects.annotate(highest_b=Max(B__score)).order_by('highest_b')

But in effect you want to do two operations: aggregate by the highest score, then sort by the text of the item with that score. That's tricky no matter what language you do it in. I've written about this issue on my blog - for your purposes, I think doing it in SQL via the .raw() method is probably the easiest.


问:
How to post data using HttpClient? (an answer than actually works)
There is another question about this, but it doesn't have a functioning solution at the end, and the only good answer, for some reason, doesn't work, not for the guy who ask it, not for me either.

This such question is here:
How to post data using HttpClient?

Given the corresponding aclarations, this is the code I have so far:

The methods to call the method who connects with the web server:

```<code>private void Button_Click(object sender, System.EventArgs e)
{
    //. . . DO SOMETHING . . .
    PopulateListView();

    //. . . DO SOMETHING ELSE . . .
}

private void PopulateListView()
{
   //. . . DO SOMETHING . . .

   list = await "http://web.server.url".GetRequest<List<User>>();

   //. . . DO SOMETHING ELSE . . .
}
</code>```

The method than connects with the web server:

```<code>public async static Task<T> SendGetRequest<T>(this string url)
{
    try
    {
        var uri = new Uri(url);
        HttpClient client = new HttpClient();
        //Preparing to have something to read
        var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
                });

        HttpResponseMessage response = await client.PostAsync(uri, formContent);

        #region - - Envio anterior (NO FUNCIONO, SIN USO) - -
        //var stringContent = new StringContent("markString");
        //var sending = await client.PostAsync(url, stringContent);

        //MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
        #endregion

        //Reading data
        //var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();
        MainActivity.ConsoleData = json.ToString();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error: "+ex.ToString());
        return default(T);
    }
}
</code>```

You maybe guessed it, but I'm trying to make a method that send some data (through POST) called "markString" to a web-server than receive it and, depending of the "markString" it returns certain json Objects.

This web server is already working properly (I tested it out with some plug-in, it work like it should)

This method is supposed to send the "markString" and receive the data back so then i can use it in the app.

I'm making a Xamarin Android application.

Also have in mind than I don't have any connection problem at all, in fact the app is sending data in an excellent matter when I try to do it using web client, but I want it to send it using HttpClient.

The problem

The code is not returning anything. Any request for information, clarification, question, constructive comments or anything than can lead to an answer would be greatly appreciated too.

Thanks in advance.

答:
Most deadlock scenarios with asynchronous code are due to blocking further up the call stack.

By default await captures a "context" (in this case, a UI context), and resumes executing in that context. So, if you call an async method and the block on the task (e.g., GetAwaiter().GetResult(), Wait(), or Result), then the UI thread is blocked, which prevents the async method from resuming and completing.

Body:
There is another question about this, but it doesn't have a functioning solution at the end, and the only good answer, for some reason, doesn't work, not for the guy who ask it, not for me either.

This such question is here:
How to post data using HttpClient?

Given the corresponding aclarations, this is the code I have so far:

The methods to call the method who connects with the web server:

private void Button_Click(object sender, System.EventArgs e)
{
    //. . . DO SOMETHING . . .
    PopulateListView();

    //. . . DO SOMETHING ELSE . . .
}

private void PopulateListView()
{
   //. . . DO SOMETHING . . .

   list = await "http://web.server.url".GetRequest<List<User>>();

   //. . . DO SOMETHING ELSE . . .
}

The method than connects with the web server:

public async static Task<T> SendGetRequest<T>(this string url)
{
    try
    {
        var uri = new Uri(url);
        HttpClient client = new HttpClient();
        //Preparing to have something to read
        var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("OperationType", "eaf7d94356e7fd39935547f6f15e1c4c234245e4")
                });

        HttpResponseMessage response = await client.PostAsync(uri, formContent);

        #region - - Envio anterior (NO FUNCIONO, SIN USO) - -
        //var stringContent = new StringContent("markString");
        //var sending = await client.PostAsync(url, stringContent);

        //MainActivity.ConsoleData = await client.PostAsync(url, stringContent);
        #endregion

        //Reading data
        //var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();
        MainActivity.ConsoleData = json.ToString();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
    }
    catch(Exception ex)
    {
        Console.WriteLine("Error: "+ex.ToString());
        return default(T);
    }
}

You maybe guessed it, but I'm trying to make a method that send some data (through POST) called "markString" to a web-server than receive it and, depending of the "markString" it returns certain json Objects.

This web server is already working properly (I tested it out with some plug-in, it work like it should)

This method is supposed to send the "markString" and receive the data back so then i can use it in the app.

I'm making a Xamarin Android application.

Also have in mind than I don't have any connection problem at all, in fact the app is sending data in an excellent matter when I try to do it using web client, but I want it to send it using HttpClient.

The problem

The code is not returning anything. Any request for information, clarification, question, constructive comments or anything than can lead to an answer would be greatly appreciated too.

Thanks in advance.


问:
Why is my canvas line so small and disoriented?
In my very simple code example below, I am trying to draw a box, 10 pixels in from the margin all the way around the outside of a canvas. Despite getting what seem like legit values from the screen extends of the browser window, I am only getting an L-shaped line, which seems really odd. My code seems very straight forward. So 2 questions:

Why is it so small (eg not going across the whole browser window?

Why isn't it a box like the code suggests it should be?

X:

Y:

<canvas id="DemoCanvas" width=100% height=100%></canvas>

```

Here's the result which you can clearly see is both way too small and not a box at all:

答:
Your problem stems from the common misunderstanding of the canvas' height and width properties. You're giving the values as percents, but that wont work. From MDN:

HTMLCanvasElement.height Is a positive integer reflecting the height
  HTML attribute of the  element interpreted in CSS pixels. When
  the attribute is not specified, or if it is set to an invalid value,
  like a negative, the default value of 150 is used.

So you should use plain integers instead. If you need a dynamic size, you can use javascript to update the values.

X:

Y:

<canvas id="DemoCanvas" width="628" height="200"></canvas>

```

Body:
In my very simple code example below, I am trying to draw a box, 10 pixels in from the margin all the way around the outside of a canvas. Despite getting what seem like legit values from the screen extends of the browser window, I am only getting an L-shaped line, which seems really odd. My code seems very straight forward. So 2 questions:

Why is it so small (eg not going across the whole browser window?

Why isn't it a box like the code suggests it should be?

X:

Y:

<canvas id="DemoCanvas" width=100% height=100%></canvas>

Here's the result which you can clearly see is both way too small and not a box at all:

Body:
Your problem stems from the common misunderstanding of the canvas' height and width properties. You're giving the values as percents, but that wont work. From MDN:

HTMLCanvasElement.height Is a positive integer reflecting the height
  HTML attribute of the  element interpreted in CSS pixels. When
  the attribute is not specified, or if it is set to an invalid value,
  like a negative, the default value of 150 is used.

So you should use plain integers instead. If you need a dynamic size, you can use javascript to update the values.

<html>
<head></head>
<body>
<p id="X">X:</p>
<p id="Y">Y:</p>
<!--<form>
Timeline Item: <input type="text" name="item"><br>
Timeline Date: <input type="date" name="date"><br>
</form>-->
<canvas id="DemoCanvas" width="628" height="200"></canvas>

<script>

var canvas = document.getElementById('DemoCanvas');
var xoutput = document.getElementById('X');
var youtput = document.getElementById('Y');

// Always check for properties and methods, to make sure your code doesn't break in other browsers.
if (canvas.getContext)
 {
  var margin = 10;

  var startx = margin;
  var starty = margin;

  var endx = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) - margin;
 var endy = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - margin;

 xoutput.innerHTML = endx;
 youtput.innerHTML = endy-margin;

  var context = canvas.getContext('2d');

   context.beginPath();

   context.moveTo(startx,starty);
   context.lineTo(endx,starty);
 context.lineTo(endx,endy);
  context.lineTo(startx,endy);
   context.lineTo(startx,starty);

  context.stroke();
 }
</script>

</body>
</html>


问:
Time complexity of while some condition is true:
In python, what is the time complexity for the very first line in

```<code>While x==true:
    line
    line
    if something is equal to something:
         x=false
         return something
</code>```

I'm guessing it may be O(n) as it depends on the number of iterations based on the input

答:
If you have an upper bound on the number of iterations for that if condition to be true, it would be that. For example if incrementing the value of something with each iteration of the loop.

However, if it is more complex than just only incrementing every iteration (no decrementing), then this is known as the halting problem and there is no known upper bound.

Body:
In python, what is the time complexity for the very first line in

While x==true:
    line
    line
    if something is equal to something:
         x=false
         return something

I'm guessing it may be O(n) as it depends on the number of iterations based on the input


问:
T-SQL: calculate age then add character to result
Been stuck on this one for a while now. Let's say I have a Client table like the one here:

```<code>Name   BirthDayNum   BirthMonthNum   BirthYearNum
--------------------------------------------------
John       23             12             1965
Jane        4              9             1975
Joe         6              3             1953
</code>```

Currently I am calculating the age using this syntax: (sorry if it is hard to read)

```<code>DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE())
- (CASE WHEN dateadd(YY, DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE()),
CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101)) > getdate() THEN 1 ELSE 0 END) AS 'Client Age'
</code>```

This will give me the age in years. Of course if I want months, I just change the DATEDIFF(year to month. So, what I am trying to do now is this.

Continue to calculate the age, but instead of returning either years or months, I would like to return the age in years and months, but also, concat a 'y' and 'm' within the value as well.  Ex.  41y 11m for Jane above.

So basically I am trying to figure out how to add a char to the return value, as well as calculate the remaining months beyond the year calculation.

Any help would be greatly appreciated!

答:
If you are on 2008 or lesser and can't use datefromparts...</p>

```<code>declare @table table ([Name] varchar(4), BirthDayNum int, BirthMonthNum int, BirthYearNum int)
insert into @table
values
('John',23,12,1965),
('Jane',4,9,1975),
('Day',30,3,1990)

;with cte as(
    select
        [Name],
        cast(BirthYearNum as varchar(4)) + '/' + cast(BirthMonthNum as varchar(2)) + '/' + cast(BirthDayNum as varchar(2)) as DOB
    from
        @table)

select
     [Name]
     ,DOB
     ,datediff(year,DOB,GETDATE()) as Years
     ,datediff(month,DOB,GETDATE()) %12 as Months
     ,rtrim(cast(datediff(year,DOB,GETDATE()) as char(2))) + 'y ' + rtrim(cast(datediff(month,DOB,GETDATE()) %12 as char(2))) + 'm' as  Age
from cte
</code>```

Body:
Been stuck on this one for a while now. Let's say I have a Client table like the one here:

Name   BirthDayNum   BirthMonthNum   BirthYearNum
--------------------------------------------------
John       23             12             1965
Jane        4              9             1975
Joe         6              3             1953

Currently I am calculating the age using this syntax: (sorry if it is hard to read)

DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE())
- (CASE WHEN dateadd(YY, DATEDIFF(year, CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101), GETDATE()),
CONVERT(datetime, CAST(client.BirthMonthNum AS varchar(2))
+ '-' + CAST(client.BirthDayNum AS varchar(2))
+ '-' + CAST(client.BirthYearNum AS varchar(4)), 101)) > getdate() THEN 1 ELSE 0 END) AS 'Client Age'

This will give me the age in years. Of course if I want months, I just change the DATEDIFF(year to month. So, what I am trying to do now is this.

Continue to calculate the age, but instead of returning either years or months, I would like to return the age in years and months, but also, concat a 'y' and 'm' within the value as well.  Ex.  41y 11m for Jane above.

So basically I am trying to figure out how to add a char to the return value, as well as calculate the remaining months beyond the year calculation.

Any help would be greatly appreciated!

Body:
If you are on 2008 or lesser and can't use datefromparts...

declare @table table ([Name] varchar(4), BirthDayNum int, BirthMonthNum int, BirthYearNum int)
insert into @table
values
('John',23,12,1965),
('Jane',4,9,1975),
('Day',30,3,1990)

;with cte as(
    select
        [Name],
        cast(BirthYearNum as varchar(4)) + '/' + cast(BirthMonthNum as varchar(2)) + '/' + cast(BirthDayNum as varchar(2)) as DOB
    from
        @table)

select
     [Name]
     ,DOB
     ,datediff(year,DOB,GETDATE()) as Years
     ,datediff(month,DOB,GETDATE()) %12 as Months
     ,rtrim(cast(datediff(year,DOB,GETDATE()) as char(2))) + 'y ' + rtrim(cast(datediff(month,DOB,GETDATE()) %12 as char(2))) + 'm' as  Age
from cte


问:
Decorator pattern in Objective-C
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

```<code>// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end
</code>```

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.

答:
Your comment in the interface:

```<code>// all methods of UIScrollView need to be duplicated here -- this is the problem
</code>```

is incorrect.  You do not have to redeclare methods inherited from the superclass in the interface even if you are re-implementing them.  This is not C++.

You do, however, have to create implementations of all the methods that redirect to the scroll view in the instance variable.  There may be a clever way to intercept the messages to instances of your subclass and automatically forward them to the instance variable, but I can't think what it would be off the top of my head.

As others have said, consider using a category of UIScrollView instead.  Categories are not a direct replacement for decorators since implementing a category will give all instances of UIScrollView your custom method, but that probably won't be a problem.

Update

You can use -forwardingTargetForSelector: to redirect messages you haven't implemented to the decorated object.  However, be aware that this will be slower than implementing each method directly or using categories.

Title: Decorator pattern in Objective-C

Body:
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.

Body:
Your comment in the interface:

// all methods of UIScrollView need to be duplicated here -- this is the problem

is incorrect.  You do not have to redeclare methods inherited from the superclass in the interface even if you are re-implementing them.  This is not C++.

You do, however, have to create implementations of all the methods that redirect to the scroll view in the instance variable.  There may be a clever way to intercept the messages to instances of your subclass and automatically forward them to the instance variable, but I can't think what it would be off the top of my head.

As others have said, consider using a category of UIScrollView instead.  Categories are not a direct replacement for decorators since implementing a category will give all instances of UIScrollView your custom method, but that probably won't be a problem.

Update

You can use -forwardingTargetForSelector: to redirect messages you haven't implemented to the decorated object.  However, be aware that this will be slower than implementing each method directly or using categories.


问:
From a container running on Docker for Windows, how can I access a port on the host?
I'm running a CentOS-based container on Docker for Windows and trying to connect to an http service running on port 8545 of my host environment.

I've tried this, attempting a variety of suspected host names and IP addresses:

curl http://localhost:8545

But the error message I get is "curl: (7) Failed connect to localhost:8545; Connection refused"

How should I figure out what IP Address to use? Is there anything I need to configure as far as allowing the port number to be accessed from inside the container?

答: You can access the host using its ip but localhost/127.0.0.1 won't work (they will resolve to the Linux VM that is part of docker for windows). If you use the default network settings, your host should be reachable on 10.0.75.1 from your container</p>


问:
c++ parse datetime from string with different timezone
How to parse datetime from string which is in different timezone? I have dates and times in simple strings like 2011-01-15 04:01:00, which are from New York timezone (Eastern: UTC -5/-4). I wrote the code below, but it automatically converts timezone to my local timezone.

Is it possible to do it without any additional C++ 11 libraries like Boost so as not to add complexity to a very simple operation? If not, an example with Boost would be nice.

I use Visual Studio 2013 on Windows 8.1.

```<code>#include <ctime>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
    vector<string> datetimes{ "2011-01-15 04:01:00",
                              "2014-06-07 23:17:00",
                              "2015-11-29 14:55:00" };

    for (auto i : datetimes)
    {
        stringstream ss1(i);
        tm tm;
        ss1 >> get_time(&tm, "%Y-%m-%d %H:%M:%S");
        stringstream ss2;
        ss2 << put_time(&tm, "%c %Z");
        cout << ss2.str() << endl;
    }
}
</code>```

Output:

```<code>01/15/11 04:01:00 Russia TZ 2 Daylight Time
06/07/14 23:17:00 Russia TZ 2 Daylight Time
11/29/15 14:55:00 Russia TZ 2 Daylight Time
</code>```

But I need the output to be like:

```<code>01/15/11 04:01:00 New York / Eastern (or whatever right name)
06/07/14 23:17:00 New York
11/29/15 14:55:00 New York
</code>```

答:
Here is your program using Howard Hinnant's timezone library (free, open-source, will run with VS-2013, does require some installation).

```<code>#include "tz.h"
#include <string>
#include <sstream>
#include <vector>
#include <iostream>

int main()
{
    using namespace std;
    using namespace date;
    vector<string> datetimes{ "2011-01-15 04:01:00",
                              "2014-06-07 23:17:00",
                              "2015-11-29 14:55:00" };

    zoned_seconds zt("America/New_York");
    for (auto const& i : datetimes)
    {
        stringstream ss1(i);
        local_seconds tm;
        ss1 >> parse("%F %T", tm);
        zt = tm;
        stringstream ss2;
        ss2 << format("%D %T %Z", zt);
        cout << ss2.str() << endl;
    }
}
</code>```

Output:

```<code>01/15/11 04:01:00 EST
06/07/14 23:17:00 EDT
11/29/15 14:55:00 EST
</code>```

Body:
How to parse datetime from string which is in different timezone? I have dates and times in simple strings like 2011-01-15 04:01:00, which are from New York timezone (Eastern: UTC -5/-4). I wrote the code below, but it automatically converts timezone to my local timezone.

Is it possible to do it without any additional C++ 11 libraries like Boost so as not to add complexity to a very simple operation? If not, an example with Boost would be nice.

I use Visual Studio 2013 on Windows 8.1.

#include <ctime>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
    vector<string> datetimes{ "2011-01-15 04:01:00",
                              "2014-06-07 23:17:00",
                              "2015-11-29 14:55:00" };

    for (auto i : datetimes)
    {
        stringstream ss1(i);
        tm tm;
        ss1 >> get_time(&tm, "%Y-%m-%d %H:%M:%S");
        stringstream ss2;
        ss2 << put_time(&tm, "%c %Z");
        cout << ss2.str() << endl;
    }
}

Output:

01/15/11 04:01:00 Russia TZ 2 Daylight Time
06/07/14 23:17:00 Russia TZ 2 Daylight Time
11/29/15 14:55:00 Russia TZ 2 Daylight Time

But I need the output to be like:

01/15/11 04:01:00 New York / Eastern (or whatever right name)
06/07/14 23:17:00 New York
11/29/15 14:55:00 New York

Body:
Here is your program using Howard Hinnant's timezone library (free, open-source, will run with VS-2013, does require some installation).

#include "tz.h"
#include <string>
#include <sstream>
#include <vector>
#include <iostream>

int main()
{
    using namespace std;
    using namespace date;
    vector<string> datetimes{ "2011-01-15 04:01:00",
                              "2014-06-07 23:17:00",
                              "2015-11-29 14:55:00" };

    zoned_seconds zt("America/New_York");
    for (auto const& i : datetimes)
    {
        stringstream ss1(i);
        local_seconds tm;
        ss1 >> parse("%F %T", tm);
        zt = tm;
        stringstream ss2;
        ss2 << format("%D %T %Z", zt);
        cout << ss2.str() << endl;
    }
}

Output:

01/15/11 04:01:00 EST
06/07/14 23:17:00 EDT
11/29/15 14:55:00 EST


问:
How to create different class objects in class constructor and overloading operators (C++)
I need yours help. I'm quite newbie in C++ (still learning) and I struggling with class constructor which include object from different class. The task is to create Rectangle class which will be described by objects (Point class) , each corner is a object with x,y coordinates. Additionally I need overload operators << and >> in the way that by ">>" user input coordinates of each point during Rectangle object creation by constructor.
When I using code as below I have error incomplete type is not allowed" on fields from p1 to p4.

List item

```<code>    #include <iostream>

using namespace std;

class Point;
class Rectangle
{
public:
    Rectangle(int p1x = 0, int p1y = 0, int p2x = 0, int p2y = 0, int p3x = 0, int p3y = 0, int p4x = 0, int p4y = 0) : p1(p1x, p1y), p2(p2x, p2y), p3(p3x, p3y), p4(p4x, p4y)
    {

    };

    friend ostream & operator << (ostream &os, const Rectangle &rect);

private:
    Point p1, p2, p3, p4;
    void change_cordinates(Rectangle &);
    int height, width;
};"
</code>```

From the other hand, when i use #include "Point.h" directive I have problem with overloading << and >> with error "function Rectangle is not a type name"

I don't know if it's clear, but I hope I described my problem peaty clear (if not correct me please or ask)

答:
As already mentioned in the comments: you'll have to ensure types are 'complete' when they are used.

In your example they are used by adding them as member variables.
You could work around this issue by holding pointers to them (instead of members) - but that is most likely a bad idea, as you then have to care about memory allocation/de-allocation.

Probably the best solution: include "Point.h" and fix your >> and << operators.

Body:
I need yours help. I'm quite newbie in C++ (still learning) and I struggling with class constructor which include object from different class. The task is to create Rectangle class which will be described by objects (Point class) , each corner is a object with x,y coordinates. Additionally I need overload operators << and >> in the way that by ">>" user input coordinates of each point during Rectangle object creation by constructor.
When I using code as below I have error incomplete type is not allowed" on fields from p1 to p4.

List item

    #include <iostream>

using namespace std;

class Point;
class Rectangle
{
public:
    Rectangle(int p1x = 0, int p1y = 0, int p2x = 0, int p2y = 0, int p3x = 0, int p3y = 0, int p4x = 0, int p4y = 0) : p1(p1x, p1y), p2(p2x, p2y), p3(p3x, p3y), p4(p4x, p4y)
    {

    };

    friend ostream & operator << (ostream &os, const Rectangle &rect);

private:
    Point p1, p2, p3, p4;
    void change_cordinates(Rectangle &);
    int height, width;
};"

From the other hand, when i use #include "Point.h" directive I have problem with overloading << and >> with error "function Rectangle is not a type name"

I don't know if it's clear, but I hope I described my problem peaty clear (if not correct me please or ask)


问:
make JSP Declaration stateless
Consider the following jsp:

```<code><%!
    private String firstName = "";
    private String lastName = "";

    private String formatName(){
        return lastName + ", " + firstName;
    }
%>
<%
    firstName = request.getParameter("FNAME");
    lastName = request.getParameter("LNAME");
    String formattedName = formatName();
    out.print(formattedName);
%>
</code>```

Is there a way to make the declaration section <%! (...) %> stateless? That is I want firstName and lastName to be unique to each page load. I am not concerned with performance or best practice, refactor is not an option right now. I'm looking for something like <%@ page persist="false" %>. Any suggestions?

答:
If you're trying to accomplish what the example appears to want to accomplish, you don't need the instance variables at all. You could write this as </p>

```<code><%!
    private String formatName(String firstName, String lastName){
        return lastName + ", " + firstName;
    }
%>
<%
    String formattedName = formatName(request.getParameter("FNAME"),
                                      request.getParameter("LNAME"));
    out.print(formattedName);
%>
</code>```

Title: make JSP Declaration stateless

Body:
Consider the following jsp:

<%!
    private String firstName = "";
    private String lastName = "";

    private String formatName(){
        return lastName + ", " + firstName;
    }
%>
<%
    firstName = request.getParameter("FNAME");
    lastName = request.getParameter("LNAME");
    String formattedName = formatName();
    out.print(formattedName);
%>

Is there a way to make the declaration section <%! (...) %> stateless? That is I want firstName and lastName to be unique to each page load. I am not concerned with performance or best practice, refactor is not an option right now. I'm looking for something like <%@ page persist="false" %>. Any suggestions?

Body:
If you're trying to accomplish what the example appears to want to accomplish, you don't need the instance variables at all. You could write this as

<%!
    private String formatName(String firstName, String lastName){
        return lastName + ", " + firstName;
    }
%>
<%
    String formattedName = formatName(request.getParameter("FNAME"),
                                      request.getParameter("LNAME"));
    out.print(formattedName);
%>


问:
Outlook Ribbon XML - Get Active MailItem when other email item is open
What's the best way to retrieve the current active mailitem for all situations. So new mail, current mail, inline reply and normal reply.
My current code works ok until user has an email open in different screen. This is considered to be the active item.

```<code>MailItem mailItem = null;

      Inspector inspector = Globals.ThisAddIn.Application.ActiveInspector();
      if(inspector != null)
      {

        object item = inspector.CurrentItem;
        if(item is MailItem)
        {
          mailItem = item as MailItem;
        }
        Marshal.ReleaseComObject(inspector);
        inspector = null;
      }
      else
      {
        Explorer explorer = Globals.ThisAddIn.Application.ActiveExplorer();
        try
        {
          mailItem = explorer.GetType().InvokeMember("ActiveInlineResponse", BindingFlags.GetProperty
                                                                             | BindingFlags.Instance |
                                                                             BindingFlags.Public, null, explorer, null)
            as MailItem;
        }
        catch(Exception) { }

        if(mailItem == null)
        {
          if(explorer.Selection.Count > 0)
          {
            mailItem = Globals.ThisAddIn.Application.ActiveExplorer().Selection[1];
          }
        }
        Marshal.ReleaseComObject(explorer);
        explorer = null;
      }
      return mailItem;
</code>```

Solution : Use the IRibbonControl

```<code>internal static MailItem GetMailItem(IRibbonControl control)
    {
      // Check to see if an item is selected in explorer or we are in inspector.
      if(control.Context is Inspector)
      {
        Inspector inspector = (Inspector)control.Context;

        if(inspector.CurrentItem is MailItem)
        {
          return inspector.CurrentItem as MailItem;
        }
      }

      if(control.Context is Explorer)
      {
        Explorer explorer = (Explorer)control.Context;

        Selection selectedItems = explorer.Selection;
        if(selectedItems.Count != 1)
        {
          return null;
        }

        if(selectedItems[1] is MailItem)
        {
          return selectedItems[1] as MailItem;
        }
      }

      return null;
    }
</code>```

答:
Use Application.ActiveWindow property. You can then check if it is an Explorer or an Inspector and act accordingly.

If this is called from a ribbon button context, you really need to use RibbonControl.Context (RibbonControl is passed as a parameter to your event handler).

Body:
What's the best way to retrieve the current active mailitem for all situations. So new mail, current mail, inline reply and normal reply.
My current code works ok until user has an email open in different screen. This is considered to be the active item.

MailItem mailItem = null;

      Inspector inspector = Globals.ThisAddIn.Application.ActiveInspector();
      if(inspector != null)
      {

        object item = inspector.CurrentItem;
        if(item is MailItem)
        {
          mailItem = item as MailItem;
        }
        Marshal.ReleaseComObject(inspector);
        inspector = null;
      }
      else
      {
        Explorer explorer = Globals.ThisAddIn.Application.ActiveExplorer();
        try
        {
          mailItem = explorer.GetType().InvokeMember("ActiveInlineResponse", BindingFlags.GetProperty
                                                                             | BindingFlags.Instance |
                                                                             BindingFlags.Public, null, explorer, null)
            as MailItem;
        }
        catch(Exception) { }

        if(mailItem == null)
        {
          if(explorer.Selection.Count > 0)
          {
            mailItem = Globals.ThisAddIn.Application.ActiveExplorer().Selection[1];
          }
        }
        Marshal.ReleaseComObject(explorer);
        explorer = null;
      }
      return mailItem;

Solution : Use the IRibbonControl

internal static MailItem GetMailItem(IRibbonControl control)
    {
      // Check to see if an item is selected in explorer or we are in inspector.
      if(control.Context is Inspector)
      {
        Inspector inspector = (Inspector)control.Context;

        if(inspector.CurrentItem is MailItem)
        {
          return inspector.CurrentItem as MailItem;
        }
      }

      if(control.Context is Explorer)
      {
        Explorer explorer = (Explorer)control.Context;

        Selection selectedItems = explorer.Selection;
        if(selectedItems.Count != 1)
        {
          return null;
        }

        if(selectedItems[1] is MailItem)
        {
          return selectedItems[1] as MailItem;
        }
      }

      return null;
    }


问:
How to read properties of a executable file?
I want to read the file properties like File Description , Product name , Copyright of a exe file. Is there any Windows API for it?

答: Those values are stored in the file's version info resource.  You can use GetFileVersionInfo() and VerQueryValue() to read them.


问:
Using Javascript to set maxlength of a form text field, not working
So, I have this in my javascript file:

```<code>function yeahbaby() {
document.getElementByName("surname").maxLength = "40";
}
</code>```

which is loaded in this line of code in my htm file

```<code><form action="blah blah blah"
method="post" name="medicalform" onsubmit="return unrelated validation function();"
onload="yeahbaby();">
</code>```

With the final result being that this input field

```<code>Surname: <input type="text" name="surname">
</code>```

is limited to a maximum of 40 characters.

However, it doesn't actually put the limit on the input field, as I can type many more than 40 characters (or whatever I try changing it to).

I know I can change it in the htm file directly but I need to actually change it using javascript. I've literally been trying to fix this for the past two hours. Have I missed something?

Edit: I've tried getElementsbyName (adding the S) and it's still not working.

Edit 2: document.getElementsByName("surname")[0].setAttribute('maxLength', '40'); doesn't work either

Edit 3: https://pastebin.com/7SNmmcSN a link to both my HTML and javascript files.

答:
Try setAttribute:</p>

```<code>document.getElementsByName("surname")[0].setAttribute('maxLength', '40');
</code>```

Body:
So, I have this in my javascript file:

function yeahbaby() {
document.getElementByName("surname").maxLength = "40";
}

which is loaded in this line of code in my htm file

<form action="blah blah blah"
method="post" name="medicalform" onsubmit="return unrelated validation function();"
onload="yeahbaby();">

With the final result being that this input field

Surname: <input type="text" name="surname">

is limited to a maximum of 40 characters.

However, it doesn't actually put the limit on the input field, as I can type many more than 40 characters (or whatever I try changing it to).

I know I can change it in the htm file directly but I need to actually change it using javascript. I've literally been trying to fix this for the past two hours. Have I missed something?

Edit: I've tried getElementsbyName (adding the S) and it's still not working.

Edit 2: document.getElementsByName("surname")[0].setAttribute('maxLength', '40'); doesn't work either

Edit 3: https://pastebin.com/7SNmmcSN a link to both my HTML and javascript files.

Body:
Try setAttribute:

document.getElementsByName("surname")[0].setAttribute('maxLength', '40');


问:
Why is QCameraImageCapture saving an image to the hard drive?
Part of an application I have written has the ability to capture pictures from the webcam. I am using a QCamera with a QCameraViewfinder to display the current view, and then when a shutter button is clicked, it snaps a picture with a QCameraImageCapture set to capture to buffer, then handles it from there. I have just discovered that it is also saving a copy of the image in the local Pictures folder. Why is this happening, and how can I stop it?</p>

答:
This is just my point of observation:

Based on the documentation, after you call capture, irrespective of destination location ( I mean CaptureToFile or CaptureToBuffer) the image is saved to a file.

note this statemet in below link: If an empty file is passed, the camera backend choses the default location and naming scheme for photos on the system.

http://doc.qt.io/qt-5/qcameraimagecapture.html#capture

The additional advantage with "CaptureToBuffer", your image is saved in some specified buffer format.

My wild guess, if at all they are not supporting ( as i am unable to find any offical information on it) only capture to buffer,
the reason could be,

the user is allowed to set the bufferformat using setBufferFormat. And the device may not support the buffer format (isCaptureDestinationSupported() is there to check it.). May be because of this they are saving to local pictures folder always.

If this saving is unavoidable by capture, and if your business strictly needs not to maintain those saved files, when your buffer is doing good, probably you can delete them in below slot.

```<code>QObject::connect(YOURCAMERACAPTUREOBJECT, SIGNAL(imageSaved), this,SLOT(saved(int id, const QString &fileName)));

void saved(int id, const QString &fileName)
{

//Delete the file by checking you have content in buffer.
//to check the buffer probably you can use "imageAvailable" signal

}
</code>```

Body:
This is just my point of observation:

Based on the documentation, after you call capture, irrespective of destination location ( I mean CaptureToFile or CaptureToBuffer) the image is saved to a file.

note this statemet in below link: If an empty file is passed, the camera backend choses the default location and naming scheme for photos on the system.

http://doc.qt.io/qt-5/qcameraimagecapture.html#capture

The additional advantage with "CaptureToBuffer", your image is saved in some specified buffer format.

My wild guess, if at all they are not supporting ( as i am unable to find any offical information on it) only capture to buffer,
the reason could be,

the user is allowed to set the bufferformat using setBufferFormat. And the device may not support the buffer format (isCaptureDestinationSupported() is there to check it.). May be because of this they are saving to local pictures folder always.

If this saving is unavoidable by capture, and if your business strictly needs not to maintain those saved files, when your buffer is doing good, probably you can delete them in below slot.

QObject::connect(YOURCAMERACAPTUREOBJECT, SIGNAL(imageSaved), this,SLOT(saved(int id, const QString &fileName)));

void saved(int id, const QString &fileName)
{

//Delete the file by checking you have content in buffer.
//to check the buffer probably you can use "imageAvailable" signal

}


问:
Displaying JSON object on blade template
I'm trying to display a JSON object that is returned to my blade template that should look the output below

```<code>2007 | Kanye | UltralightBeam
2008 | JayZ  | 99 Problems
</code>```

JSON looks like this

```<code>{
    "2007":{
        "name" : "Kanye",
        "song" : "UltralightBeam"
    },
    "2008":{
        "name" : "JayZ",
        "song" : "99 Problems"
    }
}
</code>```

So far I have something like this that shows the name and song

```<code>@foreach($data['data_obj'] as $obj)
    {{$obj['name']}} | {{$obj['song']}}
@endforeach
</code>```

But I'm just not sure how I can get it to show the year as well?

Any guidance would be appreciated. Thank you!

答:
You want to use key => value syntax:

```<code>@foreach ($data['data_obj'] as $year => $obj)
    {{ $year }} | {{ $obj['name'] }} | {{ $obj['song'] }}
@endforeach
</code>```

Body:
I'm trying to display a JSON object that is returned to my blade template that should look the output below

2007 | Kanye | UltralightBeam
2008 | JayZ  | 99 Problems

JSON looks like this

{
    "2007":{
        "name" : "Kanye",
        "song" : "UltralightBeam"
    },
    "2008":{
        "name" : "JayZ",
        "song" : "99 Problems"
    }
}

So far I have something like this that shows the name and song

@foreach($data['data_obj'] as $obj)
    {{$obj['name']}} | {{$obj['song']}}
@endforeach

But I'm just not sure how I can get it to show the year as well?

Any guidance would be appreciated. Thank you!

Body:
You want to use key => value syntax:

@foreach ($data['data_obj'] as $year => $obj)
    {{ $year }} | {{ $obj['name'] }} | {{ $obj['song'] }}
@endforeach


问:
How to ingest logs from app managed by systemd
I have a service that logs structured lines of json to stdout. Using Upstart, I could add console.log to the config file and Upstart would manage saving stdout to /var/log/upstart/<service-name>.log. Another service, filebeat, would watch this log file, parsing the lines as json and then forwarding them to elasticsearch to be indexed. These logs were managed by logrotate and backed up nightly to s3.

As far as I can tell, there's no console log equivalent in systemd. The issue is then what's the best way to ship my logs out to elasticsearch?

Here are the options I've come up with:

Build log file management into the application

This is what I'm doing right now, but it feels very ugly. Maybe I'm being too dogmatic, but this isn't "12-factor" compliant (I don't want the application to worry about how its stdout is ingested), and I've already dealt with annoying debugging issues with respect to file permissions.

journalbeat

There's another unofficial "beat" called journalbeat that can ingest logs from the systemd journal. The major issue here is that I don't think it supports processing json log lines like filebeat does. I could rip that stuff out of filebeat and send a pr to journalbeat.

Shell redirection, or similar

The idea here is to start the process with a shell or some other stdout-managing program and use that for controlling how the logs are saved. I think this is pretty much a non-starter since I use [Service]Type=notify and sdnotify for startup notification (and that's not going away).

Use logstash

Logstash can ingest from journald and has all of the capabilities to parse out json and forward to es. Configuration will be more complex and I'll have to run logstash, which is heavier than filebeat, but whatever. Leaning towards this right now.

Systemd sorcery

I don't know enough about systemd to know what's possible here. I see that StandardOutput can be set to a file descriptor provided by a socket unit file, but I'm not sure how all of that fits together or if it's even possible/pragmatic.

Sorry this question was so long. Any thoughts are helpful!

答:
Continuing to log to STDOUT is a good idea. It is one of the principles of the Twelve Factor App is also recommend by systemd as well as being well supported by container solutions.

Building log management into the app is a bad idea. The app should do one thing and do it well. Log management gets into thorny issues of log rotation or how to handle remote log shipping when the connection is temporarily down.

Journalbeat seems like a good idea. Have you tested that it doesn't work with JSON logs? The internal log structure of the systemd journal is very JSON-like.

If Journalbeat doesn't work, using a syslog daemon like rsyslog to handle the task. The systemd journal is often forwarded to to syslog by default anyway. rsyslog has a module for forwarding logs to Elasticsearch.


问:
WebDAV library that supports Kerberos?
I want to programmatically read the files of a Kerberos-protected WebDAV server.

I tried adding Kerberos support to Sardine (Java), but it does not seem to work well.

Is there a WebDAV library that supports Kerberos? (any language, preferably open source)

答:
The solution I found to work is using the Sardine method classes that extend HttpRequestBase with Apache HttpClient. You will need to use both the httpclient and httpclient-win

```<code>try {
    CloseableHttpClient client = WinHttpClients.createDefault();

    HttpMove move = new HttpMove(fullSource, fullDestination, false);

    CloseableHttpResponse response = client.execute(move);
    if (response.getStatusLine().getStatusCode() == 201){
        System.out.println("Yay");
    }

} catch (Exception e) {
    e.printStackTrace();
}

throw new Exception("Unable to move node");
</code>```

Here are the dependencies used (gradle form)

compile group: 'com.github.lookfirst', name: 'sardine', version:
'5.+'

compile group: 'org.apache.httpcomponents', name: 'httpclient',
version: '4.5.+'

compile group: 'org.apache.httpcomponents', name: 'httpclient-win',
version: '4.5.+'

Title: WebDAV library that supports Kerberos?

Body:
The solution I found to work is using the Sardine method classes that extend HttpRequestBase with Apache HttpClient. You will need to use both the httpclient and httpclient-win

try {
    CloseableHttpClient client = WinHttpClients.createDefault();

    HttpMove move = new HttpMove(fullSource, fullDestination, false);

    CloseableHttpResponse response = client.execute(move);
    if (response.getStatusLine().getStatusCode() == 201){
        System.out.println("Yay");
    }

} catch (Exception e) {
    e.printStackTrace();
}

throw new Exception("Unable to move node");

Here are the dependencies used (gradle form)

compile group: 'com.github.lookfirst', name: 'sardine', version:
'5.+'

compile group: 'org.apache.httpcomponents', name: 'httpclient',
version: '4.5.+'

compile group: 'org.apache.httpcomponents', name: 'httpclient-win',
version: '4.5.+'