问:
How to export JSON from MongoDB using Robo 3T
I am using Robo 3T (formerly RoboMongo) which I connect to a MongoDB. What I need to do is this: There is a collection in that MongoDB. I want to export the data from that collection so that I can save it into a file.

I used the interface to open the data from the collection as text and did a Ctrl + A and pasted into a text file. However, I found that not all data is copied and also that there were many comments in the text data which naturally breaks the JSON.

I am wondering if Robo 3T has a "Export As JSON" facility so that I can do a clean export.

Any pointers are appreciated!

答:
I had this same issue, and running script in robomongo (Robo 3T 1.1.1) also doesn't allow to copy values and there was no export option either.
The best way I could achieve this is to use mongoexport, if mongodb is installed on your local, you can use mongoexport to connect to database on any server and extract data

To connect to Data on remote server, and csv output file, run the following mongoexport in your command line

```<code>mongoexport --host HOSTNAME --port PORT --username USERNAME --password "PASSWORD" --collection COLLECTION_NAME --db DATABASE_NAME --out OUTPUTFILE.csv --type=csv --fieldFile fields.txt
</code>```

fieldFile: helps to extract the desired columns, ex:
contents of fields.txt can be just:

userId

to only extract values of the column 'userId'

Data on remote server, json output file:

```<code>mongoexport --host HOST_NAME --port PORT --username USERNAME --password "PASSWORD" --collection COLECTION_NAME --db DATABASE_NAME --out OUTPUT.json
</code>```

this extracts all fields into the json file

data on localhost (mongodb should be running on localhost)

```<code>mongoexport --db DATABASE_NAME --collection COLLECTION --out OUTPUT.json
</code>```

Reference: https://docs.mongodb.com/manual/reference/program/mongoexport/#use

Body:
I had this same issue, and running script in robomongo (Robo 3T 1.1.1) also doesn't allow to copy values and there was no export option either.
The best way I could achieve this is to use mongoexport, if mongodb is installed on your local, you can use mongoexport to connect to database on any server and extract data

To connect to Data on remote server, and csv output file, run the following mongoexport in your command line

mongoexport --host HOSTNAME --port PORT --username USERNAME --password "PASSWORD" --collection COLLECTION_NAME --db DATABASE_NAME --out OUTPUTFILE.csv --type=csv --fieldFile fields.txt

fieldFile: helps to extract the desired columns, ex:
contents of fields.txt can be just:

userId

to only extract values of the column 'userId'

Data on remote server, json output file:

mongoexport --host HOST_NAME --port PORT --username USERNAME --password "PASSWORD" --collection COLECTION_NAME --db DATABASE_NAME --out OUTPUT.json

this extracts all fields into the json file

data on localhost (mongodb should be running on localhost)

mongoexport --db DATABASE_NAME --collection COLLECTION --out OUTPUT.json

Reference: https://docs.mongodb.com/manual/reference/program/mongoexport/#use


来源: stackexchange

问:
Changing java file
Can I change a java file, when I'm running it on JVM, using this file?

For example:
I run abc.java. In this program I've a textarea and I want to paste text from the text area into abc.java and save the changes. Is it possible?

答:
The JVM runs class files (.class) and not Java (.java) files. To "convert" a *.java file to a *.class file it needs to be compiled firs.

So change a *.java File will not infuent the JVM in any way, because it is compleatly not interessed in.

Only because of a totality answer
You can write a programm (.java) that when it is compiled an run (.class) change its own source file (.java) (for example changing a string by user input) compiles it (.class), and restart it selfe with its new compiled form. But this is defently not what you want! One would write this kind of software only to prove that this insane idea would work.

Anyway, what you need is a way to store data, in a file or a database. (Have a look at the java.io package for file handling, and for an tutorial).

ContentLicense: CC BY-SA 2.5

Title: Changing java file

ContentLicense: CC BY-SA 3.0


问:
States not getting stored in database using city-state gem in ruby on rails
so I am using a gem called city-state gem in my web application to populate a dropdown list with the 50 states of US, but I am unable to save the selected value in the database,maybe I am missing something here, I have the following code:

```<code><%= form_for(resource, as: resource_name, :class=>'well form-horizontal' ,:style=>"margin-top:30px",url: registration_path(resource_name)) do |f| %>
  <select name="form[state]">
    <% CS.states(:us).each do |key, value| %>
      <option value="<%= key %>"><%= value %></option>
    <% end %>
  </select>
<% end %>
</code>```

I tried using

```<code><%= f.select :state, value %>
</code>```

but that would give me an empty dropdown list, any help appreciated.Thanks in advance.

```<code>Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"w1dXvna7zYZ96f9pNtCdm3ruIHu/J9+kXZ6rxoPy+7QJCqTDAs+Y1ZcOgUvRiJEEZpyJ3S0qpLEbfoKEr+15bw==", "user"=>{"firstname"=>"Han", "lastname"=>"Park", "gender"=>"Male", "dob(1i)"=>"1996", "dob(2i)"=>"12", "dob(3i)"=>"6", "ssn"=>"1432229824", "driver_license"=>"D768765764", "street_address"=>"1000 north", "city"=>"New York", "zip"=>"60098", "email"=>"han@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "tandc"=>"true"}, "state"=>"MD", "commit"=>"Sign Up"}
DEPRECATION WARNING: ssn is not an attribute known to Active Record. This
behavior is deprecated and will be removed in the next version of Rails. If
you'd like ssn to be managed by Active Record, add `attribute :ssn to your
class. (called from block in attr_encrypted at /Users/reynold/.rvm/gems/ruby-
2.2.2/gems/attr_encrypted-
3.0.3/lib/attr_encrypted/adapters/active_record.rb:75)
(0.3ms)  BEGIN
User Exists (0.8ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1
LIMIT $2  [["email", "han@saveup.com"], ["LIMIT", 1]]
SQL (6.2ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at",
"updated_at", "firstname", "lastname", "gender", "encrypted_ssn",
"encrypted_ssn_iv", "street_address", "city", "zip", "driver_license",
"tandc", "dob") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12,
$13, $14, $15) RETURNING "id"  [["email", "han@saveup.com"],
["encrypted_password",
"$2a$11$asC6.rG.aYUXJa8Ps.Gbeu3FzTFw64urmIB2KK9rxj94sH71gXaYm"],
["created_at", "2017-12-06 22:17:55.383121"], ["updated_at", "2017-12-06
22:17:55.383121"], ["firstname", "Han"], ["lastname", "Park"], ["gender",
"Male"], ["encrypted_ssn", "eWjL/lDpivR3T9cXx1w6rg==\n"], ["encrypted_ssn_iv",
"Rt/5Tl6PkwvqOjDC9nN1ng==\n"], ["street_address", "1000 north"], ["city",
"New York"], ["zip", "60098"], ["driver_license", "D768765764"], ["tandc",
"t"], ["dob", "1996-12-06"]]
(0.6ms)  COMMIT
(0.3ms)  BEGIN
SQL (2.4ms)  UPDATE "users" SET "sign_in_count" = $1, "current_sign_in_at" =
$2, "last_sign_in_at" = $3, "current_sign_in_ip" = $4, "last_sign_in_ip" = $5,
"updated_at" = $6 WHERE "users"."id" = $7  [["sign_in_count", 1],
["current_sign_in_at", "2017-12-06 22:17:55.397080"], ["last_sign_in_at",
"2017-12-06 22:17:55.397080"], ["current_sign_in_ip", "127.0.0.1/32"],
["last_sign_in_ip", "127.0.0.1/32"], ["updated_at", "2017-12-06
22:17:55.398231"], ["id", 18]]
(0.5ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 276ms (ActiveRecord: 11.1ms)

Started GET "/" for 127.0.0.1 at 2017-12-06 16:17:55 -0600
User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1
ORDER BY "users"."id" ASC LIMIT $2  [["id", 18], ["LIMIT", 1]]
Processing by HomeController#roothome as HTML
Rendering home/roothome.html.erb within layouts/application
Rendered shared/_comparechart.html.erb (1.0ms)
Rendered shared/_disclaimer.html.erb (0.7ms)
Rendered home/roothome.html.erb within layouts/application (8.1ms)
Rendered _navbar.html.erb (4.6ms)
Completed 200 OK in 478ms (Views: 474.8ms | ActiveRecord: 0.0ms)
</code>```

答:
Instead of building out the form tag and options manually wouldn’t it be cleaner to let rails do it? This would also have fixed the name issue for you:

```<code><%= form_for(resource, as: resource_name, :class=>'well form-horizontal' ,:style=>"margin-top:30px",url: registration_path(resource_name)) do |f| %>
  <%= f.select :state, CS.states(:us) %>
<% end %>
</code>```

Rails will also handle populating the current value when editing for you this way.

Body:
so I am using a gem called city-state gem in my web application to populate a dropdown list with the 50 states of US, but I am unable to save the selected value in the database,maybe I am missing something here, I have the following code:

<%= form_for(resource, as: resource_name, :class=>'well form-horizontal' ,:style=>"margin-top:30px",url: registration_path(resource_name)) do |f| %>
  <select name="form[state]">
    <% CS.states(:us).each do |key, value| %>
      <option value="<%= key %>"><%= value %></option>
    <% end %>
  </select>
<% end %>

I tried using

<%= f.select :state, value %>

but that would give me an empty dropdown list, any help appreciated.Thanks in advance.

Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"w1dXvna7zYZ96f9pNtCdm3ruIHu/J9+kXZ6rxoPy+7QJCqTDAs+Y1ZcOgUvRiJEEZpyJ3S0qpLEbfoKEr+15bw==", "user"=>{"firstname"=>"Han", "lastname"=>"Park", "gender"=>"Male", "dob(1i)"=>"1996", "dob(2i)"=>"12", "dob(3i)"=>"6", "ssn"=>"1432229824", "driver_license"=>"D768765764", "street_address"=>"1000 north", "city"=>"New York", "zip"=>"60098", "email"=>"han@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "tandc"=>"true"}, "state"=>"MD", "commit"=>"Sign Up"}
DEPRECATION WARNING: ssn is not an attribute known to Active Record. This
behavior is deprecated and will be removed in the next version of Rails. If
you'd like ssn to be managed by Active Record, add `attribute :ssn to your
class. (called from block in attr_encrypted at /Users/reynold/.rvm/gems/ruby-
2.2.2/gems/attr_encrypted-
3.0.3/lib/attr_encrypted/adapters/active_record.rb:75)
(0.3ms)  BEGIN
User Exists (0.8ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1
LIMIT $2  [["email", "han@saveup.com"], ["LIMIT", 1]]
SQL (6.2ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at",
"updated_at", "firstname", "lastname", "gender", "encrypted_ssn",
"encrypted_ssn_iv", "street_address", "city", "zip", "driver_license",
"tandc", "dob") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12,
$13, $14, $15) RETURNING "id"  [["email", "han@saveup.com"],
["encrypted_password",
"$2a$11$asC6.rG.aYUXJa8Ps.Gbeu3FzTFw64urmIB2KK9rxj94sH71gXaYm"],
["created_at", "2017-12-06 22:17:55.383121"], ["updated_at", "2017-12-06
22:17:55.383121"], ["firstname", "Han"], ["lastname", "Park"], ["gender",
"Male"], ["encrypted_ssn", "eWjL/lDpivR3T9cXx1w6rg==\n"], ["encrypted_ssn_iv",
"Rt/5Tl6PkwvqOjDC9nN1ng==\n"], ["street_address", "1000 north"], ["city",
"New York"], ["zip", "60098"], ["driver_license", "D768765764"], ["tandc",
"t"], ["dob", "1996-12-06"]]
(0.6ms)  COMMIT
(0.3ms)  BEGIN
SQL (2.4ms)  UPDATE "users" SET "sign_in_count" = $1, "current_sign_in_at" =
$2, "last_sign_in_at" = $3, "current_sign_in_ip" = $4, "last_sign_in_ip" = $5,
"updated_at" = $6 WHERE "users"."id" = $7  [["sign_in_count", 1],
["current_sign_in_at", "2017-12-06 22:17:55.397080"], ["last_sign_in_at",
"2017-12-06 22:17:55.397080"], ["current_sign_in_ip", "127.0.0.1/32"],
["last_sign_in_ip", "127.0.0.1/32"], ["updated_at", "2017-12-06
22:17:55.398231"], ["id", 18]]
(0.5ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 276ms (ActiveRecord: 11.1ms)

Started GET "/" for 127.0.0.1 at 2017-12-06 16:17:55 -0600
User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1
ORDER BY "users"."id" ASC LIMIT $2  [["id", 18], ["LIMIT", 1]]
Processing by HomeController#roothome as HTML
Rendering home/roothome.html.erb within layouts/application
Rendered shared/_comparechart.html.erb (1.0ms)
Rendered shared/_disclaimer.html.erb (0.7ms)
Rendered home/roothome.html.erb within layouts/application (8.1ms)
Rendered _navbar.html.erb (4.6ms)
Completed 200 OK in 478ms (Views: 474.8ms | ActiveRecord: 0.0ms)

Body:
Instead of building out the form tag and options manually wouldn’t it be cleaner to let rails do it? This would also have fixed the name issue for you:

<%= form_for(resource, as: resource_name, :class=>'well form-horizontal' ,:style=>"margin-top:30px",url: registration_path(resource_name)) do |f| %>
  <%= f.select :state, CS.states(:us) %>
<% end %>

Rails will also handle populating the current value when editing for you this way.


问:
How do I write conditional code based on which router link is active
My attempt is like this:</p>

```<code><ul class="nav nav-tabs search-selector" role="tablist">
  <li routerLinkActive="active"
    [routerLinkActiveOptions]="{ exact: true }">
    <a routerLink="{{ myroute[0].link }}">{{ myroute[0].label }}</a>
  </li>
  <li routerLinkActive="active"
    [routerLinkActiveOptions]="{ exact: true }">
    <a routerLink="{{ myroute[1].link }}">{{ myroute[1].label }}</a>
  </li>
</ul>
<div *ngif="route0 is active">do something related to route 0</div>
<div *ngif="route1 is active">do something related to route 1</div>
</code>```

答: @stefan-svrkota's answer is great but I found *ngIf="router.url=='/login'" also works

Body:
My attempt is like this:

    {{ myroute[0].label }}

    {{ myroute[1].label }}

do something related to route 0

do something related to route 1


问:
Reduce data frame where only one column varies in R
I have data like:

```<code>    V1    V2    V3    V4    V5
1   A     5.7    f    n     j47
2   A     5.7    f    n     j44
3   A     5.7    f    n     e54
4   B     5.1    m    y     j47
5   B     5.1    m    y     r10
</code>```

I want my output to like like:

```<code>1:    A    5.7    f    n    j47, j44, e54
2;    B    5.1    m    y    j47, r10
</code>```

ie only v5 vaires but I want to collapse my data so that all values for V5 for each identifier (given in V1) can be seen.

How can I do this?

答:
Using tidyr which is also part of the tidyverse along with dplyr: (Edit Note this adds a list column rather than collapsing V5 into a single string for each group)

library(tidyr)

nest(df, V5)
#>   V1  V2 V3 V4          data
#> 1  A 5.7  f  n j47, j44, e54
#> 2  B 5.1  m  y      j47, r10
```

<p><strong>Data used</strong></p>

<pre class="lang-r prettyprint-override"><code>df <- (read.table(text = "V1    V2    V3    V4    V5
1   A     5.7    f    n     j47
2   A     5.7    f    n     j44
3   A     5.7    f    n     e54
4   B     5.1    m    y     j47
5   B     5.1    m    y     r10", header = TRUE, stringsAsFactors = FALSE))
</code>```

Body:
I have data like:

    V1    V2    V3    V4    V5
1   A     5.7    f    n     j47
2   A     5.7    f    n     j44
3   A     5.7    f    n     e54
4   B     5.1    m    y     j47
5   B     5.1    m    y     r10

I want my output to like like:

1:    A    5.7    f    n    j47, j44, e54
2;    B    5.1    m    y    j47, r10

ie only v5 vaires but I want to collapse my data so that all values for V5 for each identifier (given in V1) can be seen.

How can I do this?

Body:
Using tidyr which is also part of the tidyverse along with dplyr: (Edit Note this adds a list column rather than collapsing V5 into a single string for each group)

library(tidyr)

nest(df, V5)
#>   V1  V2 V3 V4          data
#> 1  A 5.7  f  n j47, j44, e54
#> 2  B 5.1  m  y      j47, r10

Data used

df <- (read.table(text = "V1    V2    V3    V4    V5
1   A     5.7    f    n     j47
2   A     5.7    f    n     j44
3   A     5.7    f    n     e54
4   B     5.1    m    y     j47
5   B     5.1    m    y     r10", header = TRUE, stringsAsFactors = FALSE))


问:
fixed vector as template parameter on c++ class
I want to create a class like this:

```<code>template<std::vector<char> ID>
class test
{
      std::vector<char> m_id=ID;
 public:
      std::vector<char> getID()
      {
           return ID;
      }
}
</code>```

and then use it such as this:

```<code>typedef test1234 test<{'1','2','3','4','5'}>
test1234 t1;
std::cout <<t1.getID()<<std:;endl;
</code>```

How can I do this?

The idea is that I can define several classes with the same functionality, but different ID. I don't want to pass the ID as construction parameters (I know how to do that way!).

I am using VS 2013.

答:
If you change your problem from "how to initialize a vector with template parameter" (to which there is no solution with VS2013) to "how to have different constructors parametrised with template arguments" then I have a solution. You should define array of strings and pass a subscript for that array, that would sove it:

```<code>std::string initializers[]={{'1','2','3','4','5'},"Hello moto"};

template<int ID>
class test
{
      std::vector<char> m_id{initializers[ID].begin(),initializers[ID].end()};
 public:
      std::vector<char> getID()
      {
           return  std::vector<char> {initializers[ID].begin(),initializers[ID].end()};
      }
};
</code>```

Which will make following valid:

```<code>int main()
{
    typedef  test<1> test1234;
    test1234 t1;
    std::cout <<t1.getID()[0] <<std::endl; // you obviously do not have stream output operator for vector
}
</code>```

Add consts to your taste and probably encapsulate initializers if you want.

Body:
I want to create a class like this:

template<std::vector<char> ID>
class test
{
      std::vector<char> m_id=ID;
 public:
      std::vector<char> getID()
      {
           return ID;
      }
}

and then use it such as this:

typedef test1234 test<{'1','2','3','4','5'}>
test1234 t1;
std::cout <<t1.getID()<<std:;endl;

How can I do this?

The idea is that I can define several classes with the same functionality, but different ID. I don't want to pass the ID as construction parameters (I know how to do that way!).

I am using VS 2013.

Body:
If you change your problem from "how to initialize a vector with template parameter" (to which there is no solution with VS2013) to "how to have different constructors parametrised with template arguments" then I have a solution. You should define array of strings and pass a subscript for that array, that would sove it:

std::string initializers[]={{'1','2','3','4','5'},"Hello moto"};

template<int ID>
class test
{
      std::vector<char> m_id{initializers[ID].begin(),initializers[ID].end()};
 public:
      std::vector<char> getID()
      {
           return  std::vector<char> {initializers[ID].begin(),initializers[ID].end()};
      }
};

Which will make following valid:

int main()
{
    typedef  test<1> test1234;
    test1234 t1;
    std::cout <<t1.getID()[0] <<std::endl; // you obviously do not have stream output operator for vector
}

Add consts to your taste and probably encapsulate initializers if you want.


问:
"Deterministic" pseudorandom number generation
I am in a situation where I need to generate a very large (~10^16 elements) random matrix with a certain random sparsity pattern. Obviously storing all of these elements is completely infeasible. Only a few of the elements are needed at any given time, so they can be drawn on-demand - however, once an element is stored, it may be needed later, and it's important that the same value is used. i.e, elements cannot be thrown out and randomly redrawn - once a random element is drawn, it needs to be saved.

Based on the problem itself, there are potentially some clever ways to handle this that I won't get into. However, a colleague says that it should be possible to deterministically generate these random numbers as needed by using a pseudorandom number generator with seed given by the index in the matrix, i.e. use i + N*j for element (i, j) of the matrix where the matrix is size N*N. This would not be calling the rand() function, but using the underlying pseudorandom function with specific arguments to deterministically generate previously drawn random values. Then no numbers would need to be saved, and they could be deterministically redrawn on demand.

My understanding of PRG's was that for a sequence of numbers appear random, you must fix the seed. Does the above approach make sense? It seems to me to be like repeatedly re-seeding the PRG and just taking the first element.

答:
Basically, you want 1016 ~ 253 random numbers which uniquely determined by matrix element linear index.

Simplest random number generator would be 64bit Linear Congruential one. Basically any
reasonable one with 63-64bits length and full period will work. Code below
implements Knuth LCG with seed equal to matrix element linear index.
Another good property of the LCG is jump-ahead with logarithmic complexity - jump ~ log2(N)

Code

```<code>import numpy as np

A = np.uint64(6364136223846793005) # multiplier
C = np.uint64(1442695040888963407) # increment
K = np.float64(5.421010862427522170037E-20) # 1/2^64

def K64(seed):
    """
    Knuth 64bit MMIX LCG, return uint64 in the range [0...2^64)
    """
    return A*np.uint64(seed) + C

def KLCG64(seed):
    """
    Knuth 64bit MMIX LCG, return float64 in the range [0.0...1.0)
    """
    #return np.float64(K64(seed))*K # here is proper implementation, but slower than inlined code below
    return np.float64(A*np.uint64(seed) + C)*K

def randomMat(i, j, N):
    """
    return random element of the matrix
    """
    return KLCG64(np.uint64(i) + np.uint64(j)*np.uint64(N))

np.seterr(over='ignore') # important! LCG relies on unsigned overflow for mod operation

print(randomMat(123738, 9276, 735111))
</code>```

Body:
Basically, you want 1016 ~ 253 random numbers which uniquely determined by matrix element linear index.

Simplest random number generator would be 64bit Linear Congruential one. Basically any
reasonable one with 63-64bits length and full period will work. Code below
implements Knuth LCG with seed equal to matrix element linear index.
Another good property of the LCG is jump-ahead with logarithmic complexity - jump ~ log2(N)

Code

import numpy as np

A = np.uint64(6364136223846793005) # multiplier
C = np.uint64(1442695040888963407) # increment
K = np.float64(5.421010862427522170037E-20) # 1/2^64

def K64(seed):
    """
    Knuth 64bit MMIX LCG, return uint64 in the range [0...2^64)
    """
    return A*np.uint64(seed) + C

def KLCG64(seed):
    """
    Knuth 64bit MMIX LCG, return float64 in the range [0.0...1.0)
    """
    #return np.float64(K64(seed))*K # here is proper implementation, but slower than inlined code below
    return np.float64(A*np.uint64(seed) + C)*K

def randomMat(i, j, N):
    """
    return random element of the matrix
    """
    return KLCG64(np.uint64(i) + np.uint64(j)*np.uint64(N))

np.seterr(over='ignore') # important! LCG relies on unsigned overflow for mod operation

print(randomMat(123738, 9276, 735111))


答:
Another solution using base R's aggregate (no additional libraries necessary):

```<code>aggregate(data = df, V5 ~ V1 + V2 + V3 + V4, paste, collapse = ", ")
#  V1  V2 V3 V4            V5
#1  A 5.7  f  n j47, j44, e54
#2  B 5.1  m  y      j47, r10
</code>```

Data

```<code>df <- read.table(text =
    "V1    V2    V3    V4    V5
     1   A     5.7    f    n     j47
     2   A     5.7    f    n     j44
     3   A     5.7    f    n     e54
     4   B     5.1    m    y     j47
     5   B     5.1    m    y     r10", header = T)
</code>```

Title: Reduce data frame where only one column varies in R

Body:
Another solution using base R's aggregate (no additional libraries necessary):

aggregate(data = df, V5 ~ V1 + V2 + V3 + V4, paste, collapse = ", ")
#  V1  V2 V3 V4            V5
#1  A 5.7  f  n j47, j44, e54
#2  B 5.1  m  y      j47, r10

Data

df <- read.table(text =
    "V1    V2    V3    V4    V5
     1   A     5.7    f    n     j47
     2   A     5.7    f    n     j44
     3   A     5.7    f    n     e54
     4   B     5.1    m    y     j47
     5   B     5.1    m    y     r10", header = T)


问:
Using registerSeekCallback() to do seek operation in Spring Kafka
I have org.springframework.kafka.listener.ConcurrentMessageListenerContainer with N MessageListeners listening to N partitions of a topic. Sometimes the application needs to start at an offset different from last committed offset.
I made the listener to be ConsumerSeekAware and using registerSeekCallback(). Resetting to different offset is only needed when the application starts, not when it is running, so I don't need to store the callback that is given by registerSeekCallback().
As per the documentation, this registerSeekCallback() is invoked automatically when the listener container is started. So I'm going to invoke callback.seek(topic,partition,offset) method inside the registerSeekCallback method.

Question is, how can I get the partition which is assigned to the listener? seek method needs topic, partition, and offset as its arguments. Since partitions are assigned at runtime, I don't know how to get the right partition number to do seek operattion.

答:
registerSeekCallback is used to arbitrarily seek at runtime (any time after the container has started and partitions assigned).

Instead, you should do the seek in ConsumerSeekAware.onPartitionsAssigned() which will give you the partitions.


问:
Removing second single quote from a String in Java
I am trying to format an XML response in spring boot

In this response, I want to convert from

TitleBrief='arg Nallin' 106 HD' to
TitleBrief='arg Nallin 106 HD'

I have to use Regex to be able to do this.  Kindly suggest a good regex.

I tried this but it is not working.

```<code>String test="='Narg Mallin' '";
String pattern1="(=')(.[^']*)'";
System.out.println(test.replaceAll("(=')","=\"");
</code>```

答:
Actually, ctwheels's regex is a pretty easier way to solve this problem, and you can use it like this:

```<code>String test = "'arg Nallin' 106 HD'";
test.replaceAll("(?<!=)'(?!$)",""); // Returns "'arg Nallin 106 HD'"
</code>```

However, in other programming languages that do not support lookbehinds (JavaScript, for example), this might be what you're looking for:

As an alternative, you can capture all the text instead, except for the quote you need to remove.

Code

```<code>String test = "'arg Nallin' 106 HD'";
test.replaceAll("^([^']*'[^']*)'(.*'.*)$","$1$2"); // Returns "'arg Nallin 106 HD'"
</code>```

Explanation

/^([^']*'[^']*)'(.*'.*)$/
```

([^']*'[^']*) - This first capture group will:

[^']* - Match everything but the single quote.

' - Match the single quote you need to ignore.

[^']* - Match everything but the single quote.

' - Now, this quote is outside the other capturing groups, so it won't be present in $1, neither in $2

(.*'.*) - Capture the rest of the content after the quote, and make sure there is at least one ' left, so we can make sure the statement is an instance of a String.

Body:
I am trying to format an XML response in spring boot

In this response, I want to convert from

TitleBrief='arg Nallin' 106 HD' to
TitleBrief='arg Nallin 106 HD'

I have to use Regex to be able to do this.  Kindly suggest a good regex.

I tried this but it is not working.

String test="='Narg Mallin' '";
String pattern1="(=')(.[^']*)'";
System.out.println(test.replaceAll("(=')","=\"");

Body:
Actually, ctwheels's regex is a pretty easier way to solve this problem, and you can use it like this:

String test = "'arg Nallin' 106 HD'";
test.replaceAll("(?<!=)'(?!$)",""); // Returns "'arg Nallin 106 HD'"

However, in other programming languages that do not support lookbehinds (JavaScript, for example), this might be what you're looking for:

As an alternative, you can capture all the text instead, except for the quote you need to remove.

Code

String test = "'arg Nallin' 106 HD'";
test.replaceAll("^([^']*'[^']*)'(.*'.*)$","$1$2"); // Returns "'arg Nallin 106 HD'"

Explanation

/^([^']*'[^']*)'(.*'.*)$/

([^']*'[^']*) - This first capture group will:

[^']* - Match everything but the single quote.

' - Match the single quote you need to ignore.

[^']* - Match everything but the single quote.

' - Now, this quote is outside the other capturing groups, so it won't be present in $1, neither in $2

(.*'.*) - Capture the rest of the content after the quote, and make sure there is at least one ' left, so we can make sure the statement is an instance of a String.


问:
Laravel 5.5 - mail not working with `mail` driver
Ob my Laravel setup, mail was always working until I upgraded the framework to 5.5 (from 5.4). Now it always fail at the following:

Do note the following:

mail server on local env = http://www.toolheap.com/test-mail-server-tool/users-manual.html ive used this like since 5yrs (this is a one-click-install/no-dramas/no-config/no-error test mail server) and till yesterday it worked so im NOT changing it to something else

The php's mail() function works if called directly

The mail driver ive set is just mail however it still goes here to sendmail (you can vardump the $command and it says /usr/sbin/sendmail -bs)

Here is the .env for mail:

```<code>MAIL_DRIVER=mail
MAIL_HOST=localhost
MAIL_PORT=25
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
</code>```

So does anyone knows how to solve this? It only starred in laravel 5.5

Thanks a lot

答:
Found the reason and hence had to find an alternate solution.

[Reason]: Swiftmailer no longer supports mail transport

(See here)

https://github.com/swiftmailer/swiftmailer/issues/866

https://github.com/octobercms/october/issues/3256

[Solution]:
Use smtp instead of mail.

Body:
Ob my Laravel setup, mail was always working until I upgraded the framework to 5.5 (from 5.4). Now it always fail at the following:

Do note the following:

mail server on local env = http://www.toolheap.com/test-mail-server-tool/users-manual.html ive used this like since 5yrs (this is a one-click-install/no-dramas/no-config/no-error test mail server) and till yesterday it worked so im NOT changing it to something else

The php's mail() function works if called directly

The mail driver ive set is just mail however it still goes here to sendmail (you can vardump the $command and it says /usr/sbin/sendmail -bs)

Here is the .env for mail:

MAIL_DRIVER=mail
MAIL_HOST=localhost
MAIL_PORT=25
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

So does anyone knows how to solve this? It only starred in laravel 5.5

Thanks a lot


问:
gcloud command not found - while installing Google Cloud SDK
I am on a mac and am trying to install the Google Cloud SDK (including the gcloud command line utility) using this command in terminal

```<code>curl https://sdk.cloud.google.com | bash
</code>```

as seen at https://cloud.google.com/sdk/

It got all the way to the end and finished but even after I restarted my shell, the gcloud command still says it's not found.

Why isn't this installation working?

答:
Now after running install.sh in Mac OS, google itself giving the information to run completion.bash.inc and path.bash.inc.

If you're using zsh terminal, it'll ask you to run completion.zsh.inc and path.zsh.inc. Please see the image below

Body:
I am on a mac and am trying to install the Google Cloud SDK (including the gcloud command line utility) using this command in terminal

curl https://sdk.cloud.google.com | bash

as seen at https://cloud.google.com/sdk/

It got all the way to the end and finished but even after I restarted my shell, the gcloud command still says it's not found.

Why isn't this installation working?


问:
How to test Rails 3 Engines with Cucumber & Rspec?
I apologize if this question is slightly subjective... I am trying to figure out the best way to test Rails 3 Engines with Cucumber & Rspec.  In order to test the engine a rails 3 app is necessary.  Here is what I am currently doing:

Add a rails test app to the root of the gem (myengine) by running:  rails new /myengine/rails_app

Add Cucumber to /myengine/rails_app/features as you would in a normal Rails app

Require the Rails Engine Gem (using :path=>"/myengine") in /myengine/rails_app/Gemfile

Add spec to the root directory of the gem: /myengine/spec

Include the fixtures in /myengine/spec/fixtures and I add the following to my cuc env.rb:

env.rb:

```<code>Fixtures.reset_cache
fixtures_folder = File.join(Rails.root, 'spec', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
Fixtures.create_fixtures(fixtures_folder, fixtures)
</code>```

Do you see any problems with setting it up like this?  The tests run fine, but I am a bit hesitant to put the features inside the test rails app.  I originally tried putting the features in the root of the gem and I created the test rails app inside features/support, but for some reason my engine would not initialize when I ran the tests, even though I could see the app loading everything else when cuc ran.

If anyone is working with Rails Engines and is using cuc and rspec for testing, I would be interested to hear your setup.

**UPDATE

I changed my setup a bit since I wrote this question.  I decided to get rid of the spec directory under the root of the engine.  Now I just create a rails app named "test_app" and setup cuc and rspec inside that app like I would normally do in a rails app.  Then I include the gem like I did in step #3 above.  Since the engine is a sub-app, I guess its just best to test it like it was a normal rails app.  I am still interested in hearing if anyone has a different setup.

答:
I'll explain how I did it using as example the following gem: https://github.com/skozlov/netzke-core

The testing application. It is in netzke-core/test/rails_app. This app can be run independently, so I can also use it for manual testing or for playing around with new features if I like.

In order for the testing app to load the gem itself, I have the following in application.rb:

```<code>$:.unshift File.expand_path('../../../../lib', __FILE__)
require 'netzke-core'
</code>```

Cucumber features. They are in netzke-core/features. In env.rb I have:

```<code>require File.expand_path(File.dirname(__FILE__) + '/../../test/rails_app/config/environment')
</code>```

... which will load the testing application before executing the features.

Specs. These are in netzke-core/spec. In spec_helper.rb I have the following:

```<code>require File.expand_path("../../test/rails_app/config/environment", __FILE__)
</code>```

... which will load the testing application before running the specs.

Running tests. This setup lets me run the tests from the root of the gem:

```<code>cucumber features
</code>```

and

```<code>rspec spec
</code>```

Factory Girl. Not for this particular gem, but I'm normally using factory_girl instead of fixtures (see, for example, a similar setup in https://github.com/skozlov/netzke-basepack).

Body:
I apologize if this question is slightly subjective... I am trying to figure out the best way to test Rails 3 Engines with Cucumber & Rspec.  In order to test the engine a rails 3 app is necessary.  Here is what I am currently doing:

Add a rails test app to the root of the gem (myengine) by running:  rails new /myengine/rails_app

Add Cucumber to /myengine/rails_app/features as you would in a normal Rails app

Require the Rails Engine Gem (using :path=>"/myengine") in /myengine/rails_app/Gemfile

Add spec to the root directory of the gem: /myengine/spec

Include the fixtures in /myengine/spec/fixtures and I add the following to my cuc env.rb:

env.rb:

Fixtures.reset_cache
fixtures_folder = File.join(Rails.root, 'spec', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
Fixtures.create_fixtures(fixtures_folder, fixtures)

Do you see any problems with setting it up like this?  The tests run fine, but I am a bit hesitant to put the features inside the test rails app.  I originally tried putting the features in the root of the gem and I created the test rails app inside features/support, but for some reason my engine would not initialize when I ran the tests, even though I could see the app loading everything else when cuc ran.

If anyone is working with Rails Engines and is using cuc and rspec for testing, I would be interested to hear your setup.

**UPDATE

I changed my setup a bit since I wrote this question.  I decided to get rid of the spec directory under the root of the engine.  Now I just create a rails app named "test_app" and setup cuc and rspec inside that app like I would normally do in a rails app.  Then I include the gem like I did in step #3 above.  Since the engine is a sub-app, I guess its just best to test it like it was a normal rails app.  I am still interested in hearing if anyone has a different setup.

Body:
I'll explain how I did it using as example the following gem: https://github.com/skozlov/netzke-core

The testing application. It is in netzke-core/test/rails_app. This app can be run independently, so I can also use it for manual testing or for playing around with new features if I like.

In order for the testing app to load the gem itself, I have the following in application.rb:

$:.unshift File.expand_path('../../../../lib', __FILE__)
require 'netzke-core'

Cucumber features. They are in netzke-core/features. In env.rb I have:

require File.expand_path(File.dirname(__FILE__) + '/../../test/rails_app/config/environment')

... which will load the testing application before executing the features.

Specs. These are in netzke-core/spec. In spec_helper.rb I have the following:

require File.expand_path("../../test/rails_app/config/environment", __FILE__)

... which will load the testing application before running the specs.

Running tests. This setup lets me run the tests from the root of the gem:

cucumber features

and

rspec spec

Factory Girl. Not for this particular gem, but I'm normally using factory_girl instead of fixtures (see, for example, a similar setup in https://github.com/skozlov/netzke-basepack).


问:
Google app engine Endpoints, Objectify Register
I start google app engine with endpoints, I use objectify for persistence and I have an little question.(I hope !)

All my apiMethod start like it :

```<code>@ApiMethod(path = "getAccount", httpMethod = HttpMethod.GET)
public Account getAccount(@Named("idPlayer") long idPlayer) {
    ObjectifyLoader.loadEntity();
</code>```

ObjectifyLoader.loadEntity(); is just a method like it

```<code>   public static void loadEntity(){
    ObjectifyService.register(Account.class);
    ObjectifyService.register(WeaponsAccount.class);
}
</code>```

I got the impression that I register my class et each call to the api.

A tips for load only one time?

Thanks you for reading.
Fabiitch

答: You want to use a ServletContextListener. Check out this App Engine oage for an example.

ContentLicense: CC BY-SA 4.0

Body:
I start google app engine with endpoints, I use objectify for persistence and I have an little question.(I hope !)

All my apiMethod start like it :

@ApiMethod(path = "getAccount", httpMethod = HttpMethod.GET)
public Account getAccount(@Named("idPlayer") long idPlayer) {
    ObjectifyLoader.loadEntity();

ObjectifyLoader.loadEntity(); is just a method like it

   public static void loadEntity(){
    ObjectifyService.register(Account.class);
    ObjectifyService.register(WeaponsAccount.class);
}

I got the impression that I register my class et each call to the api.

A tips for load only one time?

Thanks you for reading.
Fabiitch


问:
Invalid name: "@angular/cli" when do npm install
I need to install angular/cli package, but got error

$sudo npm install -g @angular/cli

But I got the following error

```<code>npm ERR! Darwin 16.7.0

npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "@angular/cli"

npm ERR! node v6.6.0

npm ERR! npm  v3.10.3

npm ERR! Invalid name: "@angular/cli"

npm ERR!

npm ERR! If you need help, you may report this error at:

npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:

npm ERR!     /Users/jim/Downloads/project/admin/npm-debug.log
</code>```

答:
Somehow it looks weird as I configured angular/cli in package.json, but it result from npm version is outdated, so I did the npm update

$sudo npm update npm -g

Also the following commands can help check versions and do a clean install via "uninstall -> clean -> install".

$npm --v

$node -v

$sudo npm uninstall -g angular-cli

$sudo npm cache clean

$sudo npm install -g angular-cli@latest

Body:
I need to install angular/cli package, but got error

$sudo npm install -g @angular/cli

But I got the following error

npm ERR! Darwin 16.7.0

npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "@angular/cli"

npm ERR! node v6.6.0

npm ERR! npm  v3.10.3

npm ERR! Invalid name: "@angular/cli"

npm ERR!

npm ERR! If you need help, you may report this error at:

npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:

npm ERR!     /Users/jim/Downloads/project/admin/npm-debug.log


问:
How to apply timezone when formatting DateTime?
I have a datetime as 2011-01-11 01:51:10 and timezone as America/Los_Angeles

I want to get a localised date time for this value. This is what I do

```<code>val formatter1: DateTimeFormatter = DateTimeFormatter.ofPattern("y-M-d H:m:s");
val m1: LocalDateTime = LocalDateTime.parse("2011-01-11 01:51:10", formatter1);
println("DateTime: " + m1.atZone(ZoneId.of("America/Los_Angeles")))
</code>```

The value that I get is

```<code>DateTime: 2011-01-11T01:51:10-08:00[America/Los_Angeles]
</code>```

How do I convert it into localized datetime with -08:00 offset applied to it and no [America/Los_Angeles]?

答:
Please look into my complete answer for this. Answer</p>

```<code>    String dateTime = "MM/dd/yyyy HH:mm:ss";
    String date = "09/17/2017 20:53:31";
    Integer gmtPSTOffset = -8;
    ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset);

    // String to LocalDateTime
    LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime));
    // Set the generated LocalDateTime's TimeZone. In this case I set it to UTC
    ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC);
    System.out.println("UTC time with Timezone          : "+ldtUTC);

    // Convert above UTC to PST. You can pass ZoneOffset or ZoneId for 2nd parameter
    LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset);
    System.out.println("PST time without offset         : "+ldtPST);

    // If you want UTC time with timezone
    ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
    ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId);
    System.out.println("PST time with Offset and TimeZone   : "+zdtPST);
</code>```

Body:
I have a datetime as 2011-01-11 01:51:10 and timezone as America/Los_Angeles

I want to get a localised date time for this value. This is what I do

val formatter1: DateTimeFormatter = DateTimeFormatter.ofPattern("y-M-d H:m:s");
val m1: LocalDateTime = LocalDateTime.parse("2011-01-11 01:51:10", formatter1);
println("DateTime: " + m1.atZone(ZoneId.of("America/Los_Angeles")))

The value that I get is

DateTime: 2011-01-11T01:51:10-08:00[America/Los_Angeles]

How do I convert it into localized datetime with -08:00 offset applied to it and no [America/Los_Angeles]?

Body:
Please look into my complete answer for this. Answer

    String dateTime = "MM/dd/yyyy HH:mm:ss";
    String date = "09/17/2017 20:53:31";
    Integer gmtPSTOffset = -8;
    ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset);

    // String to LocalDateTime
    LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime));
    // Set the generated LocalDateTime's TimeZone. In this case I set it to UTC
    ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC);
    System.out.println("UTC time with Timezone          : "+ldtUTC);

    // Convert above UTC to PST. You can pass ZoneOffset or ZoneId for 2nd parameter
    LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset);
    System.out.println("PST time without offset         : "+ldtPST);

    // If you want UTC time with timezone
    ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
    ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId);
    System.out.println("PST time with Offset and TimeZone   : "+zdtPST);


问:
Loop through QSpinbox when reaches the end
Is there any way to create a QSpinbox that sets itself to the first value, when it reaches the end, and the step up button is pressed again?

I tried doing it in a custom QSpinBox but what happens is that when it reaches to the last value, y gets instantly reset, which leads to never seeing the last value.

```<code>from PyQt5.QtWidgets import QSpinBox
from music import TonoFactory

_tf = TonoFactory()

class StringBox(QSpinBox):
    def __init__(self, parent=None):
        super(StringBox, self).__init__(parent)
        strings = []
        for key in _tf.notas.keys():
            strings.append(key)
        self.setStrings(strings)
        self.editingFinished.connect(self.reset_spin)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        strings = list(strings)
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings) - 1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

    def reset_spin(self):
        if self.value() == len(self.strings()) -1:
            self.setValue(0)
</code>```

答:
A solution strategy is to add an element before and to the last so that the buttons remain enabled, we intercept the changes so that instead of going to the last go to the second, and vice versa, instead of going to the first one, you must go to the last one.

Example:

```<code>class StringBox(QSpinBox):
    def __init__(self, parent=None):
        super(StringBox, self).__init__(parent)
        strings = []
        texts = ["do", "re", "mi", "fa", "sol", "la", "si"]
        for key in texts:
            strings.append(key)
        self.setStrings([""] + strings + ["-"])
        self.setValue(1)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        strings = list(strings)
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings)-1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

    def stepBy(self, step):
        if self.value() == 1 and step == -1:
            self.setValue(self.maximum())
        elif self.value() == self.maximum() -1  and step == 1:
            self.setValue(0)
        QSpinBox.stepBy(self, step)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = StringBox()
    w.show()
    sys.exit(app.exec_())
</code>```

Note: Since you are using a dictionary and these can not have repeated keys, I recommend that the elements you add be different from the texts you show.

Body:
Is there any way to create a QSpinbox that sets itself to the first value, when it reaches the end, and the step up button is pressed again?

I tried doing it in a custom QSpinBox but what happens is that when it reaches to the last value, y gets instantly reset, which leads to never seeing the last value.

from PyQt5.QtWidgets import QSpinBox
from music import TonoFactory

_tf = TonoFactory()

class StringBox(QSpinBox):
    def __init__(self, parent=None):
        super(StringBox, self).__init__(parent)
        strings = []
        for key in _tf.notas.keys():
            strings.append(key)
        self.setStrings(strings)
        self.editingFinished.connect(self.reset_spin)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        strings = list(strings)
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings) - 1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

    def reset_spin(self):
        if self.value() == len(self.strings()) -1:
            self.setValue(0)

Body:
A solution strategy is to add an element before and to the last so that the buttons remain enabled, we intercept the changes so that instead of going to the last go to the second, and vice versa, instead of going to the first one, you must go to the last one.

Example:

class StringBox(QSpinBox):
    def __init__(self, parent=None):
        super(StringBox, self).__init__(parent)
        strings = []
        texts = ["do", "re", "mi", "fa", "sol", "la", "si"]
        for key in texts:
            strings.append(key)
        self.setStrings([""] + strings + ["-"])
        self.setValue(1)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        strings = list(strings)
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings)-1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

    def stepBy(self, step):
        if self.value() == 1 and step == -1:
            self.setValue(self.maximum())
        elif self.value() == self.maximum() -1  and step == 1:
            self.setValue(0)
        QSpinBox.stepBy(self, step)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = StringBox()
    w.show()
    sys.exit(app.exec_())

Note: Since you are using a dictionary and these can not have repeated keys, I recommend that the elements you add be different from the texts you show.


问:
Limit access to web api 2 controller in dotnet core mvc project
what is the best way to limit access to a webapi 2 controller within a MVC project to only the hosted App Service?

I have created a endpoint which my MVC client is accessing. The entire application is published to azure through an app service. How can I now protect the endpoint from being called outside of the application context?

答:
You could use an API key in the request's header to filter out unwanted request.
1. Implement a customer authorization attribute (AuthorizationFilter) class.

```<code>    [HttpPost, AuthorizationFilter]
    public CustomerInfo GetCustomerInfo(CustomerInfoRequest request)
    {
        return Business.GetCustomerInfo(request);
    }
</code>```

2. In your controller class

```<code>    public override void OnAuthorization(HttpActionContext ctx)
    {
        if (!VerifyHeaders(ctx))
        {
            ctx.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }

        base.OnAuthorization(ctx);
    }

    private bool VerifyHeaders(HttpActionContext ctx)
    {
        IEnumerable<string> values = new List<string>();

        //Read the API key from the request header
        ctx.Request.Headers.TryGetValues("ApiKey", out values);
        var apiKey = values?.FirstOrDefault();

        return CheckApiKey(apiKey);
    }

    private bool CheckApiKey(string apiKey)
    {
        //Verification is done here
        return true;
    }
</code>```

The request should contain API key which will be verified by "OnAuthorization" method.

Body:
You could use an API key in the request's header to filter out unwanted request.
1. Implement a customer authorization attribute (AuthorizationFilter) class.

    [HttpPost, AuthorizationFilter]
    public CustomerInfo GetCustomerInfo(CustomerInfoRequest request)
    {
        return Business.GetCustomerInfo(request);
    }

2. In your controller class

    public override void OnAuthorization(HttpActionContext ctx)
    {
        if (!VerifyHeaders(ctx))
        {
            ctx.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }

        base.OnAuthorization(ctx);
    }

    private bool VerifyHeaders(HttpActionContext ctx)
    {
        IEnumerable<string> values = new List<string>();

        //Read the API key from the request header
        ctx.Request.Headers.TryGetValues("ApiKey", out values);
        var apiKey = values?.FirstOrDefault();

        return CheckApiKey(apiKey);
    }

    private bool CheckApiKey(string apiKey)
    {
        //Verification is done here
        return true;
    }

The request should contain API key which will be verified by "OnAuthorization" method.


问:
When does app receipt get new transaction?
I have an app that has been using the now-deprecated pre-iOS 7 method of implementing IAP by looking at the transactionReceipt contained in the transactions that come to our transaction queue observer. That was working great. The new implementation of the observer just keeps track of whether any new transactions are being reported (state is SKPaymentTransactionStatePurchased) and if any are found in the queue, it grabs the application receipt (not the transactionReceipt) and sends that to the server.

Up until today, I found that the new transaction was always in the "in_app" field in the decrypted app receipt I get back from Apple. Today I'm testing subscriptions (which is working as far as I can tell) but noticed that when I order a non-subscription, non-consumable product, the transaction for it is not present in the "in_app" array in the app receipt until I order another non-subscription, non-consumable product. At that point I see the previously ordered product in the "in_app" array, but not the newly ordered one.

Both the previously purchased and newly purchased items are present in the "latest_receipt_info" array. I would just use that array instead of "in_app", but I hadn't started seeing "latest_receipt_info" until I started testing subscriptions, so I don't think it's always there.

Question: Am I missing a step? Should I be refreshing my app receipt in my transaction queue observer before using it? If I do, won't it prompt the user for their Apple ID credentials kind of inexplicably (they just placed an order and entered their credentials; I don't want them to have to do that again)?

答:
I don't think you are missing a step. I do think it is strange that the consumable purchase isn't showing up immediately on the on disk receipt, but it is possible that this is normal behavior, I'm not sure.

You could always trigger a receipt refresh. If the user just purchased a non-consumable item, and went through the purchase flow they shouldn't see a another login pop-up.

The other alternative is to use the latest_receipt_info on the server side as your source of truth. This field is only present if you send your iTunes Connect App-Specific Share Secret in the password field of the request JSON.

Personally, I would use the latest_receipt_info.


问:
How to remove XCode9 "Conversion to swift 4 is available" warning?
I had to convert my project manually since Xcode would crash when I tried to use the migration tool. Now that that's done I'd like to remove the warning from my project. I can't see any obvious way to do it and clicking on the warning immediately crashes Xcode which is why I ended up manually converting to begin with. </p>

答:
When manually converting - not using the migration tool - to Swift 4, remember to set the project setting to be Swift 4. (Project | Build Settings | Swift Compiler - Language | Swift Language Version.)

Screen shot:


问:
Resources for TDD aimed at Python Web Development
I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.

Are there any particular ones you would recommend for this language/application?

答:
I wrote a series of blogs on TDD in Django that covers some TDD with the nose testing framework.

There are a lot of free online resources out there for learning about TDD:

The c2 wiki article gives good background on general TDD philosophy.

The onlamp article is a simple introduction.

Here's a presentation on TDD with game development in pygame that really helped me understand TDD.

For testing web applications, test first or otherwise, I'd recommend twill and selenium as tools to use.

OwnerDisplayName: Null Route

OwnerDisplayName: Ryan


问:
Passing variables to the __() function in CakePHP
I'm in the process of building a little project this weekend called Pirates Vs. Ninjas Vs. Zombies Vs. Robots ;)

The purpose is to learn some of the aspects of Cake that I've not yet used before - such as the __() function for translation.

I've got a message that I want to output along the lines of "The %s thank you", where %s would be 'Zombies'. If I was using normal PHP, I guess I would use:

```<code>$string = 'Zombies';
printf('The %s thank you', $string);
</code>```

But as I'm trying to use the __() translate function, I don't know how to make this work.

Can anyone help me please? Thank you :)

答:
Set the second parameter of the __ function to true and it will return the translated string instead of echoing it:

```<code>$string = 'Zombies';
printf(__('The %s thank you', true), $string);
</code>```

Body:
I'm in the process of building a little project this weekend called Pirates Vs. Ninjas Vs. Zombies Vs. Robots ;)

The purpose is to learn some of the aspects of Cake that I've not yet used before - such as the __() function for translation.

I've got a message that I want to output along the lines of "The %s thank you", where %s would be 'Zombies'. If I was using normal PHP, I guess I would use:

$string = 'Zombies';
printf('The %s thank you', $string);

But as I'm trying to use the __() translate function, I don't know how to make this work.

Can anyone help me please? Thank you :)

Body:
Set the second parameter of the __ function to true and it will return the translated string instead of echoing it:

$string = 'Zombies';
printf(__('The %s thank you', true), $string);


问:
A customized npm script to compile, watch and server
I'm trying to set up a project which makes use of express and react. And I'm trying to make the best use of React-Slingshot project to benefit from it as much as possible. But the thing is that my project needs to be served (on the server side) by a script which I wrote. That script will use express and possibly socket.io to server the client side.

I think this is a problem if I use projects like React-Slingshot since they come with their own server scripts which support hot reloading and stuff. I'm willing to give up the fancy functionality like hot reloading. But I need to keep the --watch functionality so each time some file is changed, the code is compiled without me restarting the whole server.

Right now, the script section of package.json looks like this:

```<code>  "scripts": {
    "preinstall": "node tools/nodeVersionCheck.js",
    "setup": "node tools/setup/setupMessage.js && npm install && node tools/setup/setup.js",
    "remove-demo": "babel-node tools/removeDemo.js",
    "start-message": "babel-node tools/startMessage.js",
    "prestart": "npm run start-message",
    "start": "concurrently -k -r -s first \"npm run test:watch\" \"npm run open:src\" \"npm run lint:watch\"",
    "open:src": "babel-node tools/srcServer.js",
    "open:dist": "babel-node tools/distServer.js",
    "lint": "esw webpack.config.* src tools --color",
    "lint:watch": "npm run lint -- --watch",
    "clean-dist": "npm run remove-dist && mkdir dist",
    "remove-dist": "rimraf ./dist",
    "prebuild": "npm run clean-dist && npm run lint && npm run test",
    "build": "babel-node tools/build.js && babel server -d dist --presets es2015,stage-2",
    "test": "jest",
    "test:CI": "babel-node tools/testCi.js",
    "test:cover": "npm run test -- --coverage ",
    "test:cover:CI": "npm run test:CI -- --coverage && cat ./coverage/lcov.info | node_modules/coveralls/bin/coveralls.js",
    "test:watch": "jest --watch",
    "open:cover": "npm run test:cover && opn ./coverage/lcov-report/index.html",
    "analyze-bundle": "babel-node ./tools/analyzeBundle.js"
  },
</code>```

This is a modified version of what you can find in React-Slingshot. I've made a change so when I run npm run build, it builds the server code as well and terminates. It used to be like this:

```<code>   "build": "babel-node tools/build.js && npm run open:dist",
</code>```

Now, I'm trying to find a way to run my own server (i.e. node temp/server.js) while the rest of the code is compiled based on --watch as for my dev environment.

答: I believe you need a package like watch also check this video</p>

Body:
I'm trying to set up a project which makes use of express and react. And I'm trying to make the best use of React-Slingshot project to benefit from it as much as possible. But the thing is that my project needs to be served (on the server side) by a script which I wrote. That script will use express and possibly socket.io to server the client side.

I think this is a problem if I use projects like React-Slingshot since they come with their own server scripts which support hot reloading and stuff. I'm willing to give up the fancy functionality like hot reloading. But I need to keep the --watch functionality so each time some file is changed, the code is compiled without me restarting the whole server.

Right now, the script section of package.json looks like this:

  "scripts": {
    "preinstall": "node tools/nodeVersionCheck.js",
    "setup": "node tools/setup/setupMessage.js && npm install && node tools/setup/setup.js",
    "remove-demo": "babel-node tools/removeDemo.js",
    "start-message": "babel-node tools/startMessage.js",
    "prestart": "npm run start-message",
    "start": "concurrently -k -r -s first \"npm run test:watch\" \"npm run open:src\" \"npm run lint:watch\"",
    "open:src": "babel-node tools/srcServer.js",
    "open:dist": "babel-node tools/distServer.js",
    "lint": "esw webpack.config.* src tools --color",
    "lint:watch": "npm run lint -- --watch",
    "clean-dist": "npm run remove-dist && mkdir dist",
    "remove-dist": "rimraf ./dist",
    "prebuild": "npm run clean-dist && npm run lint && npm run test",
    "build": "babel-node tools/build.js && babel server -d dist --presets es2015,stage-2",
    "test": "jest",
    "test:CI": "babel-node tools/testCi.js",
    "test:cover": "npm run test -- --coverage ",
    "test:cover:CI": "npm run test:CI -- --coverage && cat ./coverage/lcov.info | node_modules/coveralls/bin/coveralls.js",
    "test:watch": "jest --watch",
    "open:cover": "npm run test:cover && opn ./coverage/lcov-report/index.html",
    "analyze-bundle": "babel-node ./tools/analyzeBundle.js"
  },

This is a modified version of what you can find in React-Slingshot. I've made a change so when I run npm run build, it builds the server code as well and terminates. It used to be like this:

   "build": "babel-node tools/build.js && npm run open:dist",

Now, I'm trying to find a way to run my own server (i.e. node temp/server.js) while the rest of the code is compiled based on --watch as for my dev environment.


问:
Excel list dependent on Vlookup
I have a table.

```<code>-----------------------
| Column 1 | Column 2 |
-----------------------
| A        |     X    |
-----------------------
| B        |     R    |
-----------------------
| C        |     T    |
-----------------------
| A        |     Y    |
-----------------------
| B        |     Q    |
-----------------------
| A        |     Z    |
-----------------------
</code>```

I have created a drop-down list in excel for "Column 1", but I would like another list that would display all values for whatever was select from "Column 1" e.g. if "A" was selected, I would then only have the options "X, Y, Z" available for selection.

I looked online for a solution but none work like above.

Is there any way to complete this in Data Validation?

Thanks!

答:
Instead of a data validation drop-down, maybe you could use slicers instead!

First filter your data as a table, then under table tools "Insert Slicer" insert two slicers, one for Column 1 and one for Column 2:

Screenshot (1)

And then right click on the "Column 2" Slicer, in "Slicer Settings" choose "Hide Items with no data" and then when you select "A" in the Column1 slicer, the Column2 Slicer will be filtered to "X,Y,Z"

Screenshot (2)

Hope this helps!

Title: Excel list dependent on Vlookup

Body:
I have a table.

-----------------------
| Column 1 | Column 2 |
-----------------------
| A        |     X    |
-----------------------
| B        |     R    |
-----------------------
| C        |     T    |
-----------------------
| A        |     Y    |
-----------------------
| B        |     Q    |
-----------------------
| A        |     Z    |
-----------------------

I have created a drop-down list in excel for "Column 1", but I would like another list that would display all values for whatever was select from "Column 1" e.g. if "A" was selected, I would then only have the options "X, Y, Z" available for selection.

I looked online for a solution but none work like above.

Is there any way to complete this in Data Validation?

Thanks!


问:
Different realizations with the same random seed
I have a project with different modules. Then I have a file called Main.py which has some code that calls these modules during the run. In the file Main.py I set random seed using:

```<code>random.seed(2)
</code>```

The output that I get from different runs is not identical even if I use the same random seed. Could you tell me why this might be happening? The various modules in my class use random.uniform, random.choice, random.sample functions. In one place, I also define rnduniform = random.uniform and use that.

Any help about how to solve this problem (i.e., be able to replicate the result by setting random seed) and help me understand this would be greatly appreciated.

Thank you.

EDIT: Solved. My error.

Sorry for wasting your time. I looked more carefully at the code and one of the functions that uses random number generation was called in an init method of one of the classes. The init method was accessed before the seed was set. I tried to delete the post but I could not. Hence, this edit.

答:
Thread safety deals with concurrent programming - or in other words, when you two different codepaths executing at the same time through means of threading. As something that might be a single line of code to you as a programmer are usually a multitude of seperate actions, a different thread might interfere with whatever variables you are using, or use intermediate calculations. This will cause very hard to understand bugs because usually your code will seem completely fine.

In this case, he is saying that your code using random() and other code in a thread that is somehow using the random number generator might conflict and not behave as expected. For example, the numbers might not be as mathematically random any longer, or if you initialize with a certain base seed and then expect random() return a number of set values over multiple calls, those numbers may not be the ones you expect to be returned. In the very worst case of using non-thread-safe functions, you might end up with harsh exceptions and/or crashes since the function is not designed to be used in multiple threads at the same time.

Also see the Wikipedia topic on Thread safety.

Body:
I have a project with different modules. Then I have a file called Main.py which has some code that calls these modules during the run. In the file Main.py I set random seed using:

random.seed(2)

The output that I get from different runs is not identical even if I use the same random seed. Could you tell me why this might be happening? The various modules in my class use random.uniform, random.choice, random.sample functions. In one place, I also define rnduniform = random.uniform and use that.

Any help about how to solve this problem (i.e., be able to replicate the result by setting random seed) and help me understand this would be greatly appreciated.

Thank you.

EDIT: Solved. My error.

Sorry for wasting your time. I looked more carefully at the code and one of the functions that uses random number generation was called in an init method of one of the classes. The init method was accessed before the seed was set. I tried to delete the post but I could not. Hence, this edit.


问:
Use Linq to search through table for items from a custom class
My code below works but I'm trying to find out how to optimize this and/or make it faster by changing it to one line because currently it performs a query on the database table once per loop and this seems to take forever

The custom class and sql table both have the same exact names as you can see. The queryList is a list of the custom class.

```<code>foreach (var item in queryList)
{
    var query = context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days).ToList();

    if (query.Count() > 0)
    {
         context.DataTable.RemoveRange(query);
    }
}
</code>```

答:
If your queryList is not a huge list, this may work:

I assume symbol should actual be item.Symbol. If that's the case, try this:

```<code>var items = queryList
    .Select(item => item.ValueName + "," + item.Symbol + "," + item.Days.ToString())
    .ToList();
var query = context.DataTable
    .Where(i => items.Contains(i.ValueName + "," + i.Symbol + "," + i.Days.ToString());
</code>```

The idea is to build a list of strings that LINQ to SQL can convert to WHERE x IN (str1, str2, str3) clause.

Body:
My code below works but I'm trying to find out how to optimize this and/or make it faster by changing it to one line because currently it performs a query on the database table once per loop and this seems to take forever

The custom class and sql table both have the same exact names as you can see. The queryList is a list of the custom class.

foreach (var item in queryList)
{
    var query = context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days).ToList();

    if (query.Count() > 0)
    {
         context.DataTable.RemoveRange(query);
    }
}

Body:
If your queryList is not a huge list, this may work:

I assume symbol should actual be item.Symbol. If that's the case, try this:

var items = queryList
    .Select(item => item.ValueName + "," + item.Symbol + "," + item.Days.ToString())
    .ToList();
var query = context.DataTable
    .Where(i => items.Contains(i.ValueName + "," + i.Symbol + "," + i.Days.ToString());

The idea is to build a list of strings that LINQ to SQL can convert to WHERE x IN (str1, str2, str3) clause.


问:
Disable attribute doesn't work with Azure Functions
I'm trying to disable a Function app, by using the Disable attribute with an app setting:

```<code>[Disable("Disable")]
[FunctionName("MyFunction")]
public static void Run([TimerTrigger("0 0 8 * * *")]TimerInfo myTimer)
</code>```

When compiling this function, the function.json looks like this:

```<code>{
    ...
    "disabled": "Disable",
    ...
}
</code>```

On my function app on Azure, I've defined the following app setting:

But when looking at the functions in the function app, the function is still disabled:

I was expecting the function not to be disabled, since the value of the app setting is 0. I guess the function app is disabled if the value of the disabled field in json is true if not set to false?

答: This is a known bug found here.</p>

Body:
I'm trying to disable a Function app, by using the Disable attribute with an app setting:

[Disable("Disable")]
[FunctionName("MyFunction")]
public static void Run([TimerTrigger("0 0 8 * * *")]TimerInfo myTimer)

When compiling this function, the function.json looks like this:

{
    ...
    "disabled": "Disable",
    ...
}

On my function app on Azure, I've defined the following app setting:

But when looking at the functions in the function app, the function is still disabled:

I was expecting the function not to be disabled, since the value of the app setting is 0. I guess the function app is disabled if the value of the disabled field in json is true if not set to false?

Body: This is a known bug found here.


问:
How do I save and retrieve information across invocations of my agent in Dialogflow?
I would like my Actions on Google agent to store and retrieve certain pieces of information across invocations - like a cookie. How do I do this?</p>

答: You could also use a Google Cloud database like BigQuery or Firestore</p>


问:
Saving HTML characters
Using FCKEditor

We are trying to place the clubs character into the database and bring it back out.  The first couple times, the character is saved correctly, but after a couple of edits to the file the html encoding of the clubs character is being lost when saved to the database.

Any ideas?

version 2.3.1

答: Short answer...   updated to newest version and the problem was corrected.</p>

Title: Saving HTML characters


问:
Variable band sizes with ordinal scale
I'd like to create an ordinal axis with varying sizes of rangeRounds or bands. Its fairly straight forward to do this using a linear axis but wondered if it where possible to do this with an ordinal axis. I wondered if I use range and have explicit values, but can't seem to make that work either.
I'm trying to create this kind of thing:

答:
You cannot get variable bands with a band scale (d3.scaleBand()). However, getting variable intervals with a regular ordinal scale (d3.scaleOrdinal()) is quite trivial.

For instance:

```<code>var scale = d3.scaleOrdinal()
  .domain(["Lemons", "Oranges", "Pears", "Apples", "Bananas"])
  .range([10, 40, 100, 150, 180, 290]);
</code>```

The only complicated thing is moving the ticks to the center of the axis... but it's not that complicated:

```<code>axisGroup.selectAll("text").each(function(d, i) {
  d3.select(this).attr("transform", "translate(0," + (scale.range()[i + 1] - scale(d)) / 2 + ")")
})
</code>```

Here is a demo:

var svg = d3.select("svg");
var scale = d3.scaleOrdinal()
  .domain(["Lemons", "Oranges", "Pears", "Apples", "Bananas"])
  .range([10, 40, 100, 150, 180, 290]);

var rects = svg.selectAll(null)
  .data(scale.domain())
  .enter()
  .append("rect")
  .attr("x", 100)
  .attr("width", 200)
  .attr("y", function(d) {
    return scale(d)
  })
  .attr("height", function(d, i) {
    return scale.range()[i + 1] - scale(d)
  })
  .style("fill", "#ccc")
  .style("stroke", "white")
  .style("stroke-width", 2)

var axis = d3.axisLeft(scale);

var gY = svg.append("g")
  .attr("transform", "translate(100,0)")
  .call(axis);

gY.selectAll("text").each(function(d, i) {
  d3.select(this).attr("transform", "translate(0," + (scale.range()[i + 1] - scale(d)) / 2 + ")")
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg height=300></svg></code>```

Title: Variable band sizes with ordinal scale

Body:
You cannot get variable bands with a band scale (d3.scaleBand()). However, getting variable intervals with a regular ordinal scale (d3.scaleOrdinal()) is quite trivial.

For instance:

var scale = d3.scaleOrdinal()
  .domain(["Lemons", "Oranges", "Pears", "Apples", "Bananas"])
  .range([10, 40, 100, 150, 180, 290]);

The only complicated thing is moving the ticks to the center of the axis... but it's not that complicated:

axisGroup.selectAll("text").each(function(d, i) {
  d3.select(this).attr("transform", "translate(0," + (scale.range()[i + 1] - scale(d)) / 2 + ")")
})

Here is a demo:

var svg = d3.select("svg");
var scale = d3.scaleOrdinal()
  .domain(["Lemons", "Oranges", "Pears", "Apples", "Bananas"])
  .range([10, 40, 100, 150, 180, 290]);

var rects = svg.selectAll(null)
  .data(scale.domain())
  .enter()
  .append("rect")
  .attr("x", 100)
  .attr("width", 200)
  .attr("y", function(d) {
    return scale(d)
  })
  .attr("height", function(d, i) {
    return scale.range()[i + 1] - scale(d)
  })
  .style("fill", "#ccc")
  .style("stroke", "white")
  .style("stroke-width", 2)

var axis = d3.axisLeft(scale);

var gY = svg.append("g")
  .attr("transform", "translate(100,0)")
  .call(axis);

gY.selectAll("text").each(function(d, i) {
  d3.select(this).attr("transform", "translate(0," + (scale.range()[i + 1] - scale(d)) / 2 + ")")
})

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg height=300></svg>


问:
Add field in woocommerce email setting tab in dashboard
I wanted to add a field in WooCommerce > Settings > Emails tab. In this section there is a list of email template and on clicking any template you can see this screen.

I want to add another field to this section for every template.

I manage to achieve it but I'm feeling its not a proper way.

My code is as follow:

```<code>add_filter( 'woocommerce_settings_tabs_email', 'emailText' );

function emailText($args) {

        ?>
        <div class="EmailText">
            <label for="EmailText">Email Text</label>
            <textarea id="EmailText" class="widefat" name="email_text"></textarea>
        </div>
        <?php

    }
</code>```

It displays the field but I cannot save anything in it.

答:
The WooCommerce Email Settings tab has a table with all of the available email templates such as 'New Order', 'Canceled Order', 'Failed Order', etc. These are usually defined by extending the WC_Email class. Take a look in /plugins/woocommerce/includes/emails for examples.

As WildProgrammers has pointed out, the 'woocommerce_settings_api_form_fields_{email-id}' can be easily used to add a setting to a specific email class. You can see the definition on the WooCommerce Settings API Code Reference page. It provides us with the array of form fields for the email class.

For this example lets add an additional option to the 'New Order' email template. We can look in the WC_Email_New_Order class constructor (found in class-wc-email-new-order.php) to find/verify the id to replace {email-id} in our hook. In this case the WC_Email_New_Order class id is 'new_order' so to add a setting or form field to the New Order options our hook will look like, add_action( 'woocommerce_settings_api_form_fields_new_order', 'add_my_custom_email_setting',10,1);

Now in the 'add_my_custom_email_setting' function all we need to do is add our new setting to the form_fields array and return it:

```<code>function add_my_custom_email_setting($form_fields){
    $form_fields['my_custom_id']=['title'=>'My Custom Option',
                                  'description'=>'This is a text area we added to the new order email settings page.',
                                  'type'=>'textarea',
                                  'default'=>''
    ];

    return $form_fields;
}
</code>```

Take a look at the 'init_form_fields' function in WC_Email class for examples of how to build the options array.

You asked how to add an option to all of the available templates. To do this we could simply manually define a hook for every email class,
add_action('woocommerce_settings_api_form_fields_new_order','add_my_custom_email_setting');
add_action('woocommerce_settings_api_form_fields_failed_order','add_my_custom_email_setting');
add_action('woocommerce_settings_api_form_fields_processing_order','add_my_custom_email_setting');
...
but if we can get a list of all of the id's then we can do it programatically instead. Lucky for us WooCommerce provides us with the 'woocommerce_email_classes' filter which is called right after WC instantiates all of the email classes. Now all we need is a function that iterates over the array of email classes provided by the 'woocommerce_email_classes' filter, get the class id's, and add a hook to 'woocommerce_settings_api_form_fields_{email-id}' for each id:

```<code>add_action( 'woocommerce_email_classes', 'add_email_custom_setting');

function add_email_custom_setting($email_class_list){
    foreach($email_class_list as $email_class){
        add_action( 'woocommerce_settings_api_form_fields_' . $email_class->id,'add_my_custom_email_setting',10,1);
    }

    return $email_class_list;
}`
</code>```

We can then use this option in our template files with $email->get_option('my_custom_id');.

You might ask why not simply add the option to the form_fields array in add_email_custom_setting?

Body:
I wanted to add a field in WooCommerce > Settings > Emails tab. In this section there is a list of email template and on clicking any template you can see this screen.

I want to add another field to this section for every template.

I manage to achieve it but I'm feeling its not a proper way.

My code is as follow:

add_filter( 'woocommerce_settings_tabs_email', 'emailText' );

function emailText($args) {

        ?>

            Email Text
            <textarea id="EmailText" class="widefat" name="email_text"></textarea>

        <?php

    }

It displays the field but I cannot save anything in it.

Body:
The WooCommerce Email Settings tab has a table with all of the available email templates such as 'New Order', 'Canceled Order', 'Failed Order', etc. These are usually defined by extending the WC_Email class. Take a look in /plugins/woocommerce/includes/emails for examples.

As WildProgrammers has pointed out, the 'woocommerce_settings_api_form_fields_{email-id}' can be easily used to add a setting to a specific email class. You can see the definition on the WooCommerce Settings API Code Reference page. It provides us with the array of form fields for the email class.

For this example lets add an additional option to the 'New Order' email template. We can look in the WC_Email_New_Order class constructor (found in class-wc-email-new-order.php) to find/verify the id to replace {email-id} in our hook. In this case the WC_Email_New_Order class id is 'new_order' so to add a setting or form field to the New Order options our hook will look like, add_action( 'woocommerce_settings_api_form_fields_new_order', 'add_my_custom_email_setting',10,1);

Now in the 'add_my_custom_email_setting' function all we need to do is add our new setting to the form_fields array and return it:

function add_my_custom_email_setting($form_fields){
    $form_fields['my_custom_id']=['title'=>'My Custom Option',
                                  'description'=>'This is a text area we added to the new order email settings page.',
                                  'type'=>'textarea',
                                  'default'=>''
    ];

    return $form_fields;
}

Take a look at the 'init_form_fields' function in WC_Email class for examples of how to build the options array.

You asked how to add an option to all of the available templates. To do this we could simply manually define a hook for every email class,
add_action('woocommerce_settings_api_form_fields_new_order','add_my_custom_email_setting');
add_action('woocommerce_settings_api_form_fields_failed_order','add_my_custom_email_setting');
add_action('woocommerce_settings_api_form_fields_processing_order','add_my_custom_email_setting');
...
but if we can get a list of all of the id's then we can do it programatically instead. Lucky for us WooCommerce provides us with the 'woocommerce_email_classes' filter which is called right after WC instantiates all of the email classes. Now all we need is a function that iterates over the array of email classes provided by the 'woocommerce_email_classes' filter, get the class id's, and add a hook to 'woocommerce_settings_api_form_fields_{email-id}' for each id:

add_action( 'woocommerce_email_classes', 'add_email_custom_setting');

function add_email_custom_setting($email_class_list){
    foreach($email_class_list as $email_class){
        add_action( 'woocommerce_settings_api_form_fields_' . $email_class->id,'add_my_custom_email_setting',10,1);
    }

    return $email_class_list;
}`

We can then use this option in our template files with $email->get_option('my_custom_id');.

You might ask why not simply add the option to the form_fields array in add_email_custom_setting?


问:
Why wont my Auth0 find my callback route in react?
Auth0 redirects to http://localhost:3000/callback#/acccess-token=dxy

I'm getting a blank screen in my react app.

Heres my main app.js

render((
    <HashRouter>

    </HashRouter>
), $('#app')[0]);```
</div>
</div>
</p>

<p>My main contains my routes.js component.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Routes extends Component {
    constructor(props, context) {
        super(props, context);

        this.state = { mainData: this.props.mainData };

        this.handleAuthentication = this.handleAuthentication.bind(this)
    }

    componentWillReceiveProps(newProps) {
        this.setState((previousState) => update(previousState, {
            mainData: { $set: newProps.mainData },
        }));
    }

    handleAuthentication(nextState, replace) {
        if (/access_token|id_token|error/.test(nextState.location.hash)) {
            this.props.auth.handleAuthentication();
        }
    }

    render() {
        return (
            <div>

                <Switch>

                  <Route path='/callback' render={props => {

                    this.handleAuthentication(props);

                    return <Callback {...props} />
                }} />

                    <Route exact path='/' render={props => (
                        <Dashboard changeAppBar={this.props.changeAppBar} userProfile={this.state.mainData.userProfile} windowHeight={this.props.wh} windowWidth={this.props.ww} />)}
                    />

                    <Route path='/settings' render={props => (
                        <Settings changeAppBar={this.props.changeAppBar} userProfile={this.state.mainData.userProfile} />)}
                    />

                </Switch>

            </div>
        );
    }
}

export default Routes;</code>```

Heres my init of auth0

    this.auth0 = new auth0.WebAuth({
      clientID: 'oiEjW4Mf6Ju4BvRfHeuObQnMbghKs38g',
      domain: 'cryptok1ng.auth0.com',
      responseType: 'token id_token',
      redirectUri: 'http://localhost:3000/callback'
    })```

Everything works fine until I get redirected from auth0 back to /callback. Simply doesn't find a screen /route and renders nothing.

Screenshot of the console. /callback breakpoint is never hit.

Thanks for any help I've been going through the docs and answers to no avail.

答:
I am assuming you In Auth0 front end client configuration> you have added the callback URi as http://localhost:3000/callback and saved it.

And also in your callback.html file you added some tags to show up something once the token is authenticated properly.

If everything is fine and you still get blank error. Please post your console screenshot to have a look.

Body:
Auth0 redirects to http://localhost:3000/callback#/acccess-token=dxy

I'm getting a blank screen in my react app.

Heres my main app.js

render((
    <HashRouter>

    </HashRouter>
), $('#app')[0]);

My main contains my routes.js component.

class Routes extends Component {
    constructor(props, context) {
        super(props, context);

        this.state = { mainData: this.props.mainData };

        this.handleAuthentication = this.handleAuthentication.bind(this)
    }

    componentWillReceiveProps(newProps) {
        this.setState((previousState) => update(previousState, {
            mainData: { $set: newProps.mainData },
        }));
    }

    handleAuthentication(nextState, replace) {
        if (/access_token|id_token|error/.test(nextState.location.hash)) {
            this.props.auth.handleAuthentication();
        }
    }

    render() {
        return (

                <Switch>

                  <Route path='/callback' render={props => {

                    this.handleAuthentication(props);

                    return <Callback {...props} />
                }} />

                    <Route exact path='/' render={props => (
                        <Dashboard changeAppBar={this.props.changeAppBar} userProfile={this.state.mainData.userProfile} windowHeight={this.props.wh} windowWidth={this.props.ww} />)}
                    />

                    <Route path='/settings' render={props => (
                        <Settings changeAppBar={this.props.changeAppBar} userProfile={this.state.mainData.userProfile} />)}
                    />

                </Switch>

        );
    }
}

export default Routes;

Heres my init of auth0

    this.auth0 = new auth0.WebAuth({
      clientID: 'oiEjW4Mf6Ju4BvRfHeuObQnMbghKs38g',
      domain: 'cryptok1ng.auth0.com',
      responseType: 'token id_token',
      redirectUri: 'http://localhost:3000/callback'
    })

Everything works fine until I get redirected from auth0 back to /callback. Simply doesn't find a screen /route and renders nothing.

Screenshot of the console. /callback breakpoint is never hit.

Thanks for any help I've been going through the docs and answers to no avail.


问:
Create a "temporary" table in spark-SQL, not spark-scala?
I have loaded a table from an input file.

```<code>CREATE TABLE MyTable (
    ID INT,
    VALUE FLOAT,
    RATE  INT
...

LOAD DATA LOCAL INPATH 'MYPATH' INTO TABLE MyTable;
</code>```

Now I'd like to create a new based on this one

```<code>DerivedTable =
    SELECT ID, VALUE*RATE AS Total
    FROM MyTable
    WHERE VALUE IS NOT NULL;
</code>```

Then I'm going to use this table as a source for other tables and for outputs.

What is a correct Sql (or Hive) way to create this "temporary" table? This should work in spark-sql?

PS: I know how to do that in spark-shell. But that is not what I'm looking for.

答:
You can:</p>

```<code>CREATE TEMPORARY VIEW DerivedTable AS (
   SELECT ID, VALUE*RATE AS Total
   FROM MyTable
   WHERE VALUE IS NOT NULL);
</code>```

Body:
I have loaded a table from an input file.

CREATE TABLE MyTable (
    ID INT,
    VALUE FLOAT,
    RATE  INT
...

LOAD DATA LOCAL INPATH 'MYPATH' INTO TABLE MyTable;

Now I'd like to create a new based on this one

DerivedTable =
    SELECT ID, VALUE*RATE AS Total
    FROM MyTable
    WHERE VALUE IS NOT NULL;

Then I'm going to use this table as a source for other tables and for outputs.

What is a correct Sql (or Hive) way to create this "temporary" table? This should work in spark-sql?

PS: I know how to do that in spark-shell. But that is not what I'm looking for.

Body:
You can:

CREATE TEMPORARY VIEW DerivedTable AS (
   SELECT ID, VALUE*RATE AS Total
   FROM MyTable
   WHERE VALUE IS NOT NULL);


问:
How do I stop AI movement with OnTriggerEnter2D in Unity?
I'm creating a basic AI script for my enemies in Unity and I have most of it working the way I want it to. The way I have my enemies set up they contain 2 colliders, a polygon collider that destroys the player when touched, and an empty game object that's a child of the enemy that is a circle collider that acts as a trigger. There's a game object that's tagged Straight Road and when the circle collider comes in contact with it, it should run a function called StopMovement(); that sets the enemies movement to 0. I used to Debug.Log(); to check to see if the collider recognizes that it's touching Straight Road and it doesn't. This is my code below. I'm hoping someone has a suggestion.

```<code>public class DogAI : GenericController {

    public Transform target;
    public float chaseRange;
    public float maxDistance;

    private Vector3 targetDirection;
    private float targetDistance;

    // Use this for initialization
    void Start()
    {
        base.Start();
    }

    // Update is called once per frame
    void Update()
    {
        base.Update();
        if (target.transform != null)
        {
            targetDirection = target.transform.position - transform.position;
            targetDirection = targetDirection.normalized;
            targetDistance = Vector3.Distance(target.position, transform.position);

            if (targetDistance <= chaseRange)
            {
               SetMovement(targetDirection);
            }

            Vector3 enemyScreenPosition = Camera.main.WorldToScreenPoint(transform.position);

            if (targetDistance > maxDistance)
            {
                Destroy(gameObject);
            }
        }
    }

    void StopMovement()
    {
        SetMovement(new Vector2(0,0));
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Straight Road"))
        {
            Debug.Log("Stop! There's a road!");//This never shows up in the log?
            StopMovement();
        }
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            DestroyObject(other.gameObject);
        }
    }
</code>```

Generic Controller script below containing the SetMovement() function.

```<code>public abstract class GenericController : MonoBehaviour
{
    public float movementSpeed = 20;
    float animationSpeed = 1;

    protected Rigidbody2D rigidbody;
    protected Animator animator;

    Vector2 movementVector;
    float currentSpeed;

    protected bool needAnimator = true;

    // Use this for initialization
    protected void Start()
    {
        rigidbody = GetComponent<Rigidbody2D>();

        if (needAnimator)
        {
            animator = GetComponent<Animator>();
            animator.speed = animationSpeed;
        }
    }

    protected void FixedUpdate()
    {
        rigidbody.velocity = movementVector;
        currentSpeed = rigidbody.velocity.magnitude;

        if (needAnimator)
            animator.SetFloat("Speed", currentSpeed);
    }

    public void SetMovement(Vector2 input)
    {
        movementVector = input * movementSpeed;
    }

    public void SetMovement(int x, int y)
    {
        SetMovement(new Vector2(x, y));
    }
</code>```

答:
From the documentation:

MonoBehaviour.OnTriggerEnter2D(Collider2D)

Sent when another object enters a trigger collider attached to this object (2D physics only).

The keyword here is enters. In other words, a trigger is for when something goes inside the area of the collider, like a player entering a region of the map, where the region is a trigger collider. If you want something to happen when a collider collides with the road, i.e. when your CircleCollider comes in contact with the road, then you want the collider to not be a trigger, and you want the functionality to be inside OnCollisionEnter2D.

Body:
I'm creating a basic AI script for my enemies in Unity and I have most of it working the way I want it to. The way I have my enemies set up they contain 2 colliders, a polygon collider that destroys the player when touched, and an empty game object that's a child of the enemy that is a circle collider that acts as a trigger. There's a game object that's tagged Straight Road and when the circle collider comes in contact with it, it should run a function called StopMovement(); that sets the enemies movement to 0. I used to Debug.Log(); to check to see if the collider recognizes that it's touching Straight Road and it doesn't. This is my code below. I'm hoping someone has a suggestion.

public class DogAI : GenericController {

    public Transform target;
    public float chaseRange;
    public float maxDistance;

    private Vector3 targetDirection;
    private float targetDistance;

    // Use this for initialization
    void Start()
    {
        base.Start();
    }

    // Update is called once per frame
    void Update()
    {
        base.Update();
        if (target.transform != null)
        {
            targetDirection = target.transform.position - transform.position;
            targetDirection = targetDirection.normalized;
            targetDistance = Vector3.Distance(target.position, transform.position);

            if (targetDistance <= chaseRange)
            {
               SetMovement(targetDirection);
            }

            Vector3 enemyScreenPosition = Camera.main.WorldToScreenPoint(transform.position);

            if (targetDistance > maxDistance)
            {
                Destroy(gameObject);
            }
        }
    }

    void StopMovement()
    {
        SetMovement(new Vector2(0,0));
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Straight Road"))
        {
            Debug.Log("Stop! There's a road!");//This never shows up in the log?
            StopMovement();
        }
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            DestroyObject(other.gameObject);
        }
    }

Generic Controller script below containing the SetMovement() function.

public abstract class GenericController : MonoBehaviour
{
    public float movementSpeed = 20;
    float animationSpeed = 1;

    protected Rigidbody2D rigidbody;
    protected Animator animator;

    Vector2 movementVector;
    float currentSpeed;

    protected bool needAnimator = true;

    // Use this for initialization
    protected void Start()
    {
        rigidbody = GetComponent<Rigidbody2D>();

        if (needAnimator)
        {
            animator = GetComponent<Animator>();
            animator.speed = animationSpeed;
        }
    }

    protected void FixedUpdate()
    {
        rigidbody.velocity = movementVector;
        currentSpeed = rigidbody.velocity.magnitude;

        if (needAnimator)
            animator.SetFloat("Speed", currentSpeed);
    }

    public void SetMovement(Vector2 input)
    {
        movementVector = input * movementSpeed;
    }

    public void SetMovement(int x, int y)
    {
        SetMovement(new Vector2(x, y));
    }