问:
How the least square method work with a given function
I have some data and I have used below numpy function to make the fitting. The fitting was fine but I need some explanation how it works.  What does p[1],p[2],p[0] stands for.It will be nice if I get the mathematical expression for that. what actually the least square is doing?</p>

```<code>fitfuncvx = lambda p, x: p[2]+p[0]*np.exp(-x/p[1])
errfuncvx = lambda p, x, y: y - fitfuncvx(p, x)
sig_fit=np.where(Sig<12)
pinit = [1, 100,0.1]
pfinal, success = optimize.leastsq(errfuncvx, pinit[:], args=(Sig[sig_fit], vx[sig_fit]))
</code>```

答:
The values p[0], p[1], and p[2] are coefficients being solved for in the least squares fit.

The least squares fit is calculating the values of the coefficients that minimize the sum of squared errors between the dependent variable data values and those predicted by the fitted function.

It's probably using a conjugate gradient iterative method to calculate the coefficients given a starting guess.

I don't think you should have a p[2].

Your fit function should be:

```<code>y = c0*exp(-c1*x)
</code>```

If I take the natural logarithm of both sides:

```<code>ln(y) = ln(c0) - c1*x = z
</code>```

if you do that transformation you're doing a simple linear regression on a new function z = z(x).

That's an easy problem.  There are formulas for the coefficients for the case of one independent variable.

Solve for the coefficients using your transformed data and substitute back into the original equation.

Body:
I have some data and I have used below numpy function to make the fitting. The fitting was fine but I need some explanation how it works.  What does p[1],p[2],p[0] stands for.It will be nice if I get the mathematical expression for that. what actually the least square is doing?

fitfuncvx = lambda p, x: p[2]+p[0]*np.exp(-x/p[1])
errfuncvx = lambda p, x, y: y - fitfuncvx(p, x)
sig_fit=np.where(Sig<12)
pinit = [1, 100,0.1]
pfinal, success = optimize.leastsq(errfuncvx, pinit[:], args=(Sig[sig_fit], vx[sig_fit]))

Body:
The values p[0], p[1], and p[2] are coefficients being solved for in the least squares fit.

The least squares fit is calculating the values of the coefficients that minimize the sum of squared errors between the dependent variable data values and those predicted by the fitted function.

It's probably using a conjugate gradient iterative method to calculate the coefficients given a starting guess.

I don't think you should have a p[2].

Your fit function should be:

y = c0*exp(-c1*x)

If I take the natural logarithm of both sides:

ln(y) = ln(c0) - c1*x = z

if you do that transformation you're doing a simple linear regression on a new function z = z(x).

That's an easy problem.  There are formulas for the coefficients for the case of one independent variable.

Solve for the coefficients using your transformed data and substitute back into the original equation.


来源: stackexchange

问:
Reshaping Pandas Data Frame by Index with Duplicate Indexes
I have a data frame similar to this:

```<code>questions = ['What color?', 'What day?', 'How cold?', 'What color?', 'What color?']
answers = ['red', 'tuesday', '45', 'blue', 'red']
ids = [0, 1, 2, 3, 0]
df = pd.DataFrame({'id': [0, 1, 2, 0, 0], 'questions': questions, 'answers': answers})

 >>> id questions    answers
      0  What color? red
      1  What day?   tuesday
      2  How cold?   45
      0 What color?  blue
      0 What color?  red
</code>```

I want this:

```<code>     How cold? What color?  What day?
id
0       None    red          None
2       None    None         tuesday
3       45      None         None
4       None    blue         None
0       None    red          None
</code>```

I have tried:

```<code>df.pivot(values='answers', index='id', columns='questions')
</code>```

However, pivot always results in an error due to duplicates in the index.

答:
If duplicates you need:</p>

```<code>df['g'] = df.groupby('id').cumcount()
df = df.set_index(['id','g', 'questions']).unstack().reset_index(level=1, drop=True)
print (df)
questions How cold? What color? What day?
id
0              None         red      None
0              None        blue      None
0              None         red      None
1              None        None   tuesday
2                45        None      None
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data frame similar to this:

questions = ['What color?', 'What day?', 'How cold?', 'What color?', 'What color?']
answers = ['red', 'tuesday', '45', 'blue', 'red']
ids = [0, 1, 2, 3, 0]
df = pd.DataFrame({'id': [0, 1, 2, 0, 0], 'questions': questions, 'answers': answers})

 >>> id questions    answers
      0  What color? red
      1  What day?   tuesday
      2  How cold?   45
      0 What color?  blue
      0 What color?  red

I want this:

     How cold? What color?  What day?
id
0       None    red          None
2       None    None         tuesday
3       45      None         None
4       None    blue         None
0       None    red          None

I have tried:

df.pivot(values='answers', index='id', columns='questions')

However, pivot always results in an error due to duplicates in the index.

Body:
If duplicates you need:

df['g'] = df.groupby('id').cumcount()
df = df.set_index(['id','g', 'questions']).unstack().reset_index(level=1, drop=True)
print (df)
questions How cold? What color? What day?
id
0              None         red      None
0              None        blue      None
0              None         red      None
1              None        None   tuesday
2                45        None      None


问:
Erase an element from a map then put it back
Suppose I have a backtracking algorithm where I need to remove an element from a map, do something, then put it back. I am not sure if there is a good way to do it:

```<code>func(std::<K, V> map &dict) {
    for (auto i : dict) {
       remove i from dict;
       func(dict);
       put i back to dict;
    }
}
</code>```

I know there are ways to delete an element from map in here but I am not sure if there are ways to achieve what I described above. I am aware that I can create a new dict in for loop and pass it in func but I am wondering if it can be done using the same dict.

答:
What you ask is definitely possible.  Here is one way to do it while trying to keep things simple and efficient:

```<code>void func(std::map<K, V> &dict) {
    for (auto i = dict.cbegin(); i != dict.cend(); ) {
       auto old = *i;
       i = dict.erase(i);   // i now points to the next element (or dict.end())
       some_other_func(dict);
       dict.insert(i, old); // i is used a hint where to re-insert the old value
    }
}
</code>```

By calling std::map::erase with an iterator argument and std::map::insert with a hint, the complexity of each iteration through this loop is amortized constant.  Note that I assumed your calling of func in line 5 was actually supposed to be some_other_func, because calling func recursively would invalidate the iterator you carefully set in line 4.

However, this is not the most efficient way to do this sort of processing (@rakurai has a suggestion that should be considered).

Body:
Suppose I have a backtracking algorithm where I need to remove an element from a map, do something, then put it back. I am not sure if there is a good way to do it:

func(std::<K, V> map &dict) {
    for (auto i : dict) {
       remove i from dict;
       func(dict);
       put i back to dict;
    }
}

I know there are ways to delete an element from map in here but I am not sure if there are ways to achieve what I described above. I am aware that I can create a new dict in for loop and pass it in func but I am wondering if it can be done using the same dict.

Body:
What you ask is definitely possible.  Here is one way to do it while trying to keep things simple and efficient:

void func(std::map<K, V> &dict) {
    for (auto i = dict.cbegin(); i != dict.cend(); ) {
       auto old = *i;
       i = dict.erase(i);   // i now points to the next element (or dict.end())
       some_other_func(dict);
       dict.insert(i, old); // i is used a hint where to re-insert the old value
    }
}

By calling std::map::erase with an iterator argument and std::map::insert with a hint, the complexity of each iteration through this loop is amortized constant.  Note that I assumed your calling of func in line 5 was actually supposed to be some_other_func, because calling func recursively would invalidate the iterator you carefully set in line 4.

However, this is not the most efficient way to do this sort of processing (@rakurai has a suggestion that should be considered).


问:
Reduce and assign using Stream api for multiple variables
I need to do following in lambda but unable to think of way where single stream and reducing(s) can help :(

I have Employee ArrayList where name member variable can be duplicate across object in list. I need to create map where key is employee name and value is object where we have sum of cost1 and cost2 for that employee.

Employee class has -> String name, Integer cost1, Integer cost2

Output class has -> Integer cost1, Integer cost2

```<code>List <Employee> employeeList = new ArrayList<>();
// data population in inputMap
Map<String, Output> outputMap = new HashMap<>();
for (Employee emp : employeeList)
{
    Output op = outputMap.get(emp.getName());
    if(op == null){
      Output newOp = new Output ();
      newOp.setCost1(emp.getCost1())
      newOp.setCost2(emp.getCost2())
      newOp.put(emp.getName(), newOp);
    }else{
       int cost1 = op.getCost1() + emp.getCost1();
       int cost2 = op.getCost2() + emp.getCost2();
       op.setCost1(cost1);
       op.setCost2(cost2);
       newOp.put(emp.getName(), op);
    }
}
</code>```

答:
I assume you have a structure sort of like this:

```<code>static class Output {
    private final int cost1;

    private final int cost2;

    public Output(int cost1, int cost2) {
        this.cost1 = cost1;
        this.cost2 = cost2;
    }

    @Override
    public String toString() {
        return "cost1 = " + cost1 + " cost2 = " + cost2;
    }
    // ... getter
}

static class Employee {
    private final String name;

    private final int cost1;

    private final int cost2;

    public Employee(String name, int cost1, int cost2) {
        this.name = name;
        this.cost1 = cost1;
        this.cost2 = cost2;
    }
 // ...getters
}
</code>```

Then the solution would be to first group by Employee::getName and reduce to Output via Collectors.reducing

```<code>  Map<String, Output> map = Arrays.asList(
                       new Employee("e", 12, 12),
                       new Employee("f", 13, 13),
                       new Employee("e", 11, 11))
            .stream()
            .collect(Collectors.groupingBy(Employee::getName,
                    Collectors.reducing(
                            new Output(0, 0),
                            emp -> new Output(emp.getCost1(), emp.getCost2()),
                            (left, right) -> new Output(left.getCost1() + right.getCost1(), left.getCost2() + right.getCost2()))));
    System.out.println(map); // {e=cost1 = 23 cost2 = 23, f=cost1 = 13 cost2 = 13}
</code>```

Body:
I need to do following in lambda but unable to think of way where single stream and reducing(s) can help :(

I have Employee ArrayList where name member variable can be duplicate across object in list. I need to create map where key is employee name and value is object where we have sum of cost1 and cost2 for that employee.

Employee class has -> String name, Integer cost1, Integer cost2

Output class has -> Integer cost1, Integer cost2

List <Employee> employeeList = new ArrayList<>();
// data population in inputMap
Map<String, Output> outputMap = new HashMap<>();
for (Employee emp : employeeList)
{
    Output op = outputMap.get(emp.getName());
    if(op == null){
      Output newOp = new Output ();
      newOp.setCost1(emp.getCost1())
      newOp.setCost2(emp.getCost2())
      newOp.put(emp.getName(), newOp);
    }else{
       int cost1 = op.getCost1() + emp.getCost1();
       int cost2 = op.getCost2() + emp.getCost2();
       op.setCost1(cost1);
       op.setCost2(cost2);
       newOp.put(emp.getName(), op);
    }
}

Body:
I assume you have a structure sort of like this:

static class Output {
    private final int cost1;

    private final int cost2;

    public Output(int cost1, int cost2) {
        this.cost1 = cost1;
        this.cost2 = cost2;
    }

    @Override
    public String toString() {
        return "cost1 = " + cost1 + " cost2 = " + cost2;
    }
    // ... getter
}

static class Employee {
    private final String name;

    private final int cost1;

    private final int cost2;

    public Employee(String name, int cost1, int cost2) {
        this.name = name;
        this.cost1 = cost1;
        this.cost2 = cost2;
    }
 // ...getters
}

Then the solution would be to first group by Employee::getName and reduce to Output via Collectors.reducing

  Map<String, Output> map = Arrays.asList(
                       new Employee("e", 12, 12),
                       new Employee("f", 13, 13),
                       new Employee("e", 11, 11))
            .stream()
            .collect(Collectors.groupingBy(Employee::getName,
                    Collectors.reducing(
                            new Output(0, 0),
                            emp -> new Output(emp.getCost1(), emp.getCost2()),
                            (left, right) -> new Output(left.getCost1() + right.getCost1(), left.getCost2() + right.getCost2()))));
    System.out.println(map); // {e=cost1 = 23 cost2 = 23, f=cost1 = 13 cost2 = 13}


问:
How to get all elements on same row html css
My screen looks like this:

I want everything to be on the same row. How do I fix this? My html code:

```<code>  .form-box
      %h3 Restrictions
      %legend Restricted Locations
      %fieldset.restrictions-row
        .restrictions-row.restrictions-label
          = label_tag :us_states, "US States"
        .restrictions-row.restrictions-select
          = collection_select :restriction, :category, Restriction.where(category: "US State"), :id, :name, prompt: true
          = hidden_field_tag :product_id, @wine.product.id
          = hidden_field_tag :restriction_category, "US State"
        .restrictions-row
          = button_tag "Add", class: 'btn btn-primary'
        %table.table.table-hover.table-condensed.story-list.restrictions-row
          %th{ style: 'padding: 3% 17%' } State
          %th{ style: 'padding: 3% 17%'} Remove
</code>```

my css:

```<code>  .restrictions-label {
    width: 10%;
    font-weight: bold;
  }
  .restrictions-select {
    width: 10%;
  }
  .restrictions-row {
    display: inline-block;
  }
</code>```

What is taking precedence? why isn't border-line working when I apply it to the divs?

答:
```<code>fieldset.restrictions-row > .restrictions-row{
  display: inline-block;
  width: auto;
}
</code>```

this is the code works like you mentioned at usual cases.

In case you fail to accomplish by code above you can use float. Then by using after you can clear float

```<code>fieldset.restrictions-row > .restrictions-row{
  float:left;
}
fieldset.restrictions-row::after{
  content:"";
  display:block;
  clear: both;
}
</code>```

Body:
My screen looks like this:

I want everything to be on the same row. How do I fix this? My html code:

  .form-box
      %h3 Restrictions
      %legend Restricted Locations
      %fieldset.restrictions-row
        .restrictions-row.restrictions-label
          = label_tag :us_states, "US States"
        .restrictions-row.restrictions-select
          = collection_select :restriction, :category, Restriction.where(category: "US State"), :id, :name, prompt: true
          = hidden_field_tag :product_id, @wine.product.id
          = hidden_field_tag :restriction_category, "US State"
        .restrictions-row
          = button_tag "Add", class: 'btn btn-primary'
        %table.table.table-hover.table-condensed.story-list.restrictions-row
          %th{ style: 'padding: 3% 17%' } State
          %th{ style: 'padding: 3% 17%'} Remove

my css:

  .restrictions-label {
    width: 10%;
    font-weight: bold;
  }
  .restrictions-select {
    width: 10%;
  }
  .restrictions-row {
    display: inline-block;
  }

What is taking precedence? why isn't border-line working when I apply it to the divs?

Body:
fieldset.restrictions-row > .restrictions-row{
  display: inline-block;
  width: auto;
}

this is the code works like you mentioned at usual cases.

In case you fail to accomplish by code above you can use float. Then by using after you can clear float

fieldset.restrictions-row > .restrictions-row{
  float:left;
}
fieldset.restrictions-row::after{
  content:"";
  display:block;
  clear: both;
}


问:
Drag and Drop control from toolbox not working
In windows form application, i created a usercontrol page. Here, I need to add a myowncontrol from tool box.

I just added myowncontrol in the tool box. by the way of browsing dll and placed it in tool box.

Here, when i drag and drop any one of default control, which  can easily dragged and placed in the usercontrol page. But when i try to drag and drop  myowncontrol into  usercontrol page , its not working.

Can't able to drag and drop.
(i mean i can pick the control from the tool box but i can't able to place it where i want)

what is the problem in my area?

答:
I'll admit that this does not directly answer your question, but I am wondering if you have tried to programmatically add the control to a Form?  You would need to add a reference to the DLL that contains the UserControl and then do something similar to below in your source code.

```<code>var myCtrl = new MyControl(); //your UserControl class here
myCtrl.Location = new Point(25,25); //give it a location
this.Controls.Add(myCtrl); //add it
</code>```

Also another thought... Are you sure that it's not really being added and it's just not visible?  For a Form or UserControl in the Visual Studio Properties Window there is a drop-down at the top which contains all the controls that have been added.

Body:
I'll admit that this does not directly answer your question, but I am wondering if you have tried to programmatically add the control to a Form?  You would need to add a reference to the DLL that contains the UserControl and then do something similar to below in your source code.

var myCtrl = new MyControl(); //your UserControl class here
myCtrl.Location = new Point(25,25); //give it a location
this.Controls.Add(myCtrl); //add it

Also another thought... Are you sure that it's not really being added and it's just not visible?  For a Form or UserControl in the Visual Studio Properties Window there is a drop-down at the top which contains all the controls that have been added.


问:
Class from PHAR not found
I want to use the PHAR from nette-tester V1.7.1 ... and build a simple script that runs a test, but i fail at a very basic level.

The class Tester\Runner\CliTester is correct and available within the PHAR, but is not found.

Composer is no option and including all files without the phar would we the worst option.

Input:

```<code><?php
include_once 'tester.phar';
$tester = new Tester\Runner\CliTester;
die($tester->run());
</code>```

Output:

```<code>Fatal error: Class 'Tester\Runner\CliTester' not found in
C:\webdev\testrunner.php on line 14 Call Stack: 0.0000 136168 1. {main}()
C:\webdev\testrunner.php:0
</code>```

答:
If you want to simply run CliTester you just need to run php tester.php in your command line.

If you include tester.phar into your application some files are not loaded. Look at stub.php in tester.phar.

Title: Class from PHAR not found

Body:
I want to use the PHAR from nette-tester V1.7.1 ... and build a simple script that runs a test, but i fail at a very basic level.

The class Tester\Runner\CliTester is correct and available within the PHAR, but is not found.

Composer is no option and including all files without the phar would we the worst option.

Input:

<?php
include_once 'tester.phar';
$tester = new Tester\Runner\CliTester;
die($tester->run());

Output:

Fatal error: Class 'Tester\Runner\CliTester' not found in
C:\webdev\testrunner.php on line 14 Call Stack: 0.0000 136168 1. {main}()
C:\webdev\testrunner.php:0


问:
Usage of _path gives a "No route matches.." error
I am following a tutorial of Rails and I have a few pages that I am adding some tests for.

I am trying to use help_path instead of :help in my pages_controller_test :

```<code>test "should get help" do
  get help_path
  assert_response :success
  assert_select "title", "Help | #{@base_title}"
end
</code>```

I added this line in my routes.rb file :

```<code> get  '/help',    to: 'pages#help'
</code>```

But I get this error :

1) Error:
  PagesControllerTest#test_should_get_help:
  ActionController::UrlGenerationError: No route matches {:action=>"/help", :controller=>"pages"}
      test/controllers/pages_controller_test.rb:62:in `block in '

I have tried a few solutions but none of them solved my issue.
I've also tried using this line instead :

```<code>match '/home' => 'main_pages#home', :as => :home
</code>```

But it didn't work either.

My rails version is : 4.2.4
My Ruby version is : ruby 2.1.9p490 (2016-03-30 revision 54437) [x86_64-linux-gnu]

Output of $rake routes :

```<code> Prefix Verb URI Pattern          Controller#Action
 root GET  /                    pages#home
 help GET  /help(.:format)      pages#help
 courses GET  /courses(.:format)   pages#courses
 programs GET  /programs(.:format)  pages#programs
 schools GET  /schools(.:format)   pages#schools
 dashboard GET  /dashboard(.:format) pages#dashboard
 profile GET  /profile(.:format)   pages#profile
 account GET  /account(.:format)   pages#account
 signout GET  /signout(.:format)   pages#signout
</code>```

EDIT :
I can use help_path .. etc in my html code without any issue, but in the test it gives that error.
Thank you :)

答:
I've ran your tests using the repo, Rails 4.2.4, Minitest 5.10.2 and the only one test that doesn't pass is the one using get help_path. I put only the 3 tests in order to shorten the post:

```<code>PagesControllerTest#test_should_get_help_using_"get_:help" = 0.39 s = .
PagesControllerTest#test_should_get_help_using_"get_help_path" = 0.00 s = E
PagesControllerTest#test_should_get_help_using_"get_'help'" = 0.01 s = .

Finished in 0.405330s, 7.4014 runs/s, 9.8685 assertions/s.

  1) Error:
PagesControllerTest#test_should_get_help_using_"get_help_path":
ActionController::UrlGenerationError: No route matches {:action=>"/help", :controller=>"pages"}
    test/controllers/pages_controller_test.rb:70:in `block in <class:PagesControllerTest>'

3 runs, 4 assertions, 0 failures, 1 errors, 0 skips
</code>```

What I did:

```<code>$ rm -rf Gemfile.lock (because of a json -v 1.8.1 gem error)
$ bundle
$ rake db:migrate
$ rake db:migrate RAILS_ENV=test
$ rake test test/controllers/pages_controller_test.rb -v
</code>```

What you can use to make the test work with help_path as the route to test specifying the controller and action is to use:

assert_routing asserts that the routing of the given path was handled correctly and
  that the parsed options (given in the expected_options hash) match
  path. Basically, it asserts that Rails recognizes the route given by
  expected_options.

Or:

assert_recognizes asserts that path and options match both ways; in other words, it
  verifies that path generates options and then that options generates
  path. This essentially combines assert_recognizes and assert_generates
  into one step.

Like:

```<code>test "should get help using assert_recognizes and help_path" do
  assert_recognizes({controller: 'pages', action: 'help'}, help_path)
  assert_response :success
end

test "should get help using assert_routing and help_path" do
  assert_routing help_path, controller: 'pages', action: 'help'
  assert_response :success
end
</code>```

Body:
I am following a tutorial of Rails and I have a few pages that I am adding some tests for.

I am trying to use help_path instead of :help in my pages_controller_test :

test "should get help" do
  get help_path
  assert_response :success
  assert_select "title", "Help | #{@base_title}"
end

I added this line in my routes.rb file :

 get  '/help',    to: 'pages#help'

But I get this error :

1) Error:
  PagesControllerTest#test_should_get_help:
  ActionController::UrlGenerationError: No route matches {:action=>"/help", :controller=>"pages"}
      test/controllers/pages_controller_test.rb:62:in `block in '

I have tried a few solutions but none of them solved my issue.
I've also tried using this line instead :

match '/home' => 'main_pages#home', :as => :home

But it didn't work either.

My rails version is : 4.2.4
My Ruby version is : ruby 2.1.9p490 (2016-03-30 revision 54437) [x86_64-linux-gnu]

Output of $rake routes :

 Prefix Verb URI Pattern          Controller#Action
 root GET  /                    pages#home
 help GET  /help(.:format)      pages#help
 courses GET  /courses(.:format)   pages#courses
 programs GET  /programs(.:format)  pages#programs
 schools GET  /schools(.:format)   pages#schools
 dashboard GET  /dashboard(.:format) pages#dashboard
 profile GET  /profile(.:format)   pages#profile
 account GET  /account(.:format)   pages#account
 signout GET  /signout(.:format)   pages#signout

EDIT :
I can use help_path .. etc in my html code without any issue, but in the test it gives that error.
Thank you :)

Body:
I've ran your tests using the repo, Rails 4.2.4, Minitest 5.10.2 and the only one test that doesn't pass is the one using get help_path. I put only the 3 tests in order to shorten the post:

PagesControllerTest#test_should_get_help_using_"get_:help" = 0.39 s = .
PagesControllerTest#test_should_get_help_using_"get_help_path" = 0.00 s = E
PagesControllerTest#test_should_get_help_using_"get_'help'" = 0.01 s = .

Finished in 0.405330s, 7.4014 runs/s, 9.8685 assertions/s.

  1) Error:
PagesControllerTest#test_should_get_help_using_"get_help_path":
ActionController::UrlGenerationError: No route matches {:action=>"/help", :controller=>"pages"}
    test/controllers/pages_controller_test.rb:70:in `block in <class:PagesControllerTest>'

3 runs, 4 assertions, 0 failures, 1 errors, 0 skips

What I did:

$ rm -rf Gemfile.lock (because of a json -v 1.8.1 gem error)
$ bundle
$ rake db:migrate
$ rake db:migrate RAILS_ENV=test
$ rake test test/controllers/pages_controller_test.rb -v

What you can use to make the test work with help_path as the route to test specifying the controller and action is to use:

assert_routing asserts that the routing of the given path was handled correctly and
  that the parsed options (given in the expected_options hash) match
  path. Basically, it asserts that Rails recognizes the route given by
  expected_options.

Or:

assert_recognizes asserts that path and options match both ways; in other words, it
  verifies that path generates options and then that options generates
  path. This essentially combines assert_recognizes and assert_generates
  into one step.

Like:

test "should get help using assert_recognizes and help_path" do
  assert_recognizes({controller: 'pages', action: 'help'}, help_path)
  assert_response :success
end

test "should get help using assert_routing and help_path" do
  assert_routing help_path, controller: 'pages', action: 'help'
  assert_response :success
end


问:
ComboBox in javaFX
I have some problem with comboBox in javaFX. I design my combobox in scene builder:

```<code><ComboBox fx:id="categoryComboBox" prefHeight="21.0" prefWidth="405.0" GridPane.columnIndex="1" GridPane.rowIndex="2">
      <items>
        <FXCollections fx:factory="observableArrayList">
          <String fx:value="Woodenware" />
          <String fx:value="Stoneware" />
          <String fx:value="Metalware" />
          <String fx:value="Fabric" />
        </FXCollections>
      </items>
    </ComboBox>
</code>```

This is my controller class:

```<code> @FXML
private ComboBox<?> categoryComboBox;
public void setCategoryComboBox(ComboBox<String> categoryComboBox) {
    this.categoryComboBox = categoryComboBox;
}

public ComboBox<String> getCategoryComboBox() {
    return categoryComboBox;
}

@FXML
private void comboBoxSelection(ActionEvent event) {
   categoryComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
         public void changed(ObservableValue<? extends String> ov,
             String old_val, String new_val) {
                String categoryStr =  getCategoryComboBox().getValue().toString(); //Don't know what to put here
     }
</code>```

When I try to get selected item from comboBox:

```<code>  int category = panel.getCategoryComboBox().getValue()
</code>```

It gives me an error message "incompatible data tyep and I have no idea why. I am new to scene builder and netbeans so please tell me where am I did wrongly.

Thanks in advance.

答:
The error is in this line:

```<code>private ComboBox<?> categoryComboBox;
</code>```

You can't cast from ? to int. So change this line to:

```<code>private ComboBox<Integer> categoryComboBox;
</code>```

Then you have to change the methode:

```<code>public ComboBox<String> getCategoryComboBox() {...}
</code>```

to

```<code> public ComboBox<Integer> getCategoryComboBox() {...}
</code>```

Title: ComboBox in javaFX

Body:
I have some problem with comboBox in javaFX. I design my combobox in scene builder:

<ComboBox fx:id="categoryComboBox" prefHeight="21.0" prefWidth="405.0" GridPane.columnIndex="1" GridPane.rowIndex="2">
      <items>
        <FXCollections fx:factory="observableArrayList">
          <String fx:value="Woodenware" />
          <String fx:value="Stoneware" />
          <String fx:value="Metalware" />
          <String fx:value="Fabric" />
        </FXCollections>
      </items>
    </ComboBox>

This is my controller class:

 @FXML
private ComboBox<?> categoryComboBox;
public void setCategoryComboBox(ComboBox<String> categoryComboBox) {
    this.categoryComboBox = categoryComboBox;
}

public ComboBox<String> getCategoryComboBox() {
    return categoryComboBox;
}

@FXML
private void comboBoxSelection(ActionEvent event) {
   categoryComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
         public void changed(ObservableValue<? extends String> ov,
             String old_val, String new_val) {
                String categoryStr =  getCategoryComboBox().getValue().toString(); //Don't know what to put here
     }

When I try to get selected item from comboBox:

  int category = panel.getCategoryComboBox().getValue()

It gives me an error message "incompatible data tyep and I have no idea why. I am new to scene builder and netbeans so please tell me where am I did wrongly.

Thanks in advance.

Body:
The error is in this line:

private ComboBox<?> categoryComboBox;

You can't cast from ? to int. So change this line to:

private ComboBox<Integer> categoryComboBox;

Then you have to change the methode:

public ComboBox<String> getCategoryComboBox() {...}

to

 public ComboBox<Integer> getCategoryComboBox() {...}


问:
Passing Key:Value Pairs to Function
I would like to iterate through the key:value pairs in a dictionary and pass them as arguments in a function. In the function I am trying to return the value I am getting from an API call. My ultimate goal is to set the keys equal to the value I am getting from the API call.

```<code>def SomeFunction(key,val):
    return APICall(val)

myDict = {'a' : 'A',
          'b' : 'B',
          'c' : 'C'
         }
for key,val in myDict.items():
    key = SomeFunction(key,val)

print a
#>>>'return value from API'
</code>```

When I run this I get an error saying 'a' is not defined. I am struggling to understand why

```<code>key = SomeFunction(key,val)
</code>```

does not instantiate the given key with the assignment of the return value from the API call.

Any help would be great.

答:
I don't think you need to send key to SomeFunction(), since only val is used by the API call

Plus, to assign/change value for a key in a dict you have to use dict[key] == value.

So your code should change to..

```<code>def SomeFunction(key,val):
    return APICall(val)

myDict = {'a' : 'A',
          'b' : 'B',
          'c' : 'C'
         }
for key,val in myDict.items():
    dict[key] = SomeFunction(val)
</code>```

Now to print the return value from the API call, (like you were trying for a), you would need to iterate through the dict again and print the keys and values.

Title: Passing Key:Value Pairs to Function

Body:
I would like to iterate through the key:value pairs in a dictionary and pass them as arguments in a function. In the function I am trying to return the value I am getting from an API call. My ultimate goal is to set the keys equal to the value I am getting from the API call.

def SomeFunction(key,val):
    return APICall(val)

myDict = {'a' : 'A',
          'b' : 'B',
          'c' : 'C'
         }
for key,val in myDict.items():
    key = SomeFunction(key,val)

print a
#>>>'return value from API'

When I run this I get an error saying 'a' is not defined. I am struggling to understand why

key = SomeFunction(key,val)

does not instantiate the given key with the assignment of the return value from the API call.

Any help would be great.

Body:
I don't think you need to send key to SomeFunction(), since only val is used by the API call

Plus, to assign/change value for a key in a dict you have to use dict[key] == value.

So your code should change to..

def SomeFunction(key,val):
    return APICall(val)

myDict = {'a' : 'A',
          'b' : 'B',
          'c' : 'C'
         }
for key,val in myDict.items():
    dict[key] = SomeFunction(val)

Now to print the return value from the API call, (like you were trying for a), you would need to iterate through the dict again and print the keys and values.


问:
Sitecore 8.2 Lucene search isn't indexing all terms in a computed field
I have a computed field that takes information from an item's sub-items and concatenates it into a new field on the item.

If I step through the debugger, I can see that the computed field is returning the correct information. If I check the indexes that are generated by Sitecore using Luke, I can also see the computed field with the correct values. However, if I perform a search with Luke (or in Sitecore) for a term in the computed field, it does not always return all the documents that contain that term.

I believe this may be related to items with multiple language versions. For example, one of the items has a Dutch version and a Serbian (Latin) version. They both contain the word "vooderlen" in their content. But, when I do a search for that term, only the Serbian document is returned. If I search for "assisteert", both documents are returned. I'm not sure why some terms are being ignored.

Here's the relevant code:

public class ChildContent : AbstractComputedIndexField
{
    public override object ComputeFieldValue(IIndexable indexable)
    {
        Assert.ArgumentNotNull(indexable, "indexable");
        Item item = indexable as SitecoreIndexableItem;

        if (item == null)
        {
            return null;
        }

        // Only compute child content for Detail Layout templates
        string detailLayoutTemplateId = Settings.GetSetting("DetailLayoutTemplateId");

        if (item.TemplateID.ToString() != detailLayoutTemplateId)
        {
            return null;
        }

        // Get Content Detail item
        string contentDetailId = item["Content Detail"];
        var valueString = new StringBuilder();
        Item contentDetailItem;
        string introContent, mainContent;

        if (string.IsNullOrEmpty(contentDetailId))
        {
            return null;
        }

        contentDetailItem = item.Database.GetItem(ID.Parse(contentDetailId), item.Language);

        if (contentDetailItem == null)
        {
            return null;
        }

        // Concatenate intro and main content
        introContent = contentDetailItem["Intro Content"];
        mainContent = contentDetailItem["Main Content"];

        if (!string.IsNullOrWhiteSpace(introContent))
        {
            valueString.Append(Regex.Replace(introContent, "<.*?>", " ") + " ");
        }

        if (!string.IsNullOrWhiteSpace(mainContent))
        {
            valueString.Append(Regex.Replace(mainContent, "<.*?>", " ") + " ");
        }

        return valueString.ToString();
    }
}
```

<p>I'm also using the following search configuration.</p>

<pre class="lang-xml prettyprint-override"><code><fieldMap type="Sitecore.ContentSearch.FieldMap, Sitecore.ContentSearch">
    <fieldNames hint="raw:AddFieldByFieldName">
        <field fieldName="_uniqueid"
            storageType="YES"
            indexType="TOKENIZED"
            vectorType="NO"
            boost="1f"
            type="System.String"
            settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
            <analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" />
        </field>
        <field fieldName="childcontent"
            storageType="YES"
            indexType="TOKENIZED"
            vectorType="NO"
            boost="1f"
            type="System.String"
            settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
        </field>
    </fieldNames>
</fieldMap>

<fields hint="raw:AddComputedIndexField">
    <field fieldName="childcontent">My.Namespace.ComputedFields.ChildContent, MyWebApp</field>
</fields>
</code>```

答:
I noticed that if I used the DutchAnalyzer in Luke, I was able to get back more results for the Dutch language. Unfortunately, Sitecore does not offer more than a few analyzers, and none are language specific unless you create a custom analyzer.

Fortunately, this put me on the right track, and I looked into different ways to get back results for the specific language I needed. By passing in a CultureExecutionContext into the GetQueryable method, I was able to get the results I expected.

var queryable = context.GetQueryable<SearchResultItem>(
    new CultureExecutionContext(
        CultureInfo.GetCultureInfo(Sitecore.Context.Language.ToString())
    )
);
```

Body:
I have a computed field that takes information from an item's sub-items and concatenates it into a new field on the item.

If I step through the debugger, I can see that the computed field is returning the correct information. If I check the indexes that are generated by Sitecore using Luke, I can also see the computed field with the correct values. However, if I perform a search with Luke (or in Sitecore) for a term in the computed field, it does not always return all the documents that contain that term.

I believe this may be related to items with multiple language versions. For example, one of the items has a Dutch version and a Serbian (Latin) version. They both contain the word "vooderlen" in their content. But, when I do a search for that term, only the Serbian document is returned. If I search for "assisteert", both documents are returned. I'm not sure why some terms are being ignored.

Here's the relevant code:

public class ChildContent : AbstractComputedIndexField
{
    public override object ComputeFieldValue(IIndexable indexable)
    {
        Assert.ArgumentNotNull(indexable, "indexable");
        Item item = indexable as SitecoreIndexableItem;

        if (item == null)
        {
            return null;
        }

        // Only compute child content for Detail Layout templates
        string detailLayoutTemplateId = Settings.GetSetting("DetailLayoutTemplateId");

        if (item.TemplateID.ToString() != detailLayoutTemplateId)
        {
            return null;
        }

        // Get Content Detail item
        string contentDetailId = item["Content Detail"];
        var valueString = new StringBuilder();
        Item contentDetailItem;
        string introContent, mainContent;

        if (string.IsNullOrEmpty(contentDetailId))
        {
            return null;
        }

        contentDetailItem = item.Database.GetItem(ID.Parse(contentDetailId), item.Language);

        if (contentDetailItem == null)
        {
            return null;
        }

        // Concatenate intro and main content
        introContent = contentDetailItem["Intro Content"];
        mainContent = contentDetailItem["Main Content"];

        if (!string.IsNullOrWhiteSpace(introContent))
        {
            valueString.Append(Regex.Replace(introContent, "<.*?>", " ") + " ");
        }

        if (!string.IsNullOrWhiteSpace(mainContent))
        {
            valueString.Append(Regex.Replace(mainContent, "<.*?>", " ") + " ");
        }

        return valueString.ToString();
    }
}

I'm also using the following search configuration.

<fieldMap type="Sitecore.ContentSearch.FieldMap, Sitecore.ContentSearch">
    <fieldNames hint="raw:AddFieldByFieldName">
        <field fieldName="_uniqueid"
            storageType="YES"
            indexType="TOKENIZED"
            vectorType="NO"
            boost="1f"
            type="System.String"
            settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
            <analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" />
        </field>
        <field fieldName="childcontent"
            storageType="YES"
            indexType="TOKENIZED"
            vectorType="NO"
            boost="1f"
            type="System.String"
            settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
        </field>
    </fieldNames>
</fieldMap>

<fields hint="raw:AddComputedIndexField">
    <field fieldName="childcontent">My.Namespace.ComputedFields.ChildContent, MyWebApp</field>
</fields>


答:
If you want to change the value of a key in a dctionary, you need to re-assign it, as @Haris has already pointed out.

```<code>for key,val in myDict.items():
    myDict[key] = SomeFunction(key,val)

print myDict['a']
</code>```

Note that you can not just use print a, because you do not magically get a variable a - the string a is still just a key in your dictionary.

Title: Passing Key:Value Pairs to Function

Body:
If you want to change the value of a key in a dctionary, you need to re-assign it, as @Haris has already pointed out.

for key,val in myDict.items():
    myDict[key] = SomeFunction(key,val)

print myDict['a']

Note that you can not just use print a, because you do not magically get a variable a - the string a is still just a key in your dictionary.


问:
When is an object completely defined?
I'm learning javascript and want to define 2 classes inside an object. The second class is derived from the first class.

It looks like:

let foo = {
    bar: (function () {
        let bar_msg = '';

        class bar {
            constructor(msg) {
                bar_msg = msg;
            }
        }
        return bar;
    }()),
    baz: (function () {
        let baz_msg = '';

        class baz extends foo.bar {
            constructor(msg) {
                super();
                baz_msg = msg;
            }
        }
        return baz;
    }())
};```
</div>
</div>
</p>

<p>Error message:</p>

<blockquote>
  <p>Uncaught ReferenceError: foo is not defined</p>
</blockquote>

<p>Then, I've tried to split the classes to multiple parts:</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>let foo = {};

foo.bar = (function () {
    let bar_msg = '';

    class bar {
        constructor(msg) {
            bar_msg = msg;
        }
    }
    return bar;
}());

foo.baz = (function () {
    let baz_msg = '';

    class baz extends foo.bar {
        constructor(msg) {
            super();
            baz_msg = msg;
        }
        msg() {
            return baz_msg;
        }
    }
    return baz;
}());

let b = new foo.baz('hi!');
console.log(b.msg());</code>```

It works.

So, my question is: Why do I get the difference? I cannot show some google search results because I have no idea about the keywords.

答:
An object is 'completely' defined when you declared it and assign it a value like so:

```<code>var foo = 'bar';
</code>```

You may declare a variable but not assign it to any value:

```<code>var foo;
</code>```

and when you try to access it, it will give you undefined. You may also assign a value to an undeclared variable:

```<code>foo = 'bar';
</code>```

And the javascript will automatically create a global variable foo. If you try to access a variable that has never been declared or implicitly declared (e.g foo = 'bar'). It will throw an error;

```<code>console.log(iDoNotExist); // will throw an error!
</code>```

In your first code, the class baz, could not locate foo in its own scope, so it will go to the global scope. But since it's also not available in the global scope and it has neither been declared explicitly nor implicitly, it will throw an error.

In the second code, you have explicitly declared foo and assign it to an object and added a property bar right after it. Any code written after foo is declared would be able to access it, including when you assign the property bar to foo, in which a class called baz tries to extend foo.bar. If the piece of code that tries to extend foo or foo.bar is written after the definition of foo. It will throw an error. See snippet below for example:

class baz extends foo {
        constructor(msg) {
            super();
            baz_msg = msg;
        }
        msg() {
            return baz_msg;
        }
    }

let foo = {};

let b = new foo.baz('hi!');```

In summary, you get the difference because the accessibility of foo. In the first variable you try to access it before it is both neither explicitly nor implicitly defined, resulting in an error. In the second variable, you've declared and assigned it to a value and try to access it after, which is perfectly legal.

Title: When is an object completely defined?

Body:
I'm learning javascript and want to define 2 classes inside an object. The second class is derived from the first class.

It looks like:

let foo = {
    bar: (function () {
        let bar_msg = '';

        class bar {
            constructor(msg) {
                bar_msg = msg;
            }
        }
        return bar;
    }()),
    baz: (function () {
        let baz_msg = '';

        class baz extends foo.bar {
            constructor(msg) {
                super();
                baz_msg = msg;
            }
        }
        return baz;
    }())
};

Error message:

Uncaught ReferenceError: foo is not defined

Then, I've tried to split the classes to multiple parts:

let foo = {};

foo.bar = (function () {
    let bar_msg = '';

    class bar {
        constructor(msg) {
            bar_msg = msg;
        }
    }
    return bar;
}());

foo.baz = (function () {
    let baz_msg = '';

    class baz extends foo.bar {
        constructor(msg) {
            super();
            baz_msg = msg;
        }
        msg() {
            return baz_msg;
        }
    }
    return baz;
}());

let b = new foo.baz('hi!');
console.log(b.msg());

It works.

So, my question is: Why do I get the difference? I cannot show some google search results because I have no idea about the keywords.

Body:
An object is 'completely' defined when you declared it and assign it a value like so:

var foo = 'bar';

You may declare a variable but not assign it to any value:

var foo;

and when you try to access it, it will give you undefined. You may also assign a value to an undeclared variable:

foo = 'bar';

And the javascript will automatically create a global variable foo. If you try to access a variable that has never been declared or implicitly declared (e.g foo = 'bar'). It will throw an error;

console.log(iDoNotExist); // will throw an error!

In your first code, the class baz, could not locate foo in its own scope, so it will go to the global scope. But since it's also not available in the global scope and it has neither been declared explicitly nor implicitly, it will throw an error.

In the second code, you have explicitly declared foo and assign it to an object and added a property bar right after it. Any code written after foo is declared would be able to access it, including when you assign the property bar to foo, in which a class called baz tries to extend foo.bar. If the piece of code that tries to extend foo or foo.bar is written after the definition of foo. It will throw an error. See snippet below for example:

class baz extends foo {
        constructor(msg) {
            super();
            baz_msg = msg;
        }
        msg() {
            return baz_msg;
        }
    }

let foo = {};

let b = new foo.baz('hi!');

In summary, you get the difference because the accessibility of foo. In the first variable you try to access it before it is both neither explicitly nor implicitly defined, resulting in an error. In the second variable, you've declared and assigned it to a value and try to access it after, which is perfectly legal.


问:
Node.js connect to ftp and download files
Hello i downloaded this npm module to connect to my ftp :  node-ftps

connection class

```<code>var FTPS = require('ftps');
var ftps = new FTPS({
  host: 'myhost',
  username: 'user',
  password: 'mypw',
  protocol: 'ftp'
});

ftps.exec(function (err, res) {
  console.log();
});
</code>```

how can i check if the connection was successful and how can  i get all files from  my path!

tryed to add an file but get an error i didn't even know if im connected

答:
I would advice you to try node-ftp which supports ftps too, Although node-ftps does the same work, it lacks good documentation and examples.

Checkout here,

https://github.com/mscdex/node-ftp

To setup a connection and to access it features, All you need to do is to download a node wrapper called ftp-client which is developed exclusively for the node-ftp module.

You can install this wrapper by issuing the below command,

```<code>npm install ftp-client
</code>```

To initialize it use the below command,

```<code>var ftpClient = require('ftp-client'),
client = new ftpClient(config, options);
</code>```

And you can find a complete example code here which will walk you through how we can connect to a server, and simultaneously upload all files from the test directory, overwriting only older files found on the server, and download files from /public_html/test directory.

https://github.com/noodny/node-ftp-client#examples

Hope this helps!

Body:
Hello i downloaded this npm module to connect to my ftp :  node-ftps

connection class

var FTPS = require('ftps');
var ftps = new FTPS({
  host: 'myhost',
  username: 'user',
  password: 'mypw',
  protocol: 'ftp'
});

ftps.exec(function (err, res) {
  console.log();
});

how can i check if the connection was successful and how can  i get all files from  my path!

tryed to add an file but get an error i didn't even know if im connected

Body:
I would advice you to try node-ftp which supports ftps too, Although node-ftps does the same work, it lacks good documentation and examples.

Checkout here,

https://github.com/mscdex/node-ftp

To setup a connection and to access it features, All you need to do is to download a node wrapper called ftp-client which is developed exclusively for the node-ftp module.

You can install this wrapper by issuing the below command,

npm install ftp-client

To initialize it use the below command,

var ftpClient = require('ftp-client'),
client = new ftpClient(config, options);

And you can find a complete example code here which will walk you through how we can connect to a server, and simultaneously upload all files from the test directory, overwriting only older files found on the server, and download files from /public_html/test directory.

https://github.com/noodny/node-ftp-client#examples

Hope this helps!


问:
retrieve sql query from cakephp finder method
I'm creating a behavior that log to a table the sql query executed by a particular Model in a controller. Looking for a method to return me the sql query executed for a particular finder method (like $this->MyModel->find('all') ) I found on the bakery that I can use $this->MyModel->find('sql'), but doesn't work for me. Someone knows how can I achieve this?

Thanks in advance

答:
$this->Model->find('sql') is not supported natively by Cake. You have to follow the rest of the instructions in the Bakery article for installing a new DBO driver, and adding support for the find('sql') method in your AppModel. Once you do this, it should be able to get you what you're looking for.

http://bakery.cakephp.org/articles/grant_cox/2008/06/23/get-the-find-query-sql-rather-than-query-result

ContentLicense: CC BY-SA 2.5


问:
Text-align isn't working for form element
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

```<code><header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>
</code>```

My css:

```<code>ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}
</code>```

Jsfiddle: https://jsfiddle.net/dsotpsq4/

答:
header {
  padding: 0 20px;
}

ul {
  display: inline;
  padding: 0;
}

ul li {
  display: inline;
  margin: 0 10px;
}

header form {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header></code>```

Body:
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

One

Two

Three

Four

    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>

My css:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

Jsfiddle: https://jsfiddle.net/dsotpsq4/

Body:
header {
  padding: 0 20px;
}

ul {
  display: inline;
  padding: 0;
}

ul li {
  display: inline;
  margin: 0 10px;
}

header form {
  float: right;
}

<header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>


问:
Docker compose variables
I have a problem with docker compose, I want to use internal conainer variables to create another another variables:

```<code>  myapp:
image: image
depends_on:
  - anotherimage
environment:
  - "VAR1=var1"
  - "VAR2=${HOSTNAME}_${VAR1}"
</code>```

What I get in VAR2 the hostname of docker engine host and nothing for VAR1

I'd like to have something like:

```<code>39ed52c98e92_var1
</code>```

答:
Docker-compose resolves variables in the compose file from the environment where you run the docker-compose command, not from inside the container. If you want to configure your environment from inside the container, you'll need to add this to the command or entrypoint your container runs. If you don't already have an entrypoint, you could create one as:

```<code>#!/bin/sh

export VAR2=${HOSTNAME}_${VAR1}
exec "$@"
</code>```

To use that, your Dockerfile would then have two extra lines:

```<code>COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
</code>```

Make sure to chmod 755 entrypoint.sh before running your docker build.

Edit: VAR1 not resolving inside your yml is a similar issue. Each variable is defined by docker-compose for the container, but that doesn't change the environment on the host that docker-compose is using. So you can't use that variable on later lines of the yml.

Title: Docker compose variables

Body:
I have a problem with docker compose, I want to use internal conainer variables to create another another variables:

  myapp:
image: image
depends_on:
  - anotherimage
environment:
  - "VAR1=var1"
  - "VAR2=${HOSTNAME}_${VAR1}"

What I get in VAR2 the hostname of docker engine host and nothing for VAR1

I'd like to have something like:

39ed52c98e92_var1

Body:
Docker-compose resolves variables in the compose file from the environment where you run the docker-compose command, not from inside the container. If you want to configure your environment from inside the container, you'll need to add this to the command or entrypoint your container runs. If you don't already have an entrypoint, you could create one as:

#!/bin/sh

export VAR2=${HOSTNAME}_${VAR1}
exec "$@"

To use that, your Dockerfile would then have two extra lines:

COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

Make sure to chmod 755 entrypoint.sh before running your docker build.

Edit: VAR1 not resolving inside your yml is a similar issue. Each variable is defined by docker-compose for the container, but that doesn't change the environment on the host that docker-compose is using. So you can't use that variable on later lines of the yml.


问:
Why does
 seem to be preferred over  for navigation bars?
According to what I've read so far,  seems to be better, but every single example I see on the Internet uses
.

Is it just me seeing things or do people really use
 ?

If so, is there a reason why ?

EDIT : just in case someone was wondering, of course I'm talking about navigation bars, and nav can't replace div in other cases...

答:
 is not a generic replacement for
 (or vice-versa). It's a semantic element that should be used for navigation.

The HTML  element represents a section of a page whose purpose
  is to provide navigation links, either within the current document or
  to other documents. Common examples of navigation sections are menus,
  tables of contents, and indexes (MDN).

 has been around much longer than , which was introduced in HTML5, and is intended to be used as a generic container.

Title: Why does <div> seem to be preferred over <nav> for navigation bars?

Body:
<nav> is not a generic replacement for <div> (or vice-versa). It's a semantic element that should be used for navigation.

The HTML <nav> element represents a section of a page whose purpose
  is to provide navigation links, either within the current document or
  to other documents. Common examples of navigation sections are menus,
  tables of contents, and indexes (MDN).

<div> has been around much longer than <nav>, which was introduced in HTML5, and is intended to be used as a generic container.


问:
Java format currency and concatenate with string
I recently upgraded my jasperserver from version 4 to version 6.3 and changed from I report to Jasper studio.  I used to format my titles like the following

```<code>"Total " + new java.text.DecimalFormat("£ #,##0.00").format($V{field1_1})
</code>```

Doing this results in the following error

```<code>java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
</code>```

How should I perform this operation now?

答:
Please check what value you are getting in $V{field1_1}. There is no problem with this statement</p>

```<code>public static void main(final String[] args) {
    System.out.println("Total " + new java.text.DecimalFormat("£ #,##0.00").format(1000.11));
}
</code>```

Body:
I recently upgraded my jasperserver from version 4 to version 6.3 and changed from I report to Jasper studio.  I used to format my titles like the following

"Total " + new java.text.DecimalFormat("£ #,##0.00").format($V{field1_1})

Doing this results in the following error

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String

How should I perform this operation now?

Body:
Please check what value you are getting in $V{field1_1}. There is no problem with this statement

public static void main(final String[] args) {
    System.out.println("Total " + new java.text.DecimalFormat("£ #,##0.00").format(1000.11));
}


问:
Formula doesn't recognize cell reference - Dynamic range
I have a SUMIFS formula with which I am trying to build a dynamic range in order to avoid a circular reference. As it must search and sum through all the range, it must not consider the line where the formula is placed.

Sheet - Example

So I wrote this formula:

SUMIFS((C1:ADDRESS(VALUE(ROW(C6))-1;COLUMN(C1));ADDRESS(VALUE(ROW(C6))+1;COLUMN(C1)):ADDRESS(COUNTA(C:C);COLUMN(C1)));(C1:ADDRESS(VALUE(ROW(C6))-1;COLUMN(A1));ADDRESS(VALUE(ROW(C6))+1;COLUMN(A1)):ADDRESS(COUNTA(C:C);COLUMN(A1)));A6;(B1:ADDRESS(VALUE(ROW(C6))-1;COLUMN(B1));ADDRESS(VALUE(ROW(C6))+1;COLUMN(B1)):ADDRESS(COUNTA(C:C);COLUMN(B1)));"X")

However, after the sum_range it doesn't recognize the cell references. It remains "black". I tried another formula with OFFSET but got the same issue.

Any ideia what is going on?

A quick note, I need a dynamic range because there might be new lines inserted afterwards or people might apply filters, so I cannot use a normal reference.

答:
You cannot have the formula in the same column as the range to sum, in this case it would cause a circular reference.

Use INDEX and two SUMIFS, SUMIFS does not like disjointed ranges and ADDRESS/OFFSET/INDIRECT are volatile:

```<code>=SUMIFS($C$1:INDEX(C:C;ROW()-1);$A$1:INDEX(A:A;ROW()-1);A2;$B$1:INDEX(B:B;ROW()-1);B2)+SUMIFS(INDEX(C:C;ROW()+1):INDEX(C:C;MATCH(1E+99;C:C));INDEX(A:A;ROW()+1):INDEX(A:A;MATCH(1E+99;C:C));A2;INDEX(B:B;ROW()+1):INDEX(B:B;MATCH(1E+99;C:C));B2)
</code>```

Body:
You cannot have the formula in the same column as the range to sum, in this case it would cause a circular reference.

Use INDEX and two SUMIFS, SUMIFS does not like disjointed ranges and ADDRESS/OFFSET/INDIRECT are volatile:

=SUMIFS($C$1:INDEX(C:C;ROW()-1);$A$1:INDEX(A:A;ROW()-1);A2;$B$1:INDEX(B:B;ROW()-1);B2)+SUMIFS(INDEX(C:C;ROW()+1):INDEX(C:C;MATCH(1E+99;C:C));INDEX(A:A;ROW()+1):INDEX(A:A;MATCH(1E+99;C:C));A2;INDEX(B:B;ROW()+1):INDEX(B:B;MATCH(1E+99;C:C));B2)


问:
Testing Finalizers and IDisposable
The question is how can I test the fact that object disposes resources when finalise is called.
The code for the class:

```<code>public class TestClass : IDisposable {

    public bool HasBeenDisposed {get; private set; }

    public void Dispose() {
        HasBeenDisposed = true;
    }

    ~TestClass() {
        Dispose();
    }
}
</code>```

Please note that I don't care about the correct implementation of Dispose/Finalize just now as I want to find the way to test it first. At this stage it is enough to assume the HasBeenDisposed will be set to true if Dispose/Finalize ware called.

The actual test I wrote looks like:

UPDATED WITH WEAKREFERENCE:

```<code>[Test]
public void IsCleanedUpOnGarbadgeCollection() {
    var o = new TestClass();
    o.HasBeenDisposed.Should().Be.False();

    **var weak = new WeakReference(o, true); // true =Track after finalisation
    o = null; // Make eligible for GC**

    GC.Collect(0, GCCollectionMode.Forced);
    GC.WaitForPendingFinalizers();

    **((TestClass)weak.Target)**.HasBeenDisposed.Should().Be.True();
}
</code>```

or the code I like better (ADDED AFTER UPDATE):

```<code>[Test]
public void IsCleanedUpOnGarbadgeCollection() {
    WeakReference weak = null;

    // Use action to isolate instance and make them eligible for GC
    // Use WeakReference to track the object after finalisaiton
    Action act = () = {
        var o = new TestClass();
        o.HasBeenDisposed.Should().Be.False();
        weak = new WeakReference(o, true); // True=Track reference AFTER Finalize
    };

    act();

    GC.Collect(0, GCCollectionMode.Forced);
    GC.WaitForPendingFinalizers();

    // No access to o variable here which forces us to use WeakReference only to avoid error
    ((TestClass)weak.Target).HasBeenDisposed.Should().Be.True();
}
</code>```

This test fails (PASSES AFTER UPDATE) but I observe following (UPDATED):

GC.WaitForPendingFinalizers() does suspend the thread and finalises instance in o, but only if is not rooted. Assigned NULL to it and used WeakReference to get it AFTER finalisation.

Finilize (destructor) code is executed at correct point when the o does not hold the instance.

So what is the correct way of testing this. What do I miss?

I suppose it is the variable o that prevents GC from collection it.

UPDATE: Yes it is the issue. Had to use WeakReference instead.

答:
A memory profiler is the most appropriate way to test for leaks.

I could recommend the .Net Memory Profiler.

Title: Testing Finalizers and IDisposable

Body:
The question is how can I test the fact that object disposes resources when finalise is called.
The code for the class:

public class TestClass : IDisposable {

    public bool HasBeenDisposed {get; private set; }

    public void Dispose() {
        HasBeenDisposed = true;
    }

    ~TestClass() {
        Dispose();
    }
}

Please note that I don't care about the correct implementation of Dispose/Finalize just now as I want to find the way to test it first. At this stage it is enough to assume the HasBeenDisposed will be set to true if Dispose/Finalize ware called.

The actual test I wrote looks like:

UPDATED WITH WEAKREFERENCE:

[Test]
public void IsCleanedUpOnGarbadgeCollection() {
    var o = new TestClass();
    o.HasBeenDisposed.Should().Be.False();

    **var weak = new WeakReference(o, true); // true =Track after finalisation
    o = null; // Make eligible for GC**

    GC.Collect(0, GCCollectionMode.Forced);
    GC.WaitForPendingFinalizers();

    **((TestClass)weak.Target)**.HasBeenDisposed.Should().Be.True();
}

or the code I like better (ADDED AFTER UPDATE):

[Test]
public void IsCleanedUpOnGarbadgeCollection() {
    WeakReference weak = null;

    // Use action to isolate instance and make them eligible for GC
    // Use WeakReference to track the object after finalisaiton
    Action act = () = {
        var o = new TestClass();
        o.HasBeenDisposed.Should().Be.False();
        weak = new WeakReference(o, true); // True=Track reference AFTER Finalize
    };

    act();

    GC.Collect(0, GCCollectionMode.Forced);
    GC.WaitForPendingFinalizers();

    // No access to o variable here which forces us to use WeakReference only to avoid error
    ((TestClass)weak.Target).HasBeenDisposed.Should().Be.True();
}

This test fails (PASSES AFTER UPDATE) but I observe following (UPDATED):

GC.WaitForPendingFinalizers() does suspend the thread and finalises instance in o, but only if is not rooted. Assigned NULL to it and used WeakReference to get it AFTER finalisation.

Finilize (destructor) code is executed at correct point when the o does not hold the instance.

So what is the correct way of testing this. What do I miss?

I suppose it is the variable o that prevents GC from collection it.

UPDATE: Yes it is the issue. Had to use WeakReference instead.


问:
Datepicker textfield edit uneditable
I have a DatePicker with the following code :

```<code>    datepicker.getEditor().addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
        datepicker.show();
    }
    );
</code>```

When clicked on the textfield, the popup appears.
Datepicker popup open

The problem is that i can't type a number in the textfield when the popup is shown.
is it a problem of focus ?
thanks for your help.

答:
```<code>import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Skin;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ExampleDatePicker extends Application {
    public static void main(final String[] args) {
        launch(args);
    }

private DatePicker datepicker;

@Override
public void start(final Stage primaryStage) {

    final StackPane stackPane = new StackPane();
    this.datepicker = new DatePicker() {
        @Override
        protected Skin<?> createDefaultSkin() {
            final DatePickerSkin datePickerSkin = (DatePickerSkin) super.createDefaultSkin();

            datePickerSkin.getPopupContent().setOnKeyTyped(new EventHandler<KeyEvent>() {
                @Override
                public void handle(final KeyEvent ke) {
                    ExampleDatePicker.this.setText(ke.getCharacter());
                }
            });

            return datePickerSkin;
        }

    };

    this.datepicker.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
        this.datepicker.show();
    });

    stackPane.getChildren().add(this.datepicker);
    primaryStage.setScene(new Scene(stackPane, 400.0, 200.0));
    primaryStage.show();

}

public void setText(final String string) {
    this.datepicker.getEditor().setText(this.datepicker.getEditor().getText() + string);
}}
</code>```

Title: Datepicker textfield edit uneditable

Body:
I have a DatePicker with the following code :

    datepicker.getEditor().addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
        datepicker.show();
    }
    );

When clicked on the textfield, the popup appears.
Datepicker popup open

The problem is that i can't type a number in the textfield when the popup is shown.
is it a problem of focus ?
thanks for your help.


问:
dask dataframe apply meta
I'm wanting to do a frequency count on a single column of a dask dataframe. The code works, but I get an warning complaining that meta is not defined. If I try to define meta I get an error AttributeError: 'DataFrame' object has no attribute 'name'. For this particular use case it doesn't look like I need to define meta but I'd like to know how to do that for future reference.

Dummy dataframe and the column frequencies

```<code>import pandas as pd
from dask import dataframe as dd

df = pd.DataFrame([['Sam', 'Alex', 'David', 'Sarah', 'Alice', 'Sam', 'Anna'],
                   ['Sam', 'David', 'David', 'Alice', 'Sam', 'Alice', 'Sam'],
                   [12, 10, 15, 23, 18, 20, 26]],
                  index=['Column A', 'Column B', 'Column C']).T
dask_df = dd.from_pandas(df)
</code>```

```<code>In [39]: dask_df.head()
Out[39]:
  Column A Column B Column C
0      Sam      Sam       12
1     Alex    David       10
2    David    David       15
3    Sarah    Alice       23
4    Alice      Sam       18
</code>```

```<code>(dask_df.groupby('Column B')
        .apply(lambda group: len(group))
       ).compute()

UserWarning: `meta` is not specified, inferred from partial data. Please provide `meta` if the result is unexpected.
  Before: .apply(func)
  After:  .apply(func, meta={'x': 'f8', 'y': 'f8'}) for dataframe result
  or:     .apply(func, meta=('x', 'f8'))            for series result
  warnings.warn(msg)
Out[60]:
Column B
Alice    2
David    2
Sam      3
dtype: int64
</code>```

Trying to define meta produces AttributeError

```<code> (dask_df.groupby('Column B')
         .apply(lambda d: len(d), meta={'Column B': 'int'})).compute()
</code>```

same for this

```<code> (dask_df.groupby('Column B')
         .apply(lambda d: len(d), meta=pd.DataFrame({'Column B': 'int'}))).compute()
</code>```

same if I try having the dtype be int instead of "int" or for that matter 'f8' or np.float64 so it doesn't seem like it's the dtype that is causing the problem.

The documentation on meta seems to imply that I should be doing exactly what I'm trying to do (http://dask.pydata.org/en/latest/dataframe-design.html#metadata).

What is meta? and how am I supposed to define it?

Using python 3.6 dask 0.14.3 and pandas 0.20.2

答:
meta is the prescription of the names/types of the output from the computation. This is required because apply() is flexible enough that it can produce just about anything from a dataframe. As you can see, if you don't provide a meta, then dask actually computes part of the data, to see what the types should be - which is fine, but you should know it is happening.
You can avoid this pre-computation (which can be expensive) and be more explicit when you know what the output should look like, by providing a zero-row version of the output (dataframe or series), or just the types.

The output of your computation is actually a series, so the following is the simplest that works

```<code>(dask_df.groupby('Column B')
     .apply(len, meta=('int'))).compute()
</code>```

but more accurate would be

```<code>(dask_df.groupby('Column B')
     .apply(len, meta=pd.Series(dtype='int', name='Column B')))
</code>```

Title: dask dataframe apply meta

Body:
I'm wanting to do a frequency count on a single column of a dask dataframe. The code works, but I get an warning complaining that meta is not defined. If I try to define meta I get an error AttributeError: 'DataFrame' object has no attribute 'name'. For this particular use case it doesn't look like I need to define meta but I'd like to know how to do that for future reference.

Dummy dataframe and the column frequencies

import pandas as pd
from dask import dataframe as dd

df = pd.DataFrame([['Sam', 'Alex', 'David', 'Sarah', 'Alice', 'Sam', 'Anna'],
                   ['Sam', 'David', 'David', 'Alice', 'Sam', 'Alice', 'Sam'],
                   [12, 10, 15, 23, 18, 20, 26]],
                  index=['Column A', 'Column B', 'Column C']).T
dask_df = dd.from_pandas(df)

In [39]: dask_df.head()
Out[39]:
  Column A Column B Column C
0      Sam      Sam       12
1     Alex    David       10
2    David    David       15
3    Sarah    Alice       23
4    Alice      Sam       18

(dask_df.groupby('Column B')
        .apply(lambda group: len(group))
       ).compute()

UserWarning: `meta` is not specified, inferred from partial data. Please provide `meta` if the result is unexpected.
  Before: .apply(func)
  After:  .apply(func, meta={'x': 'f8', 'y': 'f8'}) for dataframe result
  or:     .apply(func, meta=('x', 'f8'))            for series result
  warnings.warn(msg)
Out[60]:
Column B
Alice    2
David    2
Sam      3
dtype: int64

Trying to define meta produces AttributeError

 (dask_df.groupby('Column B')
         .apply(lambda d: len(d), meta={'Column B': 'int'})).compute()

same for this

 (dask_df.groupby('Column B')
         .apply(lambda d: len(d), meta=pd.DataFrame({'Column B': 'int'}))).compute()

same if I try having the dtype be int instead of "int" or for that matter 'f8' or np.float64 so it doesn't seem like it's the dtype that is causing the problem.

The documentation on meta seems to imply that I should be doing exactly what I'm trying to do (http://dask.pydata.org/en/latest/dataframe-design.html#metadata).

What is meta? and how am I supposed to define it?

Using python 3.6 dask 0.14.3 and pandas 0.20.2

Body:
meta is the prescription of the names/types of the output from the computation. This is required because apply() is flexible enough that it can produce just about anything from a dataframe. As you can see, if you don't provide a meta, then dask actually computes part of the data, to see what the types should be - which is fine, but you should know it is happening.
You can avoid this pre-computation (which can be expensive) and be more explicit when you know what the output should look like, by providing a zero-row version of the output (dataframe or series), or just the types.

The output of your computation is actually a series, so the following is the simplest that works

(dask_df.groupby('Column B')
     .apply(len, meta=('int'))).compute()

but more accurate would be

(dask_df.groupby('Column B')
     .apply(len, meta=pd.Series(dtype='int', name='Column B')))


问:
Sum up vector values till threshold, then start again
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

```<code>b = [1 4 4 2 3 5 6 3 5]
</code>```

Any ideas?

答:
By normalizing the arguments of cumsum with the threshold and flooring you can get grouping indizes for accumarray, which then can do the cumsumming groupwise:

```<code>t = 5;
a = [1 3 4 2 1 5 6 3 2];

%// cumulative sum of normalized vector a
n = cumsum(a/t);
%// subs for accumarray
subs = floor( n ) + 1;
%// cumsum of every group
aout = accumarray( subs(:), (1:numel(subs)).', [], @(x) {cumsum(a(x))});
%// gather results;
b = [aout{:}]
</code>```

Body:
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

b = [1 4 4 2 3 5 6 3 5]

Any ideas?

Body:
By normalizing the arguments of cumsum with the threshold and flooring you can get grouping indizes for accumarray, which then can do the cumsumming groupwise:

t = 5;
a = [1 3 4 2 1 5 6 3 2];

%// cumulative sum of normalized vector a
n = cumsum(a/t);
%// subs for accumarray
subs = floor( n ) + 1;
%// cumsum of every group
aout = accumarray( subs(:), (1:numel(subs)).', [], @(x) {cumsum(a(x))});
%// gather results;
b = [aout{:}]


问:
converting string representation of a date and time to the System.DateTime
```<code>DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);
</code>```

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?

答:
Try using DateTime.TryParseExact()

It appears to allow you to tell it what date format to expect.

Body:
DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?


问:
Building RethinkDB filter dynamically
I want to filter my data using filter specified as below:

```<code>var filter = { minAge: 2, maxAge: 11, country:'uk', city':'london'};
</code>```

In which case the filtering will be:

```<code>r.db(dbName).table(tableName)
    .filter(r.row("minAge").ge(filter.minAge)
             .and(r.row("maxAge").le(filter.maxAge))
             .and(r.row('country').eq(filter.country))
             .and(r.row('city').eq(filter.city))
           );
</code>```

However some of the filter predicates could be missing for example if I have only min age and city, I want to filter only on them:

```<code>var filter2 = { minAge: 2, city':'london'};
</code>```

Above filter should result in below

```<code>r.db(dbName).table(tableName)
    .filter(r.row("minAge").ge(filter.minAge)
             .and(r.row('city').eq(filter.city))
           );
</code>```

How to build a ReQL query according to my filter object keys that I could pass to the filter function.

答:
A moderately dirty trick to avoid filtering by missing fields is to just add default values -

```<code>r.db(dbName).table(tableName)
   .filter(r.row("minAge").default(filter.minAge).ge(filter.minAge)
      .and(r.row("maxAge").default(filter.maxAge).le(filter.maxAge))
      .and(r.row('country').default(filter.country).eq(filter.country))
      .and(r.row('city').default(filter.city).eq(filter.city))
   );
</code>```

It's not efficient, it's not great, but it should work if you don't want to over-engineer it for the time being.

Please note that sequential scans - queries without using a limit early in the query, or queries without any indexes, with just .filter() function on the whole table - will use a sequential indexes, and are SLOW. It doesn't scale well.

Title: Building RethinkDB filter dynamically

Body:
I want to filter my data using filter specified as below:

var filter = { minAge: 2, maxAge: 11, country:'uk', city':'london'};

In which case the filtering will be:

r.db(dbName).table(tableName)
    .filter(r.row("minAge").ge(filter.minAge)
             .and(r.row("maxAge").le(filter.maxAge))
             .and(r.row('country').eq(filter.country))
             .and(r.row('city').eq(filter.city))
           );

However some of the filter predicates could be missing for example if I have only min age and city, I want to filter only on them:

var filter2 = { minAge: 2, city':'london'};

Above filter should result in below

r.db(dbName).table(tableName)
    .filter(r.row("minAge").ge(filter.minAge)
             .and(r.row('city').eq(filter.city))
           );

How to build a ReQL query according to my filter object keys that I could pass to the filter function.

Body:
A moderately dirty trick to avoid filtering by missing fields is to just add default values -

r.db(dbName).table(tableName)
   .filter(r.row("minAge").default(filter.minAge).ge(filter.minAge)
      .and(r.row("maxAge").default(filter.maxAge).le(filter.maxAge))
      .and(r.row('country').default(filter.country).eq(filter.country))
      .and(r.row('city').default(filter.city).eq(filter.city))
   );

It's not efficient, it's not great, but it should work if you don't want to over-engineer it for the time being.

Please note that sequential scans - queries without using a limit early in the query, or queries without any indexes, with just .filter() function on the whole table - will use a sequential indexes, and are SLOW. It doesn't scale well.


问:
Woocommerce can't disable Guest Checkout
I am using Woocommerce and am having problems disabling the guest checkout.

I have made sure 'Enable Guest Checkout' is unticked in the settings page but people are still able to checkout without creating an account or logging in.

Is there somewhere else I should be setting this?

答:
Go to WooCommerce > Accounts and untick Enable registration on the "Checkout" page.

This should do the job!

Alternatively, you can add this code to your theme functions.php

```<code>add_action( 'template_redirect', 'woo_restirct_checkout' );
function woo_restirct_checkout() {

    if ( !is_user_logged_in() && is_checkout() ) {

        $my_account_url = get_permalink( get_option('woocommerce_myaccount_page_id') );
        wp_redirect( $my_account_url );
        exit;

    }
}
</code>```

Cheers,
Francesco

Body:
Go to WooCommerce > Accounts and untick Enable registration on the "Checkout" page.

This should do the job!

Alternatively, you can add this code to your theme functions.php

add_action( 'template_redirect', 'woo_restirct_checkout' );
function woo_restirct_checkout() {

    if ( !is_user_logged_in() && is_checkout() ) {

        $my_account_url = get_permalink( get_option('woocommerce_myaccount_page_id') );
        wp_redirect( $my_account_url );
        exit;

    }
}

Cheers,
Francesco


问:
Saving Microphone Stream to mp3 or wave
I recording sound from Microphone in Windows Phone device. Using Xna.Framework.Audio.Microphone I store the sound in MemoryStream. I can save it to PCM format. However It will be much better to convert it to mp3 file. If converting to mp3 is impossible then maybe somebody at least knows how to convert it to wav.

Thanks for your answers.

答:
Here's a great thread which answers this question:

http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/59af6c3b-0dd1-4fa0-8438-d7f82e655109

It is a simple WAV file with its
  header missing. Therefore, Windows has
  no clue about the format.
  Unfortunately, the current WP7 OS API
  (as far as I know) doesn't offer any
  service to create a WAV file (the RIFF
  header + the raw PCM data). The RIFF
  header is not complicated and well
  documented. It is fairly simple to
  write the managed code to create one
  using the known PCM format which, as
  you already know, is 16bit/mono.

Or alternatively, if you're only trying to save/play it on the wp7 device ...

You should be able to use;

```<code> SoundEffect sePlay = new SoundEffect(yourSavedByte[], mic.SampleRate, AudioChannels.Mono);
 sePlay.Play();
</code>```

to playback your audio byte[]. I
  record, save, and playback using just
  the byte[] on WP7. You shouldn’t need
  anything more then the raw byte[] if
  you use the SoundEffect class for
  playback.

Title: Saving Microphone Stream to mp3 or wave

Body:
Here's a great thread which answers this question:

http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/59af6c3b-0dd1-4fa0-8438-d7f82e655109

It is a simple WAV file with its
  header missing. Therefore, Windows has
  no clue about the format.
  Unfortunately, the current WP7 OS API
  (as far as I know) doesn't offer any
  service to create a WAV file (the RIFF
  header + the raw PCM data). The RIFF
  header is not complicated and well
  documented. It is fairly simple to
  write the managed code to create one
  using the known PCM format which, as
  you already know, is 16bit/mono.

Or alternatively, if you're only trying to save/play it on the wp7 device ...

You should be able to use;

 SoundEffect sePlay = new SoundEffect(yourSavedByte[], mic.SampleRate, AudioChannels.Mono);
 sePlay.Play();

to playback your audio byte[]. I
  record, save, and playback using just
  the byte[] on WP7. You shouldn’t need
  anything more then the raw byte[] if
  you use the SoundEffect class for
  playback.


问:
How to auto paste a value if checkbox is checked
I want a functionality, i have a list with checkbox i if checkbox is selected i want to paste the selected value in a text field.

Something like appeared in above image.

edited:

```<code><table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Order Id</th>
                <th>Order Proposed Id</th>
                <th>Order Proposed Date</th>
                <th>Store Id</th>
                <th>Select</th>
            </tr>
        </thead>
        <tbody>
        <%for(Order orderSList:orderList){ %>
            <tr>
                <td><%=orderSList.getOrderId()%></td>
                 <td><%=orderSList.getOrderProposedId()%></td>
                 <td><%=orderSList.getOrderProposedDate()%></td>
                 <td><%=orderSList.getStoreId()%></td>
                 <td><input type="checkbox" name="<portlet:namespace/>notSubmitList" value="<%=orderSList.getOrderId()%>" class="case" /></td>
            </tr>
          <%} %>
        </tbody>
    </table>
 <script>
</code>```

答:
var selectedValue = function(id, _this){
  var checkboxes = document.getElementsByClassName('selectedIN');

  for (var i = 0; i < checkboxes.length; i++) {
    if(_this != checkboxes[i]){
      checkboxes[i].checked = false;
    }
  }
  if(_this.checked){
    document.getElementById('result').innerHTML =       document.getElementById(id).value;
  }else{
     document.getElementById('result').innerHTML = '';
}
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input:-moz-read-only { /* For Firefox */
    background-color: none;
    border:none;
}

input:read-only {
    background-color: none;
    border:none;
}</code>```

                Order Id
                Order Proposed Id
                Order Proposed Date
                Store Id
                Select

              1001

                <input type="text" value="123" readonly="true" id="opID_1"/>

               Order Proposed Date
                Store Id

                <input type='checkbox'  onchange="selectedValue('opID_1',this)" class="selectedIN"/>

            5555

              <input type="text" value="456" readonly="true" id="opID_2"/>

             Order Proposed Date
              Store Id

              <input type='checkbox' onchange="selectedValue('opID_2',this)" class="selectedIN"/>

            5555

              <input type="text" value="789" readonly="true" id="opID_3"/>

             Order Proposed Date
              Store Id

              <input type='checkbox' onchange="selectedValue('opID_3',this)" class="selectedIN"/>

            5555

              <input type="text" value="999" readonly="true" id="opID_4"/>

             Order Proposed Date
              Store Id

              <input type='checkbox' onchange="selectedValue('opID_4',this)" class="selectedIN"/>

  Selected Value:

    ```

Body:
I want a functionality, i have a list with checkbox i if checkbox is selected i want to paste the selected value in a text field.

Something like appeared in above image.

edited:

                Order Id
                Order Proposed Id
                Order Proposed Date
                Store Id
                Select

        <%for(Order orderSList:orderList){ %>

                <%=orderSList.getOrderId()%>
                 <%=orderSList.getOrderProposedId()%>
                 <%=orderSList.getOrderProposedDate()%>
                 <%=orderSList.getStoreId()%>
                 <input type="checkbox" name="<portlet:namespace/>notSubmitList" value="<%=orderSList.getOrderId()%>" class="case" />

          <%} %>

Body:
var selectedValue = function(id, _this){
  var checkboxes = document.getElementsByClassName('selectedIN');

  for (var i = 0; i < checkboxes.length; i++) {
    if(_this != checkboxes[i]){
      checkboxes[i].checked = false;
    }
  }
  if(_this.checked){
    document.getElementById('result').innerHTML =       document.getElementById(id).value;
  }else{
     document.getElementById('result').innerHTML = '';
}
  }

input:-moz-read-only { /* For Firefox */
    background-color: none;
    border:none;
}

input:read-only {
    background-color: none;
    border:none;
}

<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Order Id</th>
                <th>Order Proposed Id</th>
                <th>Order Proposed Date</th>
                <th>Store Id</th>
                <th>Select</th>
            </tr>
        </thead>
        <tbody>
          <tr>
              <td>1001</td>
              <td>
                <input type="text" value="123" readonly="true" id="opID_1"/>
              </td>
               <td>Order Proposed Date</td>
                <td>Store Id</td>
              <td>
                <input type='checkbox'  onchange="selectedValue('opID_1',this)" class="selectedIN"/>
              </td>
          </tr>
          <tr>
            <td>5555</td>
            <td>
              <input type="text" value="456" readonly="true" id="opID_2"/>
            </td>
             <td>Order Proposed Date</td>
              <td>Store Id</td>
            <td>
              <input type='checkbox' onchange="selectedValue('opID_2',this)" class="selectedIN"/>
            </td>
        </tr>
        <tr>
            <td>5555</td>
            <td>
              <input type="text" value="789" readonly="true" id="opID_3"/>
            </td>
             <td>Order Proposed Date</td>
              <td>Store Id</td>
            <td>
              <input type='checkbox' onchange="selectedValue('opID_3',this)" class="selectedIN"/>
            </td>
        </tr>
        <tr>
            <td>5555</td>
            <td>
              <input type="text" value="999" readonly="true" id="opID_4"/>
            </td>
             <td>Order Proposed Date</td>
              <td>Store Id</td>
            <td>
              <input type='checkbox' onchange="selectedValue('opID_4',this)" class="selectedIN"/>
            </td>
        </tr>
</table>
<div class='selected_values'>
  <strong>Selected Value: <span id="result"></span></strong>
</div>
        </tbody>


问:
Memory-efficient filtering of `DataFrame` rows
I have a large DataFrame object (1,440,000,000 rows). I operate at memory (swap includet) limit.

I need to extract a subset of the rows with certain value of a field. However if i do like that:

```<code>>>> SUBSET = DATA[DATA.field == value]
</code>```

I end with either MemoryError exception or crash.
Is there any way to filter rows explicitely - without calculating intermediate mask (DATA.field == value)?

I have found DataFrame.filter() and DataFrame.select() methods, but they operate on column labels/row indices rather than on the row data.

答:
If by any change all the data in the DataFrame are of same types, use numpy array instead, it's more memory efficient and faster. You can convert your dataframe to numpy matrix by df.as_matrix().

Also that you might wanna check how much memory the dataframe already takes by:

```<code>    import sys
    sys.getsizeof()
</code>```

that returns the size in bytes.

Body:
I have a large DataFrame object (1,440,000,000 rows). I operate at memory (swap includet) limit.

I need to extract a subset of the rows with certain value of a field. However if i do like that:

>>> SUBSET = DATA[DATA.field == value]

I end with either MemoryError exception or crash.
Is there any way to filter rows explicitely - without calculating intermediate mask (DATA.field == value)?

I have found DataFrame.filter() and DataFrame.select() methods, but they operate on column labels/row indices rather than on the row data.

Body:
If by any change all the data in the DataFrame are of same types, use numpy array instead, it's more memory efficient and faster. You can convert your dataframe to numpy matrix by df.as_matrix().

Also that you might wanna check how much memory the dataframe already takes by:

    import sys
    sys.getsizeof()

that returns the size in bytes.


问:
Get value of attributes of nextElementSibling using javascript
my html is like this:

```<code><button onclick="prints(this.nextElementSibling.attributes)">me!</button>
<a href="project/webdev/convert.js"> convert! </a>
</code>```

the prints function just outputs the function parameters onto console log.
I need to find the href value of the a tag immediately beside the anchor tag. i.e on clicking the button, I need to get the value "project/webdev/convert.js"

The "this.nextElementSibling.href" gives me "http://127.0.0.1:8080/project/webdev/convert.js". Is there anyway I can instead get the relative address? i.e project/webdev/convert.js.

Anyhelp would be very much appreciated.(I cannot use Jquery, I want to do this with vanilla javascript)

答:
You could try this:

const btn = document.querySelector('button');
const link = btn.nextElementSibling.getAttribute('href');

btn.addEventListener('click', () => console.log(link));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>me!</button>
 convert! </code>```

Body:
my html is like this:

<button onclick="prints(this.nextElementSibling.attributes)">me!</button>
 convert!

the prints function just outputs the function parameters onto console log.
I need to find the href value of the a tag immediately beside the anchor tag. i.e on clicking the button, I need to get the value "project/webdev/convert.js"

The "this.nextElementSibling.href" gives me "http://127.0.0.1:8080/project/webdev/convert.js". Is there anyway I can instead get the relative address? i.e project/webdev/convert.js.

Anyhelp would be very much appreciated.(I cannot use Jquery, I want to do this with vanilla javascript)

Body:
You could try this:

const btn = document.querySelector('button');
const link = btn.nextElementSibling.getAttribute('href');

btn.addEventListener('click', () => console.log(link));

<button>me!</button>
<a href="project/webdev/convert.js"> convert! </a>


问:
php image from portrait to landscape
I'm using ImageResize php library in order to resize and crop images.

But now, I'm facing a problem that I've can't find a solution, and it is to convert and image from portrait to landscape.

Ofcourse I can do it deforming the image, but I want to achieve something like this:

Example

So, the point is how to put the portrait image inside a landscape background in order to not deform it.

Any idea?

Cheers.

答:
Manually, you can resize in Plain PHP like this:

```<code>//define image path
$filename="image.jpg";

// Load the image
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

//and save it on your server...
file_put_contents("myNEWimage.jpg",$rotate);
</code>```

I have an image class on Github (no rotate mind you), and it has a resize and crop. The logic in there basically keeps the aspect ratio correct and crops off overlapping stuff. You could do something similar after rotating:

https://github.com/delboy1978uk/image/blob/master/src/Image.php#L163-L180

```<code>public function resizeAndCrop($width,$height)
    {
        $target_ratio = $width / $height;
        $actual_ratio = $this->getWidth() / $this->getHeight();
        if($target_ratio == $actual_ratio){
            // Scale to size
            $this->resize($width,$height);
        } elseif($target_ratio > $actual_ratio) {
            // Resize to width, crop extra height
            $this->resizeToWidth($width);
            $this->crop($width,$height,true);
        } else {
            // Resize to height, crop additional width
            $this->resizeToHeight($height);
            $this->crop($width,$height,true);
        }
    }
</code>```

Title: php image from portrait to landscape

Body:
Manually, you can resize in Plain PHP like this:

//define image path
$filename="image.jpg";

// Load the image
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

//and save it on your server...
file_put_contents("myNEWimage.jpg",$rotate);

I have an image class on Github (no rotate mind you), and it has a resize and crop. The logic in there basically keeps the aspect ratio correct and crops off overlapping stuff. You could do something similar after rotating:

https://github.com/delboy1978uk/image/blob/master/src/Image.php#L163-L180

public function resizeAndCrop($width,$height)
    {
        $target_ratio = $width / $height;
        $actual_ratio = $this->getWidth() / $this->getHeight();
        if($target_ratio == $actual_ratio){
            // Scale to size
            $this->resize($width,$height);
        } elseif($target_ratio > $actual_ratio) {
            // Resize to width, crop extra height
            $this->resizeToWidth($width);
            $this->crop($width,$height,true);
        } else {
            // Resize to height, crop additional width
            $this->resizeToHeight($height);
            $this->crop($width,$height,true);
        }
    }