问:
sed -i option is not working on solaris
I am using sed to replace a line with NULL in a file. The command i used is

```<code>sed -i "s/.*shayam.*//g" FILE
</code>```

This is working fine in linux. shayam is replaced with blank in the FILE. But when i used this in solaris it is showing some error.

sed: illegal option -- i

How to use -i functionality of sed in solaris. Kindly help.

答:
I just answered a similar question sed -i + what the same option in SOLARIS, but for those who find this thread instead (I saw it in the related thread section):

The main problem I see with most answers given is that it doesn't work if you want to modify multiple files. The answer I gave in the other thread:

It isn't exactly the same as sed -i, but i had a similar issue. You
  can do this using perl:

```<code>perl -pi -e 's/find/replace/g' file
</code>```

doing the copy/move only works for single files. if you want to
  replace some text across every file in a directory and
  sub-directories, you need something which does it in place. you can do
  this with perl and find:

```<code>find . -exec perl -pi -e 's/find/replace/g' '{}' \;
</code>```

Title: sed -i option is not working on solaris

Body:
I am using sed to replace a line with NULL in a file. The command i used is

sed -i "s/.*shayam.*//g" FILE

This is working fine in linux. shayam is replaced with blank in the FILE. But when i used this in solaris it is showing some error.

sed: illegal option -- i

How to use -i functionality of sed in solaris. Kindly help.

Body:
I just answered a similar question sed -i + what the same option in SOLARIS, but for those who find this thread instead (I saw it in the related thread section):

The main problem I see with most answers given is that it doesn't work if you want to modify multiple files. The answer I gave in the other thread:

It isn't exactly the same as sed -i, but i had a similar issue. You
  can do this using perl:

perl -pi -e 's/find/replace/g' file

doing the copy/move only works for single files. if you want to
  replace some text across every file in a directory and
  sub-directories, you need something which does it in place. you can do
  this with perl and find:

find . -exec perl -pi -e 's/find/replace/g' '{}' \;


来源: stackexchange

问:
activerecord model with 2 parent levels
A user can have many questions. Many users can participate on a question and provide multiple answers to the same question. Relation between users and questions seems to be working fine. Problem is with answers.

model/user.rb

```<code>  has_and_belongs_to_many :questions
  has_many :answers
</code>```

model/question.rb

```<code>  has_and_belongs_to_many :users
  has_many :answers
</code>```

model/answer.rb

```<code>  has_one :question
  has_one :user, :through => :question
</code>```

Here is what I'm trying in the console:

```<code>irb(main):022:0> u1.questions.first.answers.create(answer: "foo1", order:1)
   (0.2ms)  BEGIN
  Answer Exists (0.5ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "foo1"], ["LIMIT", 1]]
  SQL (0.4ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:04 UTC], ["updated_at", 2017-03-31 19:31:04 UTC], ["answer", "foo1"], ["order", 1], ["question_id", 1]]
   (13.5ms)  COMMIT
=> #<Answer id: 6, created_at: "2017-03-31 19:31:04", updated_at: "2017-03-31 19:31:04", answer: "foo1", order: 1, user_id: nil, question_id: 1>
irb(main):023:0> u1.questions.first.answers.create(answer: "bar1", order:2)
   (0.4ms)  BEGIN
  Answer Exists (0.9ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "bar1"], ["LIMIT", 1]]
  SQL (0.5ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:04 UTC], ["updated_at", 2017-03-31 19:31:04 UTC], ["answer", "bar1"], ["order", 2], ["question_id", 1]]
   (19.9ms)  COMMIT
=> #<Answer id: 7, created_at: "2017-03-31 19:31:04", updated_at: "2017-03-31 19:31:04", answer: "bar1", order: 2, user_id: nil, question_id: 1>
irb(main):024:0> u2.questions.first.answers.create(answer: "foo2", order:1)
   (0.7ms)  BEGIN
  Answer Exists (0.6ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "foo2"], ["LIMIT", 1]]
  SQL (0.9ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:04 UTC], ["updated_at", 2017-03-31 19:31:04 UTC], ["answer", "foo2"], ["order", 1], ["question_id", 1]]
   (16.7ms)  COMMIT
=> #<Answer id: 8, created_at: "2017-03-31 19:31:04", updated_at: "2017-03-31 19:31:04", answer: "foo2", order: 1, user_id: nil, question_id: 1>
irb(main):025:0> u2.questions.first.answers.create(answer: "bar2", order:2)
   (0.5ms)  BEGIN
  Answer Exists (0.6ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "bar2"], ["LIMIT", 1]]
  SQL (0.5ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:05 UTC], ["updated_at", 2017-03-31 19:31:05 UTC], ["answer", "bar2"], ["order", 2], ["question_id", 1]]
   (14.9ms)  COMMIT
=> #<Answer id: 9, created_at: "2017-03-31 19:31:05", updated_at: "2017-03-31 19:31:05", answer: "bar2", order: 2, user_id: nil, question_id: 1>
</code>```

It's obvious something is wrong given the fact user_id is null, unless I specify. I expect user_id populated given the fact I'm creating it from a user object through a question.

```<code>irb(main):027:0* u1.questions.first.answers.count
   (0.7ms)  SELECT COUNT(*) FROM "answers" WHERE "answers"."question_id" = $1  [["question_id", 1]]
=> 4
</code>```

As I can see here, it just filters by question_id. I expect to retrieve the answers from question_id AND user_id

Can this problem be fixed? Should I just do it in another way?

Thanks

UPDATE

As a summary, this is what I would like to achieve:

```<code>User.first.answers.where(question_id: 1)
</code>```

Where the query looks like:

```<code>SELECT "answers".* FROM "answers" WHERE "answers"."user_id" = $1 AND "answers"."question_id" = $2  [["user_id", 1], ["question_id", 1]]
</code>```

I would like to be able to do:

```<code>User.first.questions.first.answers
</code>```

And get the answers for user_id and question_id

Thanks

答: I think you should use belongs_to for :user and :question (instead of has_one) and set user manually to your answers from current_user in controller.

ContentLicense: CC BY-SA 3.0

Title: activerecord model with 2 parent levels

Body:
A user can have many questions. Many users can participate on a question and provide multiple answers to the same question. Relation between users and questions seems to be working fine. Problem is with answers.

model/user.rb

  has_and_belongs_to_many :questions
  has_many :answers

model/question.rb

  has_and_belongs_to_many :users
  has_many :answers

model/answer.rb

  has_one :question
  has_one :user, :through => :question

Here is what I'm trying in the console:

irb(main):022:0> u1.questions.first.answers.create(answer: "foo1", order:1)
   (0.2ms)  BEGIN
  Answer Exists (0.5ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "foo1"], ["LIMIT", 1]]
  SQL (0.4ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:04 UTC], ["updated_at", 2017-03-31 19:31:04 UTC], ["answer", "foo1"], ["order", 1], ["question_id", 1]]
   (13.5ms)  COMMIT
=> #<Answer id: 6, created_at: "2017-03-31 19:31:04", updated_at: "2017-03-31 19:31:04", answer: "foo1", order: 1, user_id: nil, question_id: 1>
irb(main):023:0> u1.questions.first.answers.create(answer: "bar1", order:2)
   (0.4ms)  BEGIN
  Answer Exists (0.9ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "bar1"], ["LIMIT", 1]]
  SQL (0.5ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:04 UTC], ["updated_at", 2017-03-31 19:31:04 UTC], ["answer", "bar1"], ["order", 2], ["question_id", 1]]
   (19.9ms)  COMMIT
=> #<Answer id: 7, created_at: "2017-03-31 19:31:04", updated_at: "2017-03-31 19:31:04", answer: "bar1", order: 2, user_id: nil, question_id: 1>
irb(main):024:0> u2.questions.first.answers.create(answer: "foo2", order:1)
   (0.7ms)  BEGIN
  Answer Exists (0.6ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "foo2"], ["LIMIT", 1]]
  SQL (0.9ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:04 UTC], ["updated_at", 2017-03-31 19:31:04 UTC], ["answer", "foo2"], ["order", 1], ["question_id", 1]]
   (16.7ms)  COMMIT
=> #<Answer id: 8, created_at: "2017-03-31 19:31:04", updated_at: "2017-03-31 19:31:04", answer: "foo2", order: 1, user_id: nil, question_id: 1>
irb(main):025:0> u2.questions.first.answers.create(answer: "bar2", order:2)
   (0.5ms)  BEGIN
  Answer Exists (0.6ms)  SELECT  1 AS one FROM "answers" WHERE "answers"."answer" = $1 LIMIT $2  [["answer", "bar2"], ["LIMIT", 1]]
  SQL (0.5ms)  INSERT INTO "answers" ("created_at", "updated_at", "answer", "order", "question_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", 2017-03-31 19:31:05 UTC], ["updated_at", 2017-03-31 19:31:05 UTC], ["answer", "bar2"], ["order", 2], ["question_id", 1]]
   (14.9ms)  COMMIT
=> #<Answer id: 9, created_at: "2017-03-31 19:31:05", updated_at: "2017-03-31 19:31:05", answer: "bar2", order: 2, user_id: nil, question_id: 1>

It's obvious something is wrong given the fact user_id is null, unless I specify. I expect user_id populated given the fact I'm creating it from a user object through a question.

irb(main):027:0* u1.questions.first.answers.count
   (0.7ms)  SELECT COUNT(*) FROM "answers" WHERE "answers"."question_id" = $1  [["question_id", 1]]
=> 4

As I can see here, it just filters by question_id. I expect to retrieve the answers from question_id AND user_id

Can this problem be fixed? Should I just do it in another way?

Thanks

UPDATE

As a summary, this is what I would like to achieve:

User.first.answers.where(question_id: 1)

Where the query looks like:

SELECT "answers".* FROM "answers" WHERE "answers"."user_id" = $1 AND "answers"."question_id" = $2  [["user_id", 1], ["question_id", 1]]

I would like to be able to do:

User.first.questions.first.answers

And get the answers for user_id and question_id

Thanks


问:
Generating a random hex color code with PHP
I'm working on a project where I need to generate an undefined number of random,  hexadecimal color codes…how would I go about building such a function in PHP?</p>

Body:
This is how i do it.

<?php echo 'rgba('.rand(0,255).', '.rand(0,255).', '.rand(0,255).', 0.73)'; ?>


问:
Pivot and replace XDocument's nested element array of chars with a single string
Having XML like this:

```<code><ReplyMessage>
  <tran>
    <ser_num>305</ser_num>
    <time>1490987995</time>
    <source_type>0</source_type>
    <source_number>0</source_number>
    <tran_type>126</tran_type>
    <tran_code>50</tran_code>
    <t_diag>
      <bfr>S</bfr>
      <bfr>o</bfr>
      <bfr>c</bfr>
      <bfr>k</bfr>
      <bfr>e</bfr>
      <bfr>t</bfr>
      <bfr></bfr>
      <bfr>r</bfr>
      <bfr>e</bfr>
      <bfr>c</bfr>
      <bfr>v</bfr>
      <bfr></bfr>
      <bfr>o</bfr>
      <bfr>n</bfr>
      <bfr></bfr>
      <bfr>s</bfr>
      <bfr>o</bfr>
      <bfr>c</bfr>
      <bfr>k</bfr>
      <bfr>e</bfr>
      <bfr>t</bfr>
      <bfr>-</bfr>
      <bfr>7</bfr>
      <bfr>4</bfr>
      <bfr>:</bfr>
      <bfr></bfr>
      <bfr>f</bfr>
      <bfr>a</bfr>
      <bfr>i</bfr>
      <bfr>l</bfr>
      <bfr>e</bfr>
      <bfr>d</bfr>
      <bfr></bfr>
      <bfr>-</bfr>
      <bfr></bfr>
      <bfr>3</bfr>
      <bfr>0</bfr>
      <bfr>7</bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
    </t_diag>
  </tran>
</ReplyMessage>
</code>```

I wished to replace the array of nested <bfr> elements under <t_diag> with a simple string element:

```<code><ReplyMessage>
  <tran>
    <ser_num>305</ser_num>
    <time>1490987995</time>
    <source_type>0</source_type>
    <source_number>0</source_number>
    <tran_type>126</tran_type>
    <tran_code>50</tran_code>
    <t_diag>
      <bfr>Socket recv on socket-74: failed - 307</bfr>
    </t_diag>
  </tran>
</ReplyMessage>
</code>```

So, piecing together several posts from StackOverflow and MSDN, I arrived at this method, which does the job:

```<code>private XElement XmlPivotCharArrayToStr(XDocument xmlDoc, string parentName, string arrayName)
{
    XElement parent = xmlDoc.Descendants().Where(n => n.Name == parentName).FirstOrDefault();
    string st = string.Join("", parent.Elements(arrayName).Select(x => string.IsNullOrEmpty(x.Value) ? " " : x.Value)).TrimEnd();
    parent.RemoveAll();
    XElement newElement = new XElement(arrayName, st);
    parent.Add(newElement);
    return newElement;
}
</code>```

Called like this:

```<code>    //// Some initial cleanup to convert character array into string
    XmlPivotCharArrayToStr(xmlDoc, parentName: "t_diag", arrayName: "bfr");
</code>```

Now, this works, in my specific context, but I have the feeling that several improvements could be made:

Is there a way I could have specified an explicit path to parentName instead of using .Descendants() method?

Is there a better way to swap out the array and replace it with the string? - parent.RemoveAll() may be overkill.

Is there a way to detect the end of the array to avoid using TrimEnd()

Thanks in advance for any tips - I'm hoping others find (the improved version) this useful.

答:
You can select target node with xpath. For that, use extension methods (add using System.Xml.XPath). Then just:

```<code>XElement parent = xmlDoc.XPathSelectElement(path);
</code>```

Where path in your case is "/ReplyMessage/tran/t_diag".

I think RemoveAll is fine, but if you have doubts - you can remove t_diag itself, like this:

```<code>XElement newElement = new XElement(arrayName, st);
var grandParent = parent.Parent;
parent.Remove();
grandParent.Add(new XElement(parent.Name, newElement));
</code>```

TrimEnd is fine. To detect if all elements at the end are empty you need to watch all of them anyway - so you cannot do much better.

Body:
Having XML like this:

<ReplyMessage>
  <tran>
    <ser_num>305</ser_num>
    <time>1490987995</time>
    <source_type>0</source_type>
    <source_number>0</source_number>
    <tran_type>126</tran_type>
    <tran_code>50</tran_code>
    <t_diag>
      <bfr>S</bfr>
      <bfr>o</bfr>
      <bfr>c</bfr>
      <bfr>k</bfr>
      <bfr>e</bfr>
      <bfr>t</bfr>
      <bfr></bfr>
      <bfr>r</bfr>
      <bfr>e</bfr>
      <bfr>c</bfr>
      <bfr>v</bfr>
      <bfr></bfr>
      <bfr>o</bfr>
      <bfr>n</bfr>
      <bfr></bfr>
      <bfr>s</bfr>
      <bfr>o</bfr>
      <bfr>c</bfr>
      <bfr>k</bfr>
      <bfr>e</bfr>
      <bfr>t</bfr>
      <bfr>-</bfr>
      <bfr>7</bfr>
      <bfr>4</bfr>
      <bfr>:</bfr>
      <bfr></bfr>
      <bfr>f</bfr>
      <bfr>a</bfr>
      <bfr>i</bfr>
      <bfr>l</bfr>
      <bfr>e</bfr>
      <bfr>d</bfr>
      <bfr></bfr>
      <bfr>-</bfr>
      <bfr></bfr>
      <bfr>3</bfr>
      <bfr>0</bfr>
      <bfr>7</bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
      <bfr></bfr>
    </t_diag>
  </tran>
</ReplyMessage>

I wished to replace the array of nested <bfr> elements under <t_diag> with a simple string element:

<ReplyMessage>
  <tran>
    <ser_num>305</ser_num>
    <time>1490987995</time>
    <source_type>0</source_type>
    <source_number>0</source_number>
    <tran_type>126</tran_type>
    <tran_code>50</tran_code>
    <t_diag>
      <bfr>Socket recv on socket-74: failed - 307</bfr>
    </t_diag>
  </tran>
</ReplyMessage>

So, piecing together several posts from StackOverflow and MSDN, I arrived at this method, which does the job:

private XElement XmlPivotCharArrayToStr(XDocument xmlDoc, string parentName, string arrayName)
{
    XElement parent = xmlDoc.Descendants().Where(n => n.Name == parentName).FirstOrDefault();
    string st = string.Join("", parent.Elements(arrayName).Select(x => string.IsNullOrEmpty(x.Value) ? " " : x.Value)).TrimEnd();
    parent.RemoveAll();
    XElement newElement = new XElement(arrayName, st);
    parent.Add(newElement);
    return newElement;
}

Called like this:

    //// Some initial cleanup to convert character array into string
    XmlPivotCharArrayToStr(xmlDoc, parentName: "t_diag", arrayName: "bfr");

Now, this works, in my specific context, but I have the feeling that several improvements could be made:

Is there a way I could have specified an explicit path to parentName instead of using .Descendants() method?

Is there a better way to swap out the array and replace it with the string? - parent.RemoveAll() may be overkill.

Is there a way to detect the end of the array to avoid using TrimEnd()

Thanks in advance for any tips - I'm hoping others find (the improved version) this useful.

Body:
You can select target node with xpath. For that, use extension methods (add using System.Xml.XPath). Then just:

XElement parent = xmlDoc.XPathSelectElement(path);

Where path in your case is "/ReplyMessage/tran/t_diag".

I think RemoveAll is fine, but if you have doubts - you can remove t_diag itself, like this:

XElement newElement = new XElement(arrayName, st);
var grandParent = parent.Parent;
parent.Remove();
grandParent.Add(new XElement(parent.Name, newElement));

TrimEnd is fine. To detect if all elements at the end are empty you need to watch all of them anyway - so you cannot do much better.


问:
Adding Totals to a Table According to Parameters in PHP
I have this code to show a table in PHP:

```<code><?php

$harvest = Array (
       Array (
                     Array (
                                    'PRODUCT' => 'ROSE' ,
                                    'VARIETY' => 'ADELE',
                                  'GOLD' => 160,
                                    'NORMAL' => 0 ,
                                    'TOTAL' => 160
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ALESSO' ,
                                    'GOLD' => 1320 ,
                                    'NORMAL' => 550,
                                    'TOTAL' => 1870
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ANASTACIA' ,
                                    'GOLD' => 440 ,
                                    'NORMAL' => 150 ,
                                    'TOTAL' => 590
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                  'VARIETY' => 'ANASTACIA1' ,
                                  'GOLD' => 420 ,
                                    'NORMAL' => 120 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                    'VARIETY' => 'ANASTACIA1',
                                    'GOLD' => 440 ,
                                    'NORMAL' => 100 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2',
                                    'GOLD' => 640,
                                    'NORMAL' => 0,
                                    'TOTAL' => 640
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2' ,
                                    'GOLD' => 440,
                                    'NORMAL' => 440,
                                    'TOTAL' => 880
                                   )
                    )

     );

$arrayThead = array();
      for ($i=0; $i < count($harvest) ; $i++) {
        array_push($arrayThead, array_keys($harvest[$i][0]));
      }

      $totalByProduct = array();
      foreach ($harvest as $items) {
          foreach ($items as $item) {
              if(!key_exists($item['PRODUCT'], $totalByProduct)){
                  $totalByProduct[$item['PRODUCT']] = $item;
                  unset($totalByProduct[$item['PRODUCT']]['VARIETY']);
                  continue;
              }
              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $totalByProduct[$item['PRODUCT']][$th] += $item[$th];
                  }
                }
              }
          }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayComplete = array();
      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
            array_push($arrayComplete, $arrayThead[$i][$j]);
          }
        }
      }

      $arrayFinal = array();
      for ($j=0; $j < count($arrayComplete) ; $j++) {
        array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
      }

    //  exit;

      $body = '';
      $body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
      $body .= '<thead style="background-color:#f3f4f5;">';
      $body .= '<tr>';

      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
            $body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
          }else{
            $body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
          }
        }
      }
      $body .= '</tr>';
      $body .= '</thead>';
      $body .= '<tbody>';

      for ($k=0; $k < count($harvest); $k++) {
        for ($a=0; $a < count($harvest[$k]) ; $a++) {
          $body .= '<tr>';
          for ($i=0; $i < count($arrayThead) ; $i++) {
            for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
              if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
                $body .= '<td style="border: 1px solid black;font-size:12px;">'.$harvest[$k][$a][$arrayThead[$i][$j]].'</td>';
              }else{
                $body .= '<td style="border: 1px solid black; text-align:right;font-size:12px;">'.number_format($harvest[$k][$a][$arrayThead[$i][$j]]).'</td>';
              }
            }
          }
          $body .= '</tr>';
          foreach ($totalByProduct as $key => $value) {
            if($value["PRODUCT"] == $harvest[$k][$a]['PRODUCT']){
              $body .= '<tr>';
              $body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;">TOTAL '.$value["PRODUCT"].'</th>';
              $body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;"></th>';

              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $body .= '<th style="border: 1px solid black;text-align:right;font-size:12px;">'.number_format($value[$th]).'</th>';
                  }
                }
              }
              $body .= '</tr>';
            }
          }
        }
      }

      $body .= '</tbody>';
      $body .= '<tfoot>';
      $body .= '<tr>';
      $body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
      $body .= '<th style="border: 1px solid black;"></th>';

      for ($i=0; $i < count($arrayFinal) ; $i++) {
        $body .= '<th style="border: 1px solid black;text-align:right;">'.number_format($arrayFinal[$i]).'</th>';
      }

      $body .= '</tr>';
      $body .= '</tfoot>';
      $body .= '</table>';

      echo $body;
</code>```

I need to place a row with the total of GOLD, NORMAL and TOTAL inside the table, but according the product.

If you want to see how the code works you can copy the code and past in this page: PHPTESTER

I need to show the table something like this:

```<code>-------------------------------------------------------------------
  PRODUCT     |   VARIETY   |  GOLD    |  NORMAL |  TOTAL         |
-------------------------------------------------------------------
   ROSE       |   ADELE     |  160     |  0      |     160        |
-------------------------------------------------------------------
   ROSE       |   ALESSO    |  1320    |  550    |    1870        |
-------------------------------------------------------------------
   ROSE       |  ANASTACIA  |  440     |    150  |  590           |
-------------------------------------------------------------------
   TOTAL ROSE |             |  1920    |  700    |  2620          |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  420     |  120    |  540           |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  440     |    100  |  540           |
-------------------------------------------------------------------
 TOTAL ROSE1  |             |  860     |  220    |  1080          |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  640     |    0    |  640           |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  440     |    440  |  880           |
-------------------------------------------------------------------
  TOTAL ROSE2 |             |  1080    |  440    |  1520          |
-------------------------------------------------------------------
 TOTAL GENERAL|             |  3860    |  1360   |  5220          |
-------------------------------------------------------------------
</code>```

I hope that someone can help me thanks!

答:
Here is the code. You can make modification to the code</p>

```<code>foreach($harvest[0] as $key=>$value){
    $new_array[$value['PRODUCT']][] = $value;
}

echo '<table cellspacing="5" cellpadding="5" border="1px solid #ccc">';
echo "<tr>
<th>PRODUCT</th>
<th>VARIETY</th>
<th>GOLD</th>
<th>NORMAL</th>
<th>TOTAL</th>
</tr>";

$total_gold = $total_normal = $total_total = 0;
foreach($new_array as $key=>$value){
    $gold[$key] = $normal[$key] = $total[$key] = 0;
    if(is_array($value)){
        foreach($value as $k=>$v){
            $gold[$key] += $v['GOLD'];
            $normal[$key] += $v['NORMAL'];
            $total[$key] += $v['TOTAL'];
            echo "<tr>";
            echo "<td>".$key."</td>";
            echo "<td>".$v['VARIETY']."</td>";
            echo "<td>".$v['GOLD']."</td>";
            echo "<td>".$v['NORMAL']."</td>";
            echo "<td>".$v['TOTAL']."</td>";
            echo "<tr>";
        }
        echo "<tr><td><b>Total ".$key."</b></td><td></td><td>".$gold[$key]."</td><td>".$normal[$key]."</td><td>".$total[$key]."</td></tr>";
        $total_gold +=$gold[$key];
        $total_normal +=$normal[$key];
        $total_total += $total[$key];
    }

}
echo "<tr><td><b>TOTAL GENERAL</b></td><td></td><td>".$total_gold."</td><td>".$total_normal."</td><td>".$total_total."</td></tr>";

echo "</table>";
</code>```

Body:
I have this code to show a table in PHP:

<?php

$harvest = Array (
       Array (
                     Array (
                                    'PRODUCT' => 'ROSE' ,
                                    'VARIETY' => 'ADELE',
                                  'GOLD' => 160,
                                    'NORMAL' => 0 ,
                                    'TOTAL' => 160
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ALESSO' ,
                                    'GOLD' => 1320 ,
                                    'NORMAL' => 550,
                                    'TOTAL' => 1870
                                  ) ,
                     Array (
                                    'PRODUCT' => 'ROSE',
                                    'VARIETY' => 'ANASTACIA' ,
                                    'GOLD' => 440 ,
                                    'NORMAL' => 150 ,
                                    'TOTAL' => 590
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                  'VARIETY' => 'ANASTACIA1' ,
                                  'GOLD' => 420 ,
                                    'NORMAL' => 120 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE1',
                                    'VARIETY' => 'ANASTACIA1',
                                    'GOLD' => 440 ,
                                    'NORMAL' => 100 ,
                                    'TOTAL' => 540
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2',
                                    'GOLD' => 640,
                                    'NORMAL' => 0,
                                    'TOTAL' => 640
                                  ),
                     Array (
                                    'PRODUCT' => 'ROSE2',
                                    'VARIETY' => 'ANASTACIA2' ,
                                    'GOLD' => 440,
                                    'NORMAL' => 440,
                                    'TOTAL' => 880
                                   )
                    )

     );

$arrayThead = array();
      for ($i=0; $i < count($harvest) ; $i++) {
        array_push($arrayThead, array_keys($harvest[$i][0]));
      }

      $totalByProduct = array();
      foreach ($harvest as $items) {
          foreach ($items as $item) {
              if(!key_exists($item['PRODUCT'], $totalByProduct)){
                  $totalByProduct[$item['PRODUCT']] = $item;
                  unset($totalByProduct[$item['PRODUCT']]['VARIETY']);
                  continue;
              }
              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $totalByProduct[$item['PRODUCT']][$th] += $item[$th];
                  }
                }
              }
          }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayfoot= array();

      foreach ($harvest as $key => $value) {
        foreach ($value as $harv) {
          foreach ($arrayThead as $key => $values) {
            foreach ($values as $th) {
              if($th != 'PRODUCT' && $th != 'VARIETY'){
                  $arrayfoot[$th] += $harv[$th];
              }
            }
          }
        }
      }

      $arrayComplete = array();
      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
            array_push($arrayComplete, $arrayThead[$i][$j]);
          }
        }
      }

      $arrayFinal = array();
      for ($j=0; $j < count($arrayComplete) ; $j++) {
        array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
      }

    //  exit;

      $body = '';
      $body .= '
';
      $body .= '
';
      $body .= '
';

      for ($i=0; $i < count($arrayThead) ; $i++) {
        for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
          if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
            $body .= ''.$arrayThead[$i][$j].'	';
          }else{
            $body .= ''.$arrayThead[$i][$j].'	';
          }
        }
      }
      $body .= '
';
      $body .= '
';
      $body .= '
';

      for ($k=0; $k < count($harvest); $k++) {
        for ($a=0; $a < count($harvest[$k]) ; $a++) {
          $body .= '
';
          for ($i=0; $i < count($arrayThead) ; $i++) {
            for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
              if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
                $body .= ''.$harvest[$k][$a][$arrayThead[$i][$j]].'	';
              }else{
                $body .= ''.number_format($harvest[$k][$a][$arrayThead[$i][$j]]).'	';
              }
            }
          }
          $body .= '
';
          foreach ($totalByProduct as $key => $value) {
            if($value["PRODUCT"] == $harvest[$k][$a]['PRODUCT']){
              $body .= '
';
              $body .= 'TOTAL '.$value["PRODUCT"].'	';
              $body .= '	';

              foreach ($arrayThead as $key => $values) {
                foreach ($values as $th) {
                  if($th != 'PRODUCT' && $th != 'VARIETY'){

                    $body .= ''.number_format($value[$th]).'	';
                  }
                }
              }
              $body .= '
';
            }
          }
        }
      }

      $body .= '
';
      $body .= '
';
      $body .= '
';
      $body .= 'TOTAL GENERAL	';
      $body .= '	';

      for ($i=0; $i < count($arrayFinal) ; $i++) {
        $body .= ''.number_format($arrayFinal[$i]).'	';
      }

      $body .= '
';
      $body .= '
';
      $body .= '
';

      echo $body;

I need to place a row with the total of GOLD, NORMAL and TOTAL inside the table, but according the product.

If you want to see how the code works you can copy the code and past in this page: PHPTESTER

I need to show the table something like this:

-------------------------------------------------------------------
  PRODUCT     |   VARIETY   |  GOLD    |  NORMAL |  TOTAL         |
-------------------------------------------------------------------
   ROSE       |   ADELE     |  160     |  0      |     160        |
-------------------------------------------------------------------
   ROSE       |   ALESSO    |  1320    |  550    |    1870        |
-------------------------------------------------------------------
   ROSE       |  ANASTACIA  |  440     |    150  |  590           |
-------------------------------------------------------------------
   TOTAL ROSE |             |  1920    |  700    |  2620          |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  420     |  120    |  540           |
-------------------------------------------------------------------
   ROSE1      |  ANASTACIA1 |  440     |    100  |  540           |
-------------------------------------------------------------------
 TOTAL ROSE1  |             |  860     |  220    |  1080          |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  640     |    0    |  640           |
-------------------------------------------------------------------
   ROSE2      |  ANASTACIA2 |  440     |    440  |  880           |
-------------------------------------------------------------------
  TOTAL ROSE2 |             |  1080    |  440    |  1520          |
-------------------------------------------------------------------
 TOTAL GENERAL|             |  3860    |  1360   |  5220          |
-------------------------------------------------------------------

I hope that someone can help me thanks!

Body:
Here is the code. You can make modification to the code

foreach($harvest[0] as $key=>$value){
    $new_array[$value['PRODUCT']][] = $value;
}

echo '<table cellspacing="5" cellpadding="5" border="1px solid #ccc">';
echo "<tr>
<th>PRODUCT</th>
<th>VARIETY</th>
<th>GOLD</th>
<th>NORMAL</th>
<th>TOTAL</th>
</tr>";

$total_gold = $total_normal = $total_total = 0;
foreach($new_array as $key=>$value){
    $gold[$key] = $normal[$key] = $total[$key] = 0;
    if(is_array($value)){
        foreach($value as $k=>$v){
            $gold[$key] += $v['GOLD'];
            $normal[$key] += $v['NORMAL'];
            $total[$key] += $v['TOTAL'];
            echo "<tr>";
            echo "<td>".$key."</td>";
            echo "<td>".$v['VARIETY']."</td>";
            echo "<td>".$v['GOLD']."</td>";
            echo "<td>".$v['NORMAL']."</td>";
            echo "<td>".$v['TOTAL']."</td>";
            echo "<tr>";
        }
        echo "<tr><td><b>Total ".$key."</b></td><td></td><td>".$gold[$key]."</td><td>".$normal[$key]."</td><td>".$total[$key]."</td></tr>";
        $total_gold +=$gold[$key];
        $total_normal +=$normal[$key];
        $total_total += $total[$key];
    }

}
echo "<tr><td><b>TOTAL GENERAL</b></td><td></td><td>".$total_gold."</td><td>".$total_normal."</td><td>".$total_total."</td></tr>";

echo "</table>";


问:
postgresql error: 'schema "" does not exist' on temporary table
I'm finding that this rather simple postgresql 9.6 function

```<code>CREATE OR REPLACE FUNCTION public.trying_to_index_me()
RETURNS VOID  AS
$BODY$
    BEGIN
    CREATE TABLE public.table_to_index (
        id INTEGER NOT NULL,
        this_id UUID NOT NULL,
        that_id smallint NOT NULL,
        CONSTRAINT idx_table_to_index_unique
            UNIQUE (id,this_id,that_id)
    );
    CREATE INDEX idx_table_to_index_thisthat ON public.table_to_index(this_id,that_id);
    DROP TABLE public.table_to_index;
END;
$BODY$ LANGUAGE plpgsql;

--SELECT public.trying_to_index_me();
</code>```

is resulting in a schema "" does not exist error. The exact error is:

```<code>ERROR:  schema "" does not exist
SQL state: 3F000
Context: SQL statement "CREATE INDEX idx_table_to_index_thisthat
ON public.table_to_index(this_id,that_id)"
PL/pgSQL function trying_to_index_me() line 10 at SQL statement
</code>```

and occurs reliably on the second and subsequent executions. Cut/Pasting the above SQL chunk reproduces the error...for me. Quite interested if that's not the case for you. I have the following clues:

The schema detected in the error message varies. Mostly it is reported as "", but others like "0MA{Start of Text} " or some snippet of sql statement/comment from a previous statement in the transaction. Sounds memory pointer related.

It will error consistently once its in.

I find that if I CREATE OR REPLACE the function, I'll get one execution and then the errored state will occur again.

I find that if I open a new pgadminIII window (without dropping or recreating), I'll get the same one execution and then the errored state will occur again...regardless of if it was errored in a different window. Sounds connection related.

I find that commenting out the creation of either idx_temp_data_to_index_thisthat or idx_temp_data_to_index_unique resolves the issue.

Occurs in both "PostgreSQL 9.5.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16), 64-bit" and in the 9.6 implementation.

If the above function is executed from another function, the CREATE OR REPLACE FUNCTION 1-time resolve above does not work on the parent function, only when replacing the child function. And doesn't matter if that occurs in a separate pgadmin window. PSounds like neither the client or the transaction.

Truly appreciate your thoughts.

答:
This appears to have been caused by the citus data extension. The error is caused by corrupted memory that occurs once the default stack of 2M is exceeded. It doesn't show up in the logs, and never makes it to the "stack depth limit exceeded" exception that would have been thrown.

That's all speculative finger pointing.

Uninstalling citus extension resolved the issue for me.

Body:
I'm finding that this rather simple postgresql 9.6 function

CREATE OR REPLACE FUNCTION public.trying_to_index_me()
RETURNS VOID  AS
$BODY$
    BEGIN
    CREATE TABLE public.table_to_index (
        id INTEGER NOT NULL,
        this_id UUID NOT NULL,
        that_id smallint NOT NULL,
        CONSTRAINT idx_table_to_index_unique
            UNIQUE (id,this_id,that_id)
    );
    CREATE INDEX idx_table_to_index_thisthat ON public.table_to_index(this_id,that_id);
    DROP TABLE public.table_to_index;
END;
$BODY$ LANGUAGE plpgsql;

--SELECT public.trying_to_index_me();

is resulting in a schema "" does not exist error. The exact error is:

ERROR:  schema "" does not exist
SQL state: 3F000
Context: SQL statement "CREATE INDEX idx_table_to_index_thisthat
ON public.table_to_index(this_id,that_id)"
PL/pgSQL function trying_to_index_me() line 10 at SQL statement

and occurs reliably on the second and subsequent executions. Cut/Pasting the above SQL chunk reproduces the error...for me. Quite interested if that's not the case for you. I have the following clues:

The schema detected in the error message varies. Mostly it is reported as "", but others like "0MA{Start of Text} " or some snippet of sql statement/comment from a previous statement in the transaction. Sounds memory pointer related.

It will error consistently once its in.

I find that if I CREATE OR REPLACE the function, I'll get one execution and then the errored state will occur again.

I find that if I open a new pgadminIII window (without dropping or recreating), I'll get the same one execution and then the errored state will occur again...regardless of if it was errored in a different window. Sounds connection related.

I find that commenting out the creation of either idx_temp_data_to_index_thisthat or idx_temp_data_to_index_unique resolves the issue.

Occurs in both "PostgreSQL 9.5.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16), 64-bit" and in the 9.6 implementation.

If the above function is executed from another function, the CREATE OR REPLACE FUNCTION 1-time resolve above does not work on the parent function, only when replacing the child function. And doesn't matter if that occurs in a separate pgadmin window. PSounds like neither the client or the transaction.

Truly appreciate your thoughts.


问:
Is it normal to have a list of objects in an object?
I'm new to OO design, and I wondering whether it is typical to have designs where objects contain lists of other objects. An example is below:

```<code>// Person object containing a list of phone numbers
public class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Phone> Contacts { get; set; }

    public void AddPhoneNumber(Phone phone)
    {
        Contacts.Add(phoneNumber);
    }
}

// Phone object
public class Phone
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Number { get; set; }
}

// Example code to establish an object:
Person p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Smith";
p1.AddPhoneNumber(new Phone() { Number = "555957000" });
p1.AddPhoneNumber(new Phone() { Number = "555579561" });
</code>```

Is there a better way to structure this that simplifies the design and allows easier access to the data? Thanks!

答: Yes, it is absolutely fine to have an object contains  list of object. In OOPs this is called Composition, which represent strong relationship between participating class.

Body:
I'm new to OO design, and I wondering whether it is typical to have designs where objects contain lists of other objects. An example is below:

// Person object containing a list of phone numbers
public class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Phone> Contacts { get; set; }

    public void AddPhoneNumber(Phone phone)
    {
        Contacts.Add(phoneNumber);
    }
}

// Phone object
public class Phone
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Number { get; set; }
}

// Example code to establish an object:
Person p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Smith";
p1.AddPhoneNumber(new Phone() { Number = "555957000" });
p1.AddPhoneNumber(new Phone() { Number = "555579561" });

Is there a better way to structure this that simplifies the design and allows easier access to the data? Thanks!


问:
How to load images with glide dynamically (Android)?
In my android app I pull data from http requests.

In my layout I want to show images dynamically with Glide library.

I get the image urls but I can not find a way to show them in my layout.

In my layout file I have:

```<code>   <LinearLayout
    android:id="@+id/social_media_layout"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="60dp"
    android:gravity="center_vertical">

  </LinearLayout>
</code>```

Somehow I want to add imageviews(dynamically) in my LinearLayout.

For example: If I get 2 image urls from the request I need two imageviews in my linearlayout.

Note: I want to load images with Glide library.

Any idea would be helful.

Thanks.

答:
You could make a new XML file for item_social_media.xml

For example

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="60dp" >

    <ImageView
        android:id="@+id/social_media_icon"
        />

        <!-- More customization as needed -->

</RelativeLayout>
</code>```

And you can inflate that and add into the LinearLayout.

```<code>final Context context = MainActivity.this; // TODO: Get a context

// Inflate and update the view
View socialMediaItem = LayoutInflater.from(context).inflate(R.layout.item_social_media);
ImageView icon = (ImageView) socialMediaItem.findViewById(R.id.social_media_icon);
// TODO: Glide ... into(icon);

// Add to the LinearLayout
linearLayout.addView(socialMediaItem);
</code>```

Body:
In my android app I pull data from http requests.

In my layout I want to show images dynamically with Glide library.

I get the image urls but I can not find a way to show them in my layout.

In my layout file I have:

   <LinearLayout
    android:id="@+id/social_media_layout"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="60dp"
    android:gravity="center_vertical">

  </LinearLayout>

Somehow I want to add imageviews(dynamically) in my LinearLayout.

For example: If I get 2 image urls from the request I need two imageviews in my linearlayout.

Note: I want to load images with Glide library.

Any idea would be helful.

Thanks.

Body:
You could make a new XML file for item_social_media.xml

For example

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="60dp" >

    <ImageView
        android:id="@+id/social_media_icon"
        />

        <!-- More customization as needed -->

</RelativeLayout>

And you can inflate that and add into the LinearLayout.

final Context context = MainActivity.this; // TODO: Get a context

// Inflate and update the view
View socialMediaItem = LayoutInflater.from(context).inflate(R.layout.item_social_media);
ImageView icon = (ImageView) socialMediaItem.findViewById(R.id.social_media_icon);
// TODO: Glide ... into(icon);

// Add to the LinearLayout
linearLayout.addView(socialMediaItem);


问:
interactive brokers api lagging behind tws when using 100 symbols
I haven't been having this problem until I started putting more symbols up on my screeen.  I don't think it's a processing thing, my cpu has been fine and I'm not doing anything super super fancy anyways (just storing data to objects and writing to txt files every so often).

From day 1 with the api, I noticed that I had to put a sleep(1) in the while loop that constantly checks for messages, like so:

```<code>PosixTestClient client;
client.connect( host, port, clientId);
while( client.isConnected()) {
        sleep(1);
        client.processMessages();
    }
</code>```

If I don't have that sleep(1) there, it just crashes.  So I guess my first question is:  is that normal?  Or is something wrong with that?

And my next question is... any tips as to why there might be a lag in the api data as compared to the tws data?  I know there's a lag because as the data comes into the api, I'm storing it to strings and then every minute writing the data to text files.  Then I go back through my text files and compare it to the charts in tws... and I notice there's about a 2min lag!  I also notice it seems to get better (the lag goes away) after the first half hour of the trading day, when things are pretty active.

So... any advice?

答:
Do you have subscribed Booster pack?
TWS API has 100 quotes limit, as well as API. You can buy additional 100 quotes for 30$.

Quote Booster
  Increase your allowance of simultaneous quotes windows by purchasing monthly Quote Booster packs at USD 30.00 per pack.

Each booster pack provides 100 simultaneous Level I quotes. Booster Pack quotes are additional to your monthly quote allotment from all sources, including commissions.
  Booster pack quotes are available for use in the desktop systems and in the API.
  Once subscribed, quotes are available immediately and will display the next time you log into the system.
  Data from a cancelled booster pack subscription remains available through the end of the current billing cycle.
  Limit of 10 Quote Booster packs per account.

Body:
I haven't been having this problem until I started putting more symbols up on my screeen.  I don't think it's a processing thing, my cpu has been fine and I'm not doing anything super super fancy anyways (just storing data to objects and writing to txt files every so often).

From day 1 with the api, I noticed that I had to put a sleep(1) in the while loop that constantly checks for messages, like so:

PosixTestClient client;
client.connect( host, port, clientId);
while( client.isConnected()) {
        sleep(1);
        client.processMessages();
    }

If I don't have that sleep(1) there, it just crashes.  So I guess my first question is:  is that normal?  Or is something wrong with that?

And my next question is... any tips as to why there might be a lag in the api data as compared to the tws data?  I know there's a lag because as the data comes into the api, I'm storing it to strings and then every minute writing the data to text files.  Then I go back through my text files and compare it to the charts in tws... and I notice there's about a 2min lag!  I also notice it seems to get better (the lag goes away) after the first half hour of the trading day, when things are pretty active.

So... any advice?


问:
Haskell: Parsec: Pipeline of transformers of the whole file
I'm trying to use parsec to read a C/C++/java source file and do a series of transformations on the entire file. The first phase removes strings and the second phase removes comments. (That's because you might get a /* inside a string.)

So each phase transforms a string onto Either String Error, and I want to bind (in the sense of Either) them together to make a pipeline of transformations of the whole file. This seems like a fairly general requirement.

```<code>import Text.ParserCombinators.Parsec

commentless, stringless :: Parser String

stringless = fmap concat ( (many (noneOf "\"")) `sepBy` quotedString )
quotedString = (char '"') >> (many quotedChar) >> (char '"')
quotedChar = try (string "\\\"" >> return '"' ) <|> (noneOf "\"")

commentless = fmap concat $ notComment `sepBy` comment
notComment = manyTill anyChar (lookAhead (comment <|> eof))
comment = (string "//" >> manyTill anyChar newline >> spaces >> return ())
      <|> (string "/*" >> manyTill anyChar (string "*/") >>  spaces >> return ())

main =
    do c <- getContents
       case parse commentless "(stdin)" c of -- THIS WORKS
--     case parse stringless "(stdin)" c of -- THIS WORKS TOO
--     case parse (stringless `THISISWHATIWANT` commentless) "(stdin)" c of
            Left e -> do putStrLn "Error parsing input:"
                         print e
            Right r -> print r
</code>```

So how can I do this? I tried parserBind but it didn't work.

(In case anybody cares why, I'm trying to do a kind of light parse where I just extract what I want but avoid parsing the entire grammar or even knowing whether it's C++ or Java. All I need to extract is the starting and ending line numbers of all classes and functions. So I envisage a bunch of preprocessing phases that just scrub out comments, #defines/ifdefs, template preambles and contents of parentheses (because of the semicolons in for clauses), then I'll parse for snippets preceding {s (or following }s because of typedefs) and stuff those snippets through yet another phase to get the type and name of whatever it is, then recurse to just the second level to get java member functions.)

答:
You need to bind Either Error, not Parser. You need to move the bind outside the parse, and use multiple parses:

```<code>parse stringless "(stdin)" input >>= parse commentless "(stdin)"
</code>```

There is probably a better approach than what you are using, but this will do what you want.

Body:
I'm trying to use parsec to read a C/C++/java source file and do a series of transformations on the entire file. The first phase removes strings and the second phase removes comments. (That's because you might get a /* inside a string.)

So each phase transforms a string onto Either String Error, and I want to bind (in the sense of Either) them together to make a pipeline of transformations of the whole file. This seems like a fairly general requirement.

import Text.ParserCombinators.Parsec

commentless, stringless :: Parser String

stringless = fmap concat ( (many (noneOf "\"")) `sepBy` quotedString )
quotedString = (char '"') >> (many quotedChar) >> (char '"')
quotedChar = try (string "\\\"" >> return '"' ) <|> (noneOf "\"")

commentless = fmap concat $ notComment `sepBy` comment
notComment = manyTill anyChar (lookAhead (comment <|> eof))
comment = (string "//" >> manyTill anyChar newline >> spaces >> return ())
      <|> (string "/*" >> manyTill anyChar (string "*/") >>  spaces >> return ())

main =
    do c <- getContents
       case parse commentless "(stdin)" c of -- THIS WORKS
--     case parse stringless "(stdin)" c of -- THIS WORKS TOO
--     case parse (stringless `THISISWHATIWANT` commentless) "(stdin)" c of
            Left e -> do putStrLn "Error parsing input:"
                         print e
            Right r -> print r

So how can I do this? I tried parserBind but it didn't work.

(In case anybody cares why, I'm trying to do a kind of light parse where I just extract what I want but avoid parsing the entire grammar or even knowing whether it's C++ or Java. All I need to extract is the starting and ending line numbers of all classes and functions. So I envisage a bunch of preprocessing phases that just scrub out comments, #defines/ifdefs, template preambles and contents of parentheses (because of the semicolons in for clauses), then I'll parse for snippets preceding {s (or following }s because of typedefs) and stuff those snippets through yet another phase to get the type and name of whatever it is, then recurse to just the second level to get java member functions.)

Body:
You need to bind Either Error, not Parser. You need to move the bind outside the parse, and use multiple parses:

parse stringless "(stdin)" input >>= parse commentless "(stdin)"

There is probably a better approach than what you are using, but this will do what you want.


问:
Is there any link to download ab Apache benchmark
Can anyone please provide me the direct to download the Ab.exe Apache benchmark utility?</p>

答:
Just download Apache (www.apache.org).  It comes with it  (in ApacheX.X/bin)

...Guessing (from one of your other questions) that you're using a Mac... there appear to be instructions here:

http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-os-x/

(if not, I can probably help with a Windows installation, but in general, Google is your friend!)

A list of mirrors for the windows binaries can be found here.

There are some basic instructions here:

http://www.ricocheting.com/how-to-install-on-windows/apache

...basically, install it, and the ab.exe will be in the 'bin' subdirectory of the installation

ContentLicense: CC BY-SA 4.0


问:
File not reading in selenium - maven framewaork
I tried to create a quick framework. in that I created below-mentioned classes:

Config file(All browsers path)

configDataProvider java class(reads the above file)

BrowserFactory class(has firefox browser object)

configDataProviderTest class(access data from dconfigDataProvider class)

now its not reading the paths mentioned in config.properties file.

I have provided all correct path and attached screenshots:

答:
Two things which I noticed:

Don't give path in your properties path within ""

all the path seperators should be replaced with double backward slash \\ or single forward slash /


问:
Send email with Qt
Hello I am trying to create a method to send emails through my qt app and it works very much ok but when I try to send arabic on non english message it send as "????" question marks
here is my code

```<code>    void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body)
{
    message.append("User-Agent: Mozilla Thunderbird 1.0.6 (Macintosh/20050716)\n");
    message.append("X-Accept-Language: ar_EG, en_US\n");
    message.append("MIME-Version: 1.0\r\n");
    message = "To: " + to + "\r\n";
    message.append("From: " + from + "\r\n");
    message.append("Subject: " + subject + "\r\n");
    //message.append("Content-Type: text/html; charset=UTF8;\r\n");
    message.append("Message From Smart Clinic\r\n");
    message.append(QString("Build Number: %1 \r\n").arg(BUILD));
    message.append(QString("Version     : %1 \r\n").arg(APPVERSION));
    message.append(body);
    message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    message.replace( QString::fromLatin1( "\r\n.\r\n" ),QString::fromLatin1( "\r\n..\r\n" ) );

    this->from = from;
    rcpt = to;
    state = Init;
    socket->connectToHostEncrypted(host, port); //"smtp.gmail.com" and 465 for gmail TLS
    if (!socket->waitForConnected(timeout)) {
        emit status( tr( "Failed to send message" ) );
     }

    t = new QTextStream( socket );
}
</code>```

how to make it able to send english and non english text
thank you

答:
Your message is converted in 8-bits array as   ASCII (like Latin1). You should use UTF8 encoding.
Your code looks like incomplete one - some of variable without declaration. So it's hard to say where exactly message converting to bytes</p>

Title: Send email with Qt

Body:
Hello I am trying to create a method to send emails through my qt app and it works very much ok but when I try to send arabic on non english message it send as "????" question marks
here is my code

    void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body)
{
    message.append("User-Agent: Mozilla Thunderbird 1.0.6 (Macintosh/20050716)\n");
    message.append("X-Accept-Language: ar_EG, en_US\n");
    message.append("MIME-Version: 1.0\r\n");
    message = "To: " + to + "\r\n";
    message.append("From: " + from + "\r\n");
    message.append("Subject: " + subject + "\r\n");
    //message.append("Content-Type: text/html; charset=UTF8;\r\n");
    message.append("Message From Smart Clinic\r\n");
    message.append(QString("Build Number: %1 \r\n").arg(BUILD));
    message.append(QString("Version     : %1 \r\n").arg(APPVERSION));
    message.append(body);
    message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    message.replace( QString::fromLatin1( "\r\n.\r\n" ),QString::fromLatin1( "\r\n..\r\n" ) );

    this->from = from;
    rcpt = to;
    state = Init;
    socket->connectToHostEncrypted(host, port); //"smtp.gmail.com" and 465 for gmail TLS
    if (!socket->waitForConnected(timeout)) {
        emit status( tr( "Failed to send message" ) );
     }

    t = new QTextStream( socket );
}

how to make it able to send english and non english text
thank you


问:
sails lifecycle - custom service and config.log
I defined a l.js under /api/services

```<code>exports.i = sails.log.info;
exports.v = sails.log.verbose;
exports.err = sails.log.error;
exports.w = sails.log.warn;
exports.d = sails.log.debug;
</code>```

It works fine but when I want to define custom logger in /config/log.js

```<code>let customLogger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console, winston.transports.File)({
            name: 'file.info',
            level: 'info',
            filename: logPath + '/server-info.log',
            json: true
        }),
        new (winston.transports.Console, winston.transports.File)({
            name: 'file.warning',
            level: 'warning',
            filename: logPath + '/server-warning.log',
            json: true
        }),
        new (winston.transports.File)({
            name: 'file.error',
            level: 'error',
            filename: logPath + '/server-error.log',
            json: true
        })
    ]
});

module.exports.log = {
    level: 'info',
    custom: customLogger,
};
</code>```

When I use sails.log.error("123"); l.err("456") in controller, only "123" showed in server-error.log file. "456" only print to console.

When I check sails doc about lifecycle, it seems /config/log.js loaded before /api/services. How should I modify my code?

Thanks

答:
Although config/log.js is loaded before api/services/l.js, (my feeling is) assignment of custom logger defined in log.js to sails.log.<level> happens after the service is loaded.

Hence the behavior.

Re-assigning on lifted event fixes this. Use this code in l.js:

```<code>exports.err = sails.log.error;

sails.on('lifted', function() {
  console.log('lifted event');
  // Re-assign here
  exports.err = sails.log.error;
});
</code>```

Do similarly for other methods of the service.

Body:
I defined a l.js under /api/services

exports.i = sails.log.info;
exports.v = sails.log.verbose;
exports.err = sails.log.error;
exports.w = sails.log.warn;
exports.d = sails.log.debug;

It works fine but when I want to define custom logger in /config/log.js

let customLogger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console, winston.transports.File)({
            name: 'file.info',
            level: 'info',
            filename: logPath + '/server-info.log',
            json: true
        }),
        new (winston.transports.Console, winston.transports.File)({
            name: 'file.warning',
            level: 'warning',
            filename: logPath + '/server-warning.log',
            json: true
        }),
        new (winston.transports.File)({
            name: 'file.error',
            level: 'error',
            filename: logPath + '/server-error.log',
            json: true
        })
    ]
});

module.exports.log = {
    level: 'info',
    custom: customLogger,
};

When I use sails.log.error("123"); l.err("456") in controller, only "123" showed in server-error.log file. "456" only print to console.

When I check sails doc about lifecycle, it seems /config/log.js loaded before /api/services. How should I modify my code?

Thanks

Body:
Although config/log.js is loaded before api/services/l.js, (my feeling is) assignment of custom logger defined in log.js to sails.log.<level> happens after the service is loaded.

Hence the behavior.

Re-assigning on lifted event fixes this. Use this code in l.js:

exports.err = sails.log.error;

sails.on('lifted', function() {
  console.log('lifted event');
  // Re-assign here
  exports.err = sails.log.error;
});

Do similarly for other methods of the service.


问:
FeathersJS: server to server authentication
I just notice that there is a possibility to authenticate server side or client side pretty easily:
https://docs.feathersjs.com/authentication/readme.html

But those instructions rely on a javascript server/client.
Generically, how can I authenticate a server side (Microservice) with a simple cURL request? which has no email and it is not an actual user (server to server), let's assume I have the secret key.

TL;DR How can I convert this to a simple cURL request for server authentication:

```<code>app.configure(authentication({
    token: {
        secret: 'my-secret'
    }
}));
</code>```

答:
It depends on the feathers-authentication module version. In v0.7.x:

```<code>curl 'http://localhost:3030/auth/local/' -H 'Content-Type: application/json' --data-binary '{ "email": "user@example.com", "password": "secret" }'
</code>```

In 1.x:

```<code>curl 'http://localhost:3030/authentication' -H 'Content-Type: application/json' --data-binary '{ "strategy": "local", "email": "user@example.com", "password": "secret" }'
</code>```

Both will return a token for the authenticated user.

Body:
I just notice that there is a possibility to authenticate server side or client side pretty easily:
https://docs.feathersjs.com/authentication/readme.html

But those instructions rely on a javascript server/client.
Generically, how can I authenticate a server side (Microservice) with a simple cURL request? which has no email and it is not an actual user (server to server), let's assume I have the secret key.

TL;DR How can I convert this to a simple cURL request for server authentication:

app.configure(authentication({
    token: {
        secret: 'my-secret'
    }
}));

Body:
It depends on the feathers-authentication module version. In v0.7.x:

curl 'http://localhost:3030/auth/local/' -H 'Content-Type: application/json' --data-binary '{ "email": "user@example.com", "password": "secret" }'

In 1.x:

curl 'http://localhost:3030/authentication' -H 'Content-Type: application/json' --data-binary '{ "strategy": "local", "email": "user@example.com", "password": "secret" }'

Both will return a token for the authenticated user.


问:
Session works in one page but not another
I am working in a php charting package. I start with a form.html that sends to an answer.php page. The answer.php creates the SESSION. Then a required test.php page picks up the session but the required graph.php page does not. I cannot transfer my data from the form to the graph. The required phplot.php is the graph engine and is not needed in the SESSION thread.

I have spent five days researching and testing with no luck. I have switched the coding around many times. I'm hoping that someone with great php experience will recognize something easily.

The coding for the three pages is below.

answer.php page:

```<code><?php
session_unset();
session_start();
require_once 'phplot/test.php';
?>
<?php
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;
echo "<div id='graph'>";
echo "<p class='martop10 f18 b'>Graph:</p>";
echo "<img src='phplot/graph.php'>";
echo "</div>";
?>
<?php
session_destroy();
?>
</code>```

graph.php page:

```<code><?php
$Sbs_now2 == 0;
session_start();# Is this redundant? I've tried it in and out.
?>
<?php
require_once 'phplot.php';#Graph engine
$delta = 0.1;$sigma = 15;$sqrt2pi = sqrt(2*M_PI);$u = 75;
$data = array();
for ($x = 0; $x <= 150; $x++)
  $data[] = array('', $x, $Sbs_now2 + $x);
unset($Sbs_now2);
?>
</code>```

test.php page:

```<code><?php
#I don't need the session_start() for this page
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];
echo '<b>Session BS Now: '.$Sbs_now2.'</b><br>';
?>
</code>```

Thank you,

Gary

答:
First thing In every page you will use "$_SESSION" you need to start session through "session_start()" if session start is not present in the code you can not get data from $ _SESSION variable, I recommend using $_POST variable Your php session is not full and does not cause problems

Use this: (Pass throught $_POST)

```<code><?php
// passing data to the post
$_POST['data'] = "Test using Post";
// Receiving the data from the post
$data = $_POST['data'];
// to test and see if it works
echo $_POST['data']; // or echo $data
</code>```

Hope i have helped

Cheers

Body:
I am working in a php charting package. I start with a form.html that sends to an answer.php page. The answer.php creates the SESSION. Then a required test.php page picks up the session but the required graph.php page does not. I cannot transfer my data from the form to the graph. The required phplot.php is the graph engine and is not needed in the SESSION thread.

I have spent five days researching and testing with no luck. I have switched the coding around many times. I'm hoping that someone with great php experience will recognize something easily.

The coding for the three pages is below.

answer.php page:

<?php
session_unset();
session_start();
require_once 'phplot/test.php';
?>
<?php
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;
echo "
";
echo "
Graph:
";
echo "";
echo "
";
?>
<?php
session_destroy();
?>

graph.php page:

<?php
$Sbs_now2 == 0;
session_start();# Is this redundant? I've tried it in and out.
?>
<?php
require_once 'phplot.php';#Graph engine
$delta = 0.1;$sigma = 15;$sqrt2pi = sqrt(2*M_PI);$u = 75;
$data = array();
for ($x = 0; $x <= 150; $x++)
  $data[] = array('', $x, $Sbs_now2 + $x);
unset($Sbs_now2);
?>

test.php page:

<?php
#I don't need the session_start() for this page
$_POST['bs_now2'];$bs_now2 = $_POST['bs_now2'];$_SESSION['bs_now2'] = $bs_now2;$Sbs_now2 = $_SESSION['bs_now2'];
echo 'Session BS Now: '.$Sbs_now2.'
';
?>

Thank you,

Gary

Body:
First thing In every page you will use "$_SESSION" you need to start session through "session_start()" if session start is not present in the code you can not get data from $ _SESSION variable, I recommend using $_POST variable Your php session is not full and does not cause problems

Use this: (Pass throught $_POST)

<?php
// passing data to the post
$_POST['data'] = "Test using Post";
// Receiving the data from the post
$data = $_POST['data'];
// to test and see if it works
echo $_POST['data']; // or echo $data

Hope i have helped

Cheers


答:
I did not think this was possible, but this worked for me.

```<code>  +----+----+-------------------------+
  | e  | c  | .. _my-reference-label: |
  |    |    |                         |
  |    |    | p                       |
  +====+====+=========================+
  | e1 | c1 | p1                      |
  +----+----+-------------------------+
  | e2 | c2 | p2                      |
  +----+----+-------------------------+
</code>```

and then the link to the target would be:

```<code>  :ref:`Link title <my-reference-label>`.
</code>```

The formatting makes the targeted cell larger than it should be, but you can fiddle with the other column widths to get percentage widths close enough.

Title: RST/Sphinx create inline target markup inside array

Body:
I have an array in sphinx / rst, and I would like to reference a line or cell from other part of my documentation.

How can I create an inline markup reference target in the array?

The array looks like this:

+-----------------+-------------------------+-------------------------------------------------------+
| e               | c                       | p                                                     |
+=================+=========================+=======================================================+
| e1              | c1                      | p1                                                    |
+-----------------+-------------------------+-------------------------------------------------------+
| e2              | c2                      | p2                                                    |
+-----------------+-------------------------+-------------------------------------------------------+

Body:
I did not think this was possible, but this worked for me.

  +----+----+-------------------------+
  | e  | c  | .. _my-reference-label: |
  |    |    |                         |
  |    |    | p                       |
  +====+====+=========================+
  | e1 | c1 | p1                      |
  +----+----+-------------------------+
  | e2 | c2 | p2                      |
  +----+----+-------------------------+

and then the link to the target would be:

  :ref:`Link title <my-reference-label>`.

The formatting makes the targeted cell larger than it should be, but you can fiddle with the other column widths to get percentage widths close enough.


问:
CorruptedFrameException data frame using reserved opcode 7
I am trying to establish a web socket communication behind my corporate proxy. I can see that the proxy connection between my proxy server and remote host established and get back handshake response. After that when I try to send a message I get the exception.

Here is my channel init

```<code>Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();

                if (sslCtx != null) {
                    p.addFirst("ssl", sslCtx.newHandler(ch.alloc(), host, port));
                }
                if(proxyHandler != null){
                    p.addFirst("proxyHandler", proxyHandler);

                }
                p.addLast(new LoggingHandler(LogLevel.DEBUG));
                p.addLast("clientCodec", new HttpClientCodec());

                p.addLast("decoder", new HttpRequestDecoder());
                p.addLast("aggregator", new HttpObjectAggregator(65536));
                p.addLast("encoder", new HttpResponseEncoder());
                p.addLast(handler);

            }
        });
</code>```

And exception is

```<code>io.netty.handler.codec.CorruptedFrameException: data frame using reserved opcode 7
  at io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.protocolViolation(WebSocket08FrameDecoder.java:412)
  at io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.decode(WebSocket08FrameDecoder.java:229)
  at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411)
  at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:373)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359)
  at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:351)
  at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:373)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359)
  at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
  at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:129)
  at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:651)
  at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:574)
  at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:488)
  at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:450)
  at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:873)
  at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
  at java.lang.Thread.run(Thread.java:745)
WebSocket Client
disconnected!
</code>```

答:
I have run into the same issue and found out that this issue appears as a result of the WebSocket upgrade operation as reported here: WebSocket upgrade wrecks HttpProxyHandler. Leaving a note in case anyone has the same problem.

The important part quoted:

Short story: WebSocketClientHandshaker reorganizes the Pipeline after
  receiving the upgrade from the server. If there is an HttpProxyHandler
  in the Pipeline, it has installed its own HttpClientCodec which gets
  wrecked by WebSocketClientHandshaker.

```<code>HttpClientCodec#0        <-- #finishHandshake hit this one.
ws-decoder               <-- We don't want this here.
ws-encoder               <-- We don't want this here.
Http11ProxyHandler#0
SslHandler#0
HttpClientCodec#1
                         <-- ws-xxcoder should appear here.
DownendChannelHandler#0  <-- My own stuff.
</code>```

It seems there is no fix yet so one may need to hack into the WebSocketClientHandshaker or the post references kind of a workaround.

Body:
I am trying to establish a web socket communication behind my corporate proxy. I can see that the proxy connection between my proxy server and remote host established and get back handshake response. After that when I try to send a message I get the exception.

Here is my channel init

Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();

                if (sslCtx != null) {
                    p.addFirst("ssl", sslCtx.newHandler(ch.alloc(), host, port));
                }
                if(proxyHandler != null){
                    p.addFirst("proxyHandler", proxyHandler);

                }
                p.addLast(new LoggingHandler(LogLevel.DEBUG));
                p.addLast("clientCodec", new HttpClientCodec());

                p.addLast("decoder", new HttpRequestDecoder());
                p.addLast("aggregator", new HttpObjectAggregator(65536));
                p.addLast("encoder", new HttpResponseEncoder());
                p.addLast(handler);

            }
        });

And exception is

io.netty.handler.codec.CorruptedFrameException: data frame using reserved opcode 7
  at io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.protocolViolation(WebSocket08FrameDecoder.java:412)
  at io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.decode(WebSocket08FrameDecoder.java:229)
  at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411)
  at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:373)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359)
  at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:351)
  at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:373)
  at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359)
  at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
  at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:129)
  at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:651)
  at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:574)
  at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:488)
  at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:450)
  at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:873)
  at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
  at java.lang.Thread.run(Thread.java:745)
WebSocket Client
disconnected!

Body:
I have run into the same issue and found out that this issue appears as a result of the WebSocket upgrade operation as reported here: WebSocket upgrade wrecks HttpProxyHandler. Leaving a note in case anyone has the same problem.

The important part quoted:

Short story: WebSocketClientHandshaker reorganizes the Pipeline after
  receiving the upgrade from the server. If there is an HttpProxyHandler
  in the Pipeline, it has installed its own HttpClientCodec which gets
  wrecked by WebSocketClientHandshaker.

HttpClientCodec#0        <-- #finishHandshake hit this one.
ws-decoder               <-- We don't want this here.
ws-encoder               <-- We don't want this here.
Http11ProxyHandler#0
SslHandler#0
HttpClientCodec#1
                         <-- ws-xxcoder should appear here.
DownendChannelHandler#0  <-- My own stuff.

It seems there is no fix yet so one may need to hack into the WebSocketClientHandshaker or the post references kind of a workaround.


问:
Subset around values that follow a pattern
Hopefully, this is a fairly straight forward question. I am using R to help subset some data that I am working with. Below is print() of some of the data that I am currently working with. I am trying to create a subset() of the data based around JobCode. As you can see the JobCode follows a pattern (00 - 0000) where the first 2 numbers are the same for a specific industry.

```<code>          ID   State         StateName JobCode
          1    AL            Alabama   51-9199
          2    AL            Alabama   27-3011
          4    AL            Alabama   49-9043
          5    AL            Alabama   49-2097
</code>```

My current attempt is to use this test <- subset(data, data$State == "AL" & data$JobCode == ("15-####"))(where # is a placeholder for the remaining 4 values) to subset for JobCode beginning with "15-". Is there any way to tell the subset to look for those remaining 4 values?

I'm sorry for the poor formatting as I am new to StackOverflow and I am also quite inexperienced with R. Thank you for your help.

答:
You can use the %like% operator of data.table library:

```<code>library(data.table)

setDT(df)

df[ State == "AL" & JobCode %like% "15-" ]
</code>```

Body:
Hopefully, this is a fairly straight forward question. I am using R to help subset some data that I am working with. Below is print() of some of the data that I am currently working with. I am trying to create a subset() of the data based around JobCode. As you can see the JobCode follows a pattern (00 - 0000) where the first 2 numbers are the same for a specific industry.

          ID   State         StateName JobCode
          1    AL            Alabama   51-9199
          2    AL            Alabama   27-3011
          4    AL            Alabama   49-9043
          5    AL            Alabama   49-2097

My current attempt is to use this test <- subset(data, data$State == "AL" & data$JobCode == ("15-####"))(where # is a placeholder for the remaining 4 values) to subset for JobCode beginning with "15-". Is there any way to tell the subset to look for those remaining 4 values?

I'm sorry for the poor formatting as I am new to StackOverflow and I am also quite inexperienced with R. Thank you for your help.

Body:
You can use the %like% operator of data.table library:

library(data.table)

setDT(df)

df[ State == "AL" & JobCode %like% "15-" ]