问:
Heroku rake db:structure:load with cleardb can't find 'mysql'
I am trying to install an instance of Sharetribe on a heroku dyno. I am at the point where I am trying to create the database. I first tried rake db:migrate and it worked for most of the migrations but failed on one of them.

I was advised to use rake db:structure:load, so I tried that and I am getting an error from Heroku saying that mysql needs to be added to the PATH variable. Why is this, and how can I fix it? I'm not sure why it happens on db:schema:load and db:structure:load but not on db:migrate.

The complete stack trace with the error message is:

```<code>rake aborted!
failed to execute:
mysqlPlease check the output above for any errors and make sure that `mysql` is installed in your PATH and has proper permissions.

/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/mysql_database_tasks.rb:148:in `run_cmd'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/mysql_database_tasks.rb:72:in `structure_load'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:189:in `structure_load'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:222:in `load_schema_for'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:236:in `block in load_schema_current'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:276:in `block in each_current_configuration'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:275:in `each'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:275:in `each_current_configuration'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:235:in `load_schema_current'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/railties/databases.rake:293:in `block (3 levels) in <top (required)>'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli/exec.rb:74:in `load'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli/exec.rb:74:in `kernel_load'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli/exec.rb:27:in `run'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli.rb:332:in `exec'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli.rb:20:in `dispatch'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli.rb:11:in `start'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/exe/bundle:34:in `block in <top (required)>'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/friendly_errors.rb:100:in `with_friendly_errors'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/exe/bundle:26:in `<top (required)>'
/app/bin/bundle:3:in `load'
/app/bin/bundle:3:in `<main>'
Tasks: TOP => db:structure:load
(See full trace by running task with --trace)
</code>```

Thanks!

答:
Heroku doesn't support mysql, you need to use pg gem in your gemfile in production block.
Please read Getting Started with Rails 5.x on Heroku

Body:
I am trying to install an instance of Sharetribe on a heroku dyno. I am at the point where I am trying to create the database. I first tried rake db:migrate and it worked for most of the migrations but failed on one of them.

I was advised to use rake db:structure:load, so I tried that and I am getting an error from Heroku saying that mysql needs to be added to the PATH variable. Why is this, and how can I fix it? I'm not sure why it happens on db:schema:load and db:structure:load but not on db:migrate.

The complete stack trace with the error message is:

rake aborted!
failed to execute:
mysqlPlease check the output above for any errors and make sure that `mysql` is installed in your PATH and has proper permissions.

/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/mysql_database_tasks.rb:148:in `run_cmd'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/mysql_database_tasks.rb:72:in `structure_load'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:189:in `structure_load'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:222:in `load_schema_for'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:236:in `block in load_schema_current'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:276:in `block in each_current_configuration'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:275:in `each'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:275:in `each_current_configuration'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:235:in `load_schema_current'
/app/vendor/bundle/ruby/2.3.0/gems/activerecord-4.2.7.1/lib/active_record/railties/databases.rake:293:in `block (3 levels) in <top (required)>'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli/exec.rb:74:in `load'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli/exec.rb:74:in `kernel_load'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli/exec.rb:27:in `run'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli.rb:332:in `exec'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli.rb:20:in `dispatch'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/cli.rb:11:in `start'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/exe/bundle:34:in `block in <top (required)>'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/lib/bundler/friendly_errors.rb:100:in `with_friendly_errors'
/app/vendor/bundle/ruby/2.3.0/gems/bundler-1.13.7/exe/bundle:26:in `<top (required)>'
/app/bin/bundle:3:in `load'
/app/bin/bundle:3:in `'
Tasks: TOP => db:structure:load
(See full trace by running task with --trace)

Thanks!


来源: stackexchange

问:
Love2D Collision?
I'm building a flappy bird clone i LOVE 2D and all i have is the bird flapping, with the background behind it. I would like to make it so when the bird touches the ground the game ends,or shows a game over screen. And i cant seem to find a good way to do this without using external libraries though. Is there a solution to this? I have the ground as separate image if that helps or matters. I'm using the latest LOVE 2D framework version.

Thanks! I know someone will give me the answer i need!

答:
I use this simple code partially taken from the love2d forums. Here's the code and under the function is how you use it. (can be reused for many objects)

```<code>-----------------------Code-------------------------
function colMulti(x1, y1, w1, h1,  x2, y2, w2, h2)
    return  x1 < x2+w2 and
            x2 < x1+w1 and
            y1 < y2+h2 and
            y2 < y1+h1
end

-----------------------Usage-------------------------
x1, y1, w1, h1 = bird.x, bird.y, bird.img:getWidth(), bird.img:getHeight()
x2, y2, w2, h2 = ground.x, ground.y, ground.img:getWidth(), ground.img:getHeight()

if colMulti(x1, y1, w1, h1,  x2, y2, w2, h2) then
    —Execute bird death here
end
</code>```

There is a much longer, complicated, and more efficient method for collision detection, but you have to learn a ton about the built in physics engine for love2d. (Doesn't seem like you need it thou.)

More info on other way: https://love2d.org/wiki/love.physics

ContentLicense: CC BY-SA 3.0

Title: Love2D Collision?

Body:
I use this simple code partially taken from the love2d forums. Here's the code and under the function is how you use it. (can be reused for many objects)

-----------------------Code-------------------------
function colMulti(x1, y1, w1, h1,  x2, y2, w2, h2)
    return  x1 < x2+w2 and
            x2 < x1+w1 and
            y1 < y2+h2 and
            y2 < y1+h1
end

-----------------------Usage-------------------------
x1, y1, w1, h1 = bird.x, bird.y, bird.img:getWidth(), bird.img:getHeight()
x2, y2, w2, h2 = ground.x, ground.y, ground.img:getWidth(), ground.img:getHeight()

if colMulti(x1, y1, w1, h1,  x2, y2, w2, h2) then
    —Execute bird death here
end

There is a much longer, complicated, and more efficient method for collision detection, but you have to learn a ton about the built in physics engine for love2d. (Doesn't seem like you need it thou.)

More info on other way: https://love2d.org/wiki/love.physics


问:
Interning strings in declarative programming
The following scenario shows an abstraction that seems to me to be impossible to implement declaratively.

Suppose that I want to create a Symbol object which allows you to create objects with strings that can be compared, like Symbol.for() in JavaScript. A simple implementation in JS might look like this:

function MySymbol(text){//Comparable symbol object class
  this.text = text;
  this.equals = function(other){//Method to compare to other MySymbol
    return this.text == other.text;
  }
}
```

<p>I could easily write this in a declarative language like Haskell:
</p>

```data MySymbol = MySymbol String

makeSymbol :: String -> MySymbol
makeSymbol s = MySymbol s

compareSymbol :: MySymbol -> MySymbol -> Bool
compareSymbol (MySymbol s1) (MySymbol s2) = s1 == s2
```

<p>However, maybe in the future I want to improve efficiency by using a global registry <strong>without changing the interface</strong> to the MySymbol objects. (The user of my class doesn't need to know that I've changed it to use a registry)</p>

<p>For example, this is easily done in Javascript:</p>

<pre class="lang-js prettyprint-override"><code>function MySymbol(text){
  if (MySymbol.registry.has(text)){//check if symbol already in registry
    this.id = MySymbol.registry.get(text);//get id
  } else {
    this.id = MySymbol.nextId++;
    MySymbol.registry.set(text, this.id);//Add new symbol with nextId
  }
  this.equals = function(other){//To compare, simply compare ids
    return this.id == other.id;
  }
}
//Setup initial empty registry
MySymbol.registry = new Map();//A map from strings to numbers
MySymbol.nextId = 0;
</code>```

However, it is impossible to create a mutable global registry in Haskell. (I can create a registry, but not without changing the interface to my functions.)

Specifically, these three possible Haskell solutions all have problems:

Force the user to pass a registry argument or equivalent, making the interface implementation dependent

Use some fancy Monad stuff like Haskell's Control.Monad.Random, which would require either foreseeing the optimization from the start or changing the interface (and is basically just adding the concept of state into your program and therefore breaks referential transparency etc.)

Have a slow implementation which might not be practical in a given application

None of these solutions allow me to sufficiently abstract away implementation from my Haskell interface.

So, my question is: Is there a way to implement this optimization to a Symbol object in Haskell (or any declarative language) without causing one of the three problems listed above,
and are there any other situations where an imperative language can express an abstraction (for example an optimization like above) that a declarative language can't?

答: The intern package shows how. As discussed by @luqui, it uses unsafePerformIO at a few key moments, and is careful to hide the identifiers produced during interning.

Body:
The following scenario shows an abstraction that seems to me to be impossible to implement declaratively.

Suppose that I want to create a Symbol object which allows you to create objects with strings that can be compared, like Symbol.for() in JavaScript. A simple implementation in JS might look like this:

function MySymbol(text){//Comparable symbol object class
  this.text = text;
  this.equals = function(other){//Method to compare to other MySymbol
    return this.text == other.text;
  }
}

I could easily write this in a declarative language like Haskell:

data MySymbol = MySymbol String

makeSymbol :: String -> MySymbol
makeSymbol s = MySymbol s

compareSymbol :: MySymbol -> MySymbol -> Bool
compareSymbol (MySymbol s1) (MySymbol s2) = s1 == s2

However, maybe in the future I want to improve efficiency by using a global registry without changing the interface to the MySymbol objects. (The user of my class doesn't need to know that I've changed it to use a registry)

For example, this is easily done in Javascript:

function MySymbol(text){
  if (MySymbol.registry.has(text)){//check if symbol already in registry
    this.id = MySymbol.registry.get(text);//get id
  } else {
    this.id = MySymbol.nextId++;
    MySymbol.registry.set(text, this.id);//Add new symbol with nextId
  }
  this.equals = function(other){//To compare, simply compare ids
    return this.id == other.id;
  }
}
//Setup initial empty registry
MySymbol.registry = new Map();//A map from strings to numbers
MySymbol.nextId = 0;

However, it is impossible to create a mutable global registry in Haskell. (I can create a registry, but not without changing the interface to my functions.)

Specifically, these three possible Haskell solutions all have problems:

Force the user to pass a registry argument or equivalent, making the interface implementation dependent

Use some fancy Monad stuff like Haskell's Control.Monad.Random, which would require either foreseeing the optimization from the start or changing the interface (and is basically just adding the concept of state into your program and therefore breaks referential transparency etc.)

Have a slow implementation which might not be practical in a given application

None of these solutions allow me to sufficiently abstract away implementation from my Haskell interface.

So, my question is: Is there a way to implement this optimization to a Symbol object in Haskell (or any declarative language) without causing one of the three problems listed above,
and are there any other situations where an imperative language can express an abstraction (for example an optimization like above) that a declarative language can't?


问:
Copy all files and folders from a source folder to multiple folders with a specic name
I have a source folder(c:\test*) and I want that folder copied to all folders in the same location (c:\resultaat) but only to the folders in that location that contains the name demo_profit.

I think I'm almost there, but I'm missing a small part I think.

```<code>$destination = get-item -include demo_profit* -path C:\resultaat\*
copy-item C:\test\* $destination -recurse -force
</code>```

thanks for your help

答:
The -Directory parameter of Get-ChildItem requires AFAIK PSv5</p>

```<code>Get-ChildItem -Directory -Path 'C:\resultaat\' | ForEach-Object{
  if (Test-Path (Join-Path $_.FullName 'demo_profit')){
    Copy-Item C:\test\* $_.FullName -recurse -force
  }
</code>```

Body:
I have a source folder(c:\test*) and I want that folder copied to all folders in the same location (c:\resultaat) but only to the folders in that location that contains the name demo_profit.

I think I'm almost there, but I'm missing a small part I think.

$destination = get-item -include demo_profit* -path C:\resultaat\*
copy-item C:\test\* $destination -recurse -force

thanks for your help

Body:
The -Directory parameter of Get-ChildItem requires AFAIK PSv5

Get-ChildItem -Directory -Path 'C:\resultaat\' | ForEach-Object{
  if (Test-Path (Join-Path $_.FullName 'demo_profit')){
    Copy-Item C:\test\* $_.FullName -recurse -force
  }


问:
PHPMailer on Godaddy server
Below is my code it works fine on XAMPP Server. When I load same to the Godaddy server it gives an error Class 'PHPMailer' not found in

I have loaded all PHPmailer files on godaddy server.

```<code><?php
$email_from = "something@gmail.com";
$from = "Name";

include_once('PHPMailer/PHPMailerAutoload.php');
$mail = new PHPMailer(true);

//Send mail using gmail

$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = 'ssl'; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "something@gmail.com"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->IsHTML(true);

//Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $from);
?>
</code>```

答:
Your error message is coming from this line not finding/importing the PHPMailer class file:

```<code>include_once('PHPMailer/PHPMailerAutoload.php');
</code>```

This definitely sounds like a pathing issue.

Are your directory paths all correct?  That is, this PHP code -- is it running from a directory with PHPMailer directory in the same location?  And if you're manually putting the files on your server, is your PHPMailerAutoload.php finding the PHPMailer class itself?

Title: PHPMailer on Godaddy server

Body:
Below is my code it works fine on XAMPP Server. When I load same to the Godaddy server it gives an error Class 'PHPMailer' not found in

I have loaded all PHPmailer files on godaddy server.

<?php
$email_from = "something@gmail.com";
$from = "Name";

include_once('PHPMailer/PHPMailerAutoload.php');
$mail = new PHPMailer(true);

//Send mail using gmail

$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = 'ssl'; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "something@gmail.com"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->IsHTML(true);

//Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $from);
?>

Body:
Your error message is coming from this line not finding/importing the PHPMailer class file:

include_once('PHPMailer/PHPMailerAutoload.php');

This definitely sounds like a pathing issue.

Are your directory paths all correct?  That is, this PHP code -- is it running from a directory with PHPMailer directory in the same location?  And if you're manually putting the files on your server, is your PHPMailerAutoload.php finding the PHPMailer class itself?


问:
simulate current date during tests
I am writing tests and I wonder if there is a way to change the current date during my test?

The point is that I am testing the statistic functionality of the application, which is connected to a tracking model that creates an instance every time an action is called (only some actions are tracked, via a "before_filter only" call)

So I need to call this actions in different controller at different points in time to test my analytics component is making the right calculations, but I did not find any way to implement change_current_time in the following sample code:

```<code>test "login count" do
  change_current_time(2.day.ago)
  get "users/login/testuser/testpassword"
  assert login_count(2.day.ago) == 1
  change_current_time(1.day.ago)
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(1.day.ago) == 2
end
</code>```

答: There's a bunch of gems for doing this kind of thing. My favourite is delorean: https://github.com/bebanjo/delorean</p>

ContentLicense: CC BY-SA 2.5

Title: simulate current date during tests

Body:
I am writing tests and I wonder if there is a way to change the current date during my test?

The point is that I am testing the statistic functionality of the application, which is connected to a tracking model that creates an instance every time an action is called (only some actions are tracked, via a "before_filter only" call)

So I need to call this actions in different controller at different points in time to test my analytics component is making the right calculations, but I did not find any way to implement change_current_time in the following sample code:

test "login count" do
  change_current_time(2.day.ago)
  get "users/login/testuser/testpassword"
  assert login_count(2.day.ago) == 1
  change_current_time(1.day.ago)
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(1.day.ago) == 2
end


问:
Get the PID from the child process
I am having an issue trying to get the PID from a command using Time.
The command I use is:

```<code>{ time cp  ubuntu/ubuntu-16.04.2-desktop-amd64.iso
 ubuntucopia/$i-ubuntu-16.04.2-desktop-amd64.iso; }
    2>> "logs/time.log" &
</code>```

If I use now $!, I've get te PID from TIME. How could I do to get the pid of the command cp? Currently to solve this I am using this:

```<code>father=$!
cpPid=$(pgrep -P $father)
</code>```

With this, not always I get the pid, sometimes $cpPid is empty.

Thank you!

答:
This will get you the pid of the cp command, though you should use a search string more specific than cp, as this sample has a high potential for multiple matches.</p>

```<code>ps -eo pid,cmd | grep cp | grep -v grep | awk '{print $1}'
</code>```

Title: Get the PID from the child process

Body:
I am having an issue trying to get the PID from a command using Time.
The command I use is:

{ time cp  ubuntu/ubuntu-16.04.2-desktop-amd64.iso
 ubuntucopia/$i-ubuntu-16.04.2-desktop-amd64.iso; }
    2>> "logs/time.log" &

If I use now $!, I've get te PID from TIME. How could I do to get the pid of the command cp? Currently to solve this I am using this:

father=$!
cpPid=$(pgrep -P $father)

With this, not always I get the pid, sometimes $cpPid is empty.

Thank you!

Body:
This will get you the pid of the cp command, though you should use a search string more specific than cp, as this sample has a high potential for multiple matches.

ps -eo pid,cmd | grep cp | grep -v grep | awk '{print $1}'


问:
AWS Java Lambda local variables vs object variables
I am trying to find answer to a very specific question. Trying to go through documentation but so far no luck.

Imagine this piece of code

```<code>@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
    Request request = parseRequest(input);

    List<String> validationErrors = validate(request);

    if (validationErrors.size() == 0){
        ordersManager.getOrderStatusForStore(orderId, storeId);
    } else {
        generateBadRequestResponse(output, "Invalid Request", null);
    }
}

private List<String> validate(Request request) {
    orderId = request.getPathParameters().get(PATH_PARAM_ORDER_ID);
    programId = request.getPathParameters().get(PATH_PARAM_STORE_ID);
    return new ArrayList<>();
}
</code>```

Here, I am storing orderId and storeId in field variables. Is this okay? I am not sure if AWS will cache this function and hence cache the field variables or would it initiate a new Java object for every request. If its a new object, then storing in field variable is fine but not sure.

答:
Strongly not recommended.

Multiple invocations may use the same Lambda function instance and this will break your current functionality.

You need to ensure your instance variables are thread safe and can be accessed by multiple threads when it comes to Lambda. Limit your instance variable writes to initialization - once only.

Body:
I am trying to find answer to a very specific question. Trying to go through documentation but so far no luck.

Imagine this piece of code

@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
    Request request = parseRequest(input);

    List<String> validationErrors = validate(request);

    if (validationErrors.size() == 0){
        ordersManager.getOrderStatusForStore(orderId, storeId);
    } else {
        generateBadRequestResponse(output, "Invalid Request", null);
    }
}

private List<String> validate(Request request) {
    orderId = request.getPathParameters().get(PATH_PARAM_ORDER_ID);
    programId = request.getPathParameters().get(PATH_PARAM_STORE_ID);
    return new ArrayList<>();
}

Here, I am storing orderId and storeId in field variables. Is this okay? I am not sure if AWS will cache this function and hence cache the field variables or would it initiate a new Java object for every request. If its a new object, then storing in field variable is fine but not sure.


问:
how to deal with multiple devise model for omniauth in ruby on rails
I have a 3types of users (student, teacher and admin). Students will record their study, Teachers will supervise students and admins will administer service. So I made all users with a devise gem. Actually my purpose was that every user can login with facebook or twitter but I couldn't do that because omniauthable in devise supports only one devise model...
how to deal with multiple devise model for omniauth like</p>

```<code><%= link_to 'student login with facebook', ........ %>
<%= link_to 'teacher login with facebook', ........ %>
</code>```

答:
You can follow this Devise guide on how to get around setting up multiple models with Devise :omniauthable here.

If you can get around using multiple models you should consider using 1 User model with 3 roles (Student, Teacher, Admin). Check out the cancancan gem and that might fit in better what with you are looking to do.

Body:
I have a 3types of users (student, teacher and admin). Students will record their study, Teachers will supervise students and admins will administer service. So I made all users with a devise gem. Actually my purpose was that every user can login with facebook or twitter but I couldn't do that because omniauthable in devise supports only one devise model...
how to deal with multiple devise model for omniauth like

<%= link_to 'student login with facebook', ........ %>
<%= link_to 'teacher login with facebook', ........ %>


问:
SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES)
I keep getting this error:

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost'
  (using password: YES)

And I don't know how to fix it.

I have installed MySQL, Apache2, PHP and phpMyAdmin. Then I've changed a few things in the .htaccess file and changed AllowOverride from none to all (not sure where I did this again). That's all I've done with the server. I read people talking about databases, but I've only got 1 DB.

答:
It seems you're attempting to access the database with the root user, without providing the corresponding password.
If you have no idea what the password is, I suggest you attempt to recover it, using this procedure.</p>


问:
Scala: importance during implementation of case class private
I understand that using something like

```<code>case class private A()

new A()#This will be a invalid call as A is private
</code>```

But what I do not understand that as from an implementation perspective, what advantage does this provide while coding? Because calling A() twice will give 2 instances of the class anyways. If this syntax is not used to prevent instantiation like Java, then why would I want to not let someone instantiate my class using new?

答:
Marking a case class constructor private is useless. As you've notices, case classes get a synthetic companion object with an apply method whose implementation is simply a call to the actual constructor.

Scala case classes have been designed to just "classes + the case modifier", meaning that everything that works on classes also works on case classes, which also include the (pointless) ability to specify access modifiers on the constructor.

Body:
I understand that using something like

case class private A()

new A()#This will be a invalid call as A is private

But what I do not understand that as from an implementation perspective, what advantage does this provide while coding? Because calling A() twice will give 2 instances of the class anyways. If this syntax is not used to prevent instantiation like Java, then why would I want to not let someone instantiate my class using new?


问:
How to isolate an integer in a QString
I have a QString of Gcode that will look like this:

```<code>T<some number> <and anything might come after it>
</code>```

Currently, I'm using myString.midRef(1,1).toInt() to get the digit I want (I don't care about the rest of the line). However, this will not work if there is a two digit number, like so:

```<code>T12 ;blah blah blah
</code>```

Is there a good / better way of doing this other than searching index by index to see where the number stops?

There will always be a T in front of the number.

There will always be a semicolon after the number if there is any other text after it, but there may not be a space in between the number and the semicolon.

There may or may not be anything after the number at all.

答:
Use regular expression to extract the number pattern, e.g.

```<code>int ib, ie, n;
QStringRef num;
ib = str.indexOf(QRegExp("T\\d+(\\s*;{1}.|$)"));
if (ib >= 0) {
    ib++;
    ie = str.indexOf(";", ib);
    n = ie >= ib ? ie - ib : -1;
    num = str.midRef(ib, n);
}
</code>```

Notes:

T\d+ match a pattern begins with T followed by one or more digit.

\s*;{1}.|$ match zero or more white spaces followed by semicolon plus any character OR exactly none in the last character.

Please note that in the above rule, "T123 " or "T123\n" won't match the pattern. If you want to allow white space, use the following:

```<code>QRegExp("T\\d+\\s*(;{1}.|$)")
</code>```

Title: How to isolate an integer in a QString

Body:
I have a QString of Gcode that will look like this:

T<some number> <and anything might come after it>

Currently, I'm using myString.midRef(1,1).toInt() to get the digit I want (I don't care about the rest of the line). However, this will not work if there is a two digit number, like so:

T12 ;blah blah blah

Is there a good / better way of doing this other than searching index by index to see where the number stops?

There will always be a T in front of the number.

There will always be a semicolon after the number if there is any other text after it, but there may not be a space in between the number and the semicolon.

There may or may not be anything after the number at all.

Body:
Use regular expression to extract the number pattern, e.g.

int ib, ie, n;
QStringRef num;
ib = str.indexOf(QRegExp("T\\d+(\\s*;{1}.|$)"));
if (ib >= 0) {
    ib++;
    ie = str.indexOf(";", ib);
    n = ie >= ib ? ie - ib : -1;
    num = str.midRef(ib, n);
}

Notes:

T\d+ match a pattern begins with T followed by one or more digit.

\s*;{1}.|$ match zero or more white spaces followed by semicolon plus any character OR exactly none in the last character.

Please note that in the above rule, "T123 " or "T123\n" won't match the pattern. If you want to allow white space, use the following:

QRegExp("T\\d+\\s*(;{1}.|$)")


问:
Python call class with inputs from list
I have a class called Interval for which I want to create multiple interval objects from a list of intervals. How do I do it with map ?

```<code>class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]
</code>```

I tried to do:

```<code>objs = map(Interval, intervals)
</code>```

But this sends the full interval as the first parameter rather than the inputs to the class individually.

答:
You can use starmap from itertools:

```<code><b>from itertools import starmap</b>

objs = <b>starmap</b>(Interval,intervals)</code>```

Mind that starmap works lazily (like map in Python-3.x) and that you will need to materialize it, for instance using list(..):

```<code>>>> list(objs)
[<__main__.Interval object at 0x7efbf7e82358>, <__main__.Interval object at 0x7efbf7e82390>, <__main__.Interval object at 0x7efbf7e823c8>, <__main__.Interval object at 0x7efbf7e82400>, <__main__.Interval object at 0x7efbf7e82438>]
</code>```

If you do not want to use the itertools library, an equivalent is:

```<code>objs = map(<b>lambda x: Interval(*x)</b>,intervals)</code>```

As far as I know, that's why they call it starmap: because of the asterisk if you would use a lambda expression.

Title: Python call class with inputs from list

Body:
I have a class called Interval for which I want to create multiple interval objects from a list of intervals. How do I do it with map ?

class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]

I tried to do:

objs = map(Interval, intervals)

But this sends the full interval as the first parameter rather than the inputs to the class individually.

Body:
You can use starmap from itertools:

from itertools import starmap

objs = starmap(Interval,intervals)

Mind that starmap works lazily (like map in Python-3.x) and that you will need to materialize it, for instance using list(..):

>>> list(objs)
[<__main__.Interval object at 0x7efbf7e82358>, <__main__.Interval object at 0x7efbf7e82390>, <__main__.Interval object at 0x7efbf7e823c8>, <__main__.Interval object at 0x7efbf7e82400>, <__main__.Interval object at 0x7efbf7e82438>]

If you do not want to use the itertools library, an equivalent is:

objs = map(lambda x: Interval(*x),intervals)

As far as I know, that's why they call it starmap: because of the asterisk if you would use a lambda expression.


问:
JavaScript template language that pre-compiles to pure JavaScript
I'm using the Google Closure Compiler in advanced mode for a project I'm working on. This is an extremely aggressive JavaScript compiler that can optimize your code quite a bit. However, in order to do this it needs to see the whole picture. That is to say, if I assign something to window.foo, and then only access window.foo from JS that the compiler can't see, it won't exist, since it will have been changed to window.f or even removed all together.

This complicates things when it comes time for JS temples. Since they are loaded at runtime out of a string, they tend to refer to variables that no longer exist. This can be mitigated slightly by using quoted assignment for the object used to provide values to the template. eg. templateContext['user'] rather then templateContext.user. However, that doesn't allow me to do templateContext.user.username and so on, so it's somewhat limiting.

tl;dr: I need a JavaScript templating solution that can be pre-processed into pure JavaScript that I can include in a .js file.

Does anything like this exist?

答: Honestly, I'm not sure how I missed this: Google Closure Templates.</p>


问:
Javascript get JSON value from URL error
im using the function below to get image names. I also use the json code to get data of a different url, but somehow it isnt working at this. (im new to javascript. Just writing php normally.</p>

```<code>function getImgname(name) {
        $.getJSON("http://url.com/info.php?name="+name, function(json321) {
       return json321.js_skininfo;
     });
}
</code>```

答:
I tried this now:

```<code>function getImgname(myName) {
                        $.ajax({
                            url: "http://url.com/ninfo.php",
                            type: 'POST',
                            dataType: 'json',
                            success: function (data) {
                                return data.js_skininfo;
                            },
                            error: function () {
                            }
                        });
}
</code>```

This isnt working (undefinied), but if i alert the data.js_skininfo it shows me the correct value.

Body:
im using the function below to get image names. I also use the json code to get data of a different url, but somehow it isnt working at this. (im new to javascript. Just writing php normally.

function getImgname(name) {
        $.getJSON("http://url.com/info.php?name="+name, function(json321) {
       return json321.js_skininfo;
     });
}

Body:
I tried this now:

function getImgname(myName) {
                        $.ajax({
                            url: "http://url.com/ninfo.php",
                            type: 'POST',
                            dataType: 'json',
                            success: function (data) {
                                return data.js_skininfo;
                            },
                            error: function () {
                            }
                        });
}

This isnt working (undefinied), but if i alert the data.js_skininfo it shows me the correct value.


问:
How to validate an input string using conditionally allowed strings?
I want to block some words from being used in a username unless they are a substring of a permitted string.

The words love, hug, and kiss are not permitted, unless they are used in mylovely,givehug,kissing.

I started with this pattern, but it doesn't work:

```<code>preg_match('[love|hug|kiss]', $data)
</code>```

These are some inputs with the desired outputs:

boolove (invalid - "love" found, but not in "mylovely")

mylovely (valid - "love" contained in "mylovely")

givehug (valid - "hug" contained in "givehug")

igivehug (valid - "hug" contained in "givehug")

kissing (valid - "kiss" contained in "kissing")

youhug (invalid - "hug" found, but not in "givehug")

ikiss (invalid - "kiss" found, but not in "kissing")

Basit (valid - doesn't contain love, hug, or kiss)

How can I achieve this validation to return a true|false response?

答:
My non-regex method has a potential flaw exposed when two $flag values exist, but one $forgive value exists, so I wish to provide a regex method that uses a pattern with lookbehinds and lookaheads to identify invalid strings:

Code (PHP Demo , Pattern Demo):

```<code>$inputs=['love','mickmackusa','kisses','mylovely','give','hug','givehug','kiss','kissing'];
foreach($inputs as $input){
    echo "\n$input ";
    var_export(preg_match('/kiss(?!ing)|(?<!give)hug|(?<!my)love(?!ly)/i',$input)==1?false:true);
}
</code>```

Output:

```<code>love false
mickmackusa true
kisses false
mylovely true
give true
hug false
givehug true
kiss false
kissing true
</code>```

Old non-regex method...

Input:

```<code>$input='code'; // mylovely(true) , give(false) , code(true)
$checks=['love'=>'mylovely','give'=>'givehug','kiss'=>'kissing'];
</code>```

Method (no regex):

```<code>$result=true;
foreach($checks as $flag=>$forgive){
    if(stripos($input,$flag)!==false && stripos($input,$forgive)===false){
        $result=false;  // unforgivable word included
        break;
    }
}
var_export($result);
</code>```

Output:

```<code>true
</code>```

Explanation:

The $checks array has keys that represent words that may be invalid, and values that are permitted if the key is matched in the $input value.

The 3 $check elements are iterated and stripos() is used to case-insensitively check for input validity.

For efficiency, as soon as $input is deemed invalid, the loop is broken.

Body:
I want to block some words from being used in a username unless they are a substring of a permitted string.

The words love, hug, and kiss are not permitted, unless they are used in mylovely,givehug,kissing.

I started with this pattern, but it doesn't work:

preg_match('[love|hug|kiss]', $data)

These are some inputs with the desired outputs:

boolove (invalid - "love" found, but not in "mylovely")

mylovely (valid - "love" contained in "mylovely")

givehug (valid - "hug" contained in "givehug")

igivehug (valid - "hug" contained in "givehug")

kissing (valid - "kiss" contained in "kissing")

youhug (invalid - "hug" found, but not in "givehug")

ikiss (invalid - "kiss" found, but not in "kissing")

Basit (valid - doesn't contain love, hug, or kiss)

How can I achieve this validation to return a true|false response?

Body:
My non-regex method has a potential flaw exposed when two $flag values exist, but one $forgive value exists, so I wish to provide a regex method that uses a pattern with lookbehinds and lookaheads to identify invalid strings:

Code (PHP Demo , Pattern Demo):

$inputs=['love','mickmackusa','kisses','mylovely','give','hug','givehug','kiss','kissing'];
foreach($inputs as $input){
    echo "\n$input ";
    var_export(preg_match('/kiss(?!ing)|(?<!give)hug|(?<!my)love(?!ly)/i',$input)==1?false:true);
}

Output:

love false
mickmackusa true
kisses false
mylovely true
give true
hug false
givehug true
kiss false
kissing true

Old non-regex method...

Input:

$input='code'; // mylovely(true) , give(false) , code(true)
$checks=['love'=>'mylovely','give'=>'givehug','kiss'=>'kissing'];

Method (no regex):

$result=true;
foreach($checks as $flag=>$forgive){
    if(stripos($input,$flag)!==false && stripos($input,$forgive)===false){
        $result=false;  // unforgivable word included
        break;
    }
}
var_export($result);

Output:

true

Explanation:

The $checks array has keys that represent words that may be invalid, and values that are permitted if the key is matched in the $input value.

The 3 $check elements are iterated and stripos() is used to case-insensitively check for input validity.

For efficiency, as soon as $input is deemed invalid, the loop is broken.


问:
Laravel Datatables adding column with specific html
I have a problem with adding column into the jquery.datatables.

My datatable function looks like this

```<code> public function getSliderImages()
{

    $query = Slider::with('User')->select('sliders.*');

    return Datatables::of($query)
        ->addColumn('fullName',function ($data){
            return $data->user->firstName .' '. $data->user->lastName;
        })
        ->addColumn('types',function ($data){
            return '<ul class="list-condensed list-unstyled no-margin">' .
                '<li><span class="text-semibold">Boyut:</span> '.$data->size.'</li>' .
                '<li><span class="text-semibold">Format:</span> ' .$data->ext.'</li></ul>';
        })

        ->make(true);
}
</code>```

The returning json file is pretty good however here is the problem
My datatable looks like this

And last thing is my javascript

```<code>columns: [
                {data: 'slider_slug', name: 'slider_slug',"render": function(data, type, row) {
                    return '<a href="'+loc+'/'+data+'" data-popup="lightbox"> <img src="'+loc+'/'+data+'" class="img-rounded img-preview" </a>';
                },

                    orderable: false,
                    searchable: false
                },
                {data: 'slider_slug', name: 'slider_slug'},
                {data: 'fullName', name: 'fullName'},
                {data: 'created_at', name: 'created_at'},
                {data: 'action',name:'action'},
                {data: 'types',name:'types'},
</code>```

The returning value is acts like a plain text but its html.

In the javascript I couldnt get 2 data from server.I mean I cannot get 2 variables in 1 row.

How can I solve this problem

答:
I think I have the solution to your problem, try this </p>

```<code> columns: [
              {data: 'slider_slug', name: 'slider_slug',
                            render:function (data, type, full, meta) {
                                console.log(full);
                                return '<a href="'+loc+'/'+data+'" data-popup="lightbox"> <img src="'+loc+'/'+data+'" class="img-rounded img-preview" </a>';
                            }
                    }
</code>```

Body:
I have a problem with adding column into the jquery.datatables.

My datatable function looks like this

 public function getSliderImages()
{

    $query = Slider::with('User')->select('sliders.*');

    return Datatables::of($query)
        ->addColumn('fullName',function ($data){
            return $data->user->firstName .' '. $data->user->lastName;
        })
        ->addColumn('types',function ($data){
            return '
' .
                '
Boyut: '.$data->size.'
' .
                '
Format: ' .$data->ext.'

';
        })

        ->make(true);
}

The returning json file is pretty good however here is the problem
My datatable looks like this

And last thing is my javascript

columns: [
                {data: 'slider_slug', name: 'slider_slug',"render": function(data, type, row) {
                    return ' <img src="'+loc+'/'+data+'" class="img-rounded img-preview" ';
                },

                    orderable: false,
                    searchable: false
                },
                {data: 'slider_slug', name: 'slider_slug'},
                {data: 'fullName', name: 'fullName'},
                {data: 'created_at', name: 'created_at'},
                {data: 'action',name:'action'},
                {data: 'types',name:'types'},

The returning value is acts like a plain text but its html.

In the javascript I couldnt get 2 data from server.I mean I cannot get 2 variables in 1 row.

How can I solve this problem

Body:
I think I have the solution to your problem, try this

 columns: [
              {data: 'slider_slug', name: 'slider_slug',
                            render:function (data, type, full, meta) {
                                console.log(full);
                                return '<a href="'+loc+'/'+data+'" data-popup="lightbox"> <img src="'+loc+'/'+data+'" class="img-rounded img-preview" </a>';
                            }
                    }


问:
Downloading Java JDK through Script
I have been using the following to download JDK 8u112 via a script.

```<code>wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u112-b15/jdk-8u112-linux-x64.tar.gz
</code>```

Recently, it throws ERROR 404: Not found and when you go to the link, it shows the same text in Downloading Java JDK on Linux via wget is shown license page instead

I've also tried http://download.oracle.com/otn/java/jdk/8u112-b15/jdk-8u112-linux-x64.tar.gz but it throws 401 Authorization Error.

Is there a new work around on this?

答:
It seems like the most recent version of jdk can be downloaded by wget but not the files in the archives.
As such, I'm using casper.js script to login to Oracle and to download.

Following is my script to download Japanese version of jdk8u121. The current script will only attempt to download but will fail on redirect. I'm using download.sh bash script to scan the log to get the url with session parameter and using wget to do the actual download.

You'll need to replace <username> and <password> with valid ones to login to Oracle site.

Change values of jdkTag and jdkFileLink to get the jdk version you want to download.

oraclejdk.js

```<code>var casper = require('casper').create({
  verbose: true,
  logLevel: 'info',  // debug
  pageSettings: {
    userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
    loadImages: false,
    loadPlugins: false
  }
});

// login info
var loginUrl='http://www.oracle.com/webapps/redirect/signon?nexturl=https://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html';
var username='<username>';
var password='<password>';

// accept license page info
var jdkUrl='http://www.oracle.com/technetwork/';
var jdkTag='jdk-8u121-oth-JPR';

// download jdk info
var jdkFileLink='jdk-8u121-oth-JPRXXXjdk-8u121-linux-x64.tar.gz';

// open login page
casper.start(loginUrl);

casper.thenEvaluate(function(username, password) {
//  this.capture('loginPage.png', {top:0, left:0, width:600, height:800});
    document.querySelector("#sso_username").value = username;
    document.querySelector("#ssopassword").value = password;
    doLogin(document.LoginForm);
}, {
     username: username,
     password: password
});

// login to oracle site
casper.then(function() {
  this.waitForUrl(jdkUrl, function() {
//    this.capture('jdkPage.png', {top:0, left:0, width:1200, height:800});
    this.evaluate(function(jdkTag) {
      disableDownloadAnchors(document, false, jdkTag);
      hideAgreementDiv(document, jdkTag);
      writeSessionCookie('oraclelicense', 'accept-securebackup-cookie');
    }, {
        jdkTag: jdkTag
    });
  }, null, null, 5000);
});

// accept license
casper.then(function() {
  this.waitFor(function checkLink() {
    return this.evaluate(function(jdkTag) {
      return (document.getElementById('agreementDiv' + jdkTag).getAttribute('style') === 'visibility: hidden;');
    }, {
        jdkTag: jdkTag
    });
  }, function then() {
//    this.capture('acceptedLicense.png', {top:0, left:0, width:1200, height:800});
    downlink = this.evaluate(function(jdkFileLink) {
      var jdkElement = document.getElementById(jdkFileLink);
      if (jdkElement) {
        var jdkLink = jdkElement.getAttribute("href");
        jdkElement.click();
        return jdkLink;
      }
    }, {
      jdkFileLink: jdkFileLink
    });
  }, null, 5000);
});

casper.run();
</code>```

download.sh

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

url=$(casperjs --web-security=no oraclejdk.js |grep "http://download.oracle.com/otn/java/jdk" $() | sed -e 's/^.*: //')
jdk=$(echo "${url}" | sed -e 's/^.*jdk-/jdk/' |sed -e 's/?.*//')
wget -O "${jdk}" "${url}"
</code>```

Title: Downloading Java JDK through Script

Body:
I have been using the following to download JDK 8u112 via a script.

wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u112-b15/jdk-8u112-linux-x64.tar.gz

Recently, it throws ERROR 404: Not found and when you go to the link, it shows the same text in Downloading Java JDK on Linux via wget is shown license page instead

I've also tried http://download.oracle.com/otn/java/jdk/8u112-b15/jdk-8u112-linux-x64.tar.gz but it throws 401 Authorization Error.

Is there a new work around on this?

Body:
It seems like the most recent version of jdk can be downloaded by wget but not the files in the archives.
As such, I'm using casper.js script to login to Oracle and to download.

Following is my script to download Japanese version of jdk8u121. The current script will only attempt to download but will fail on redirect. I'm using download.sh bash script to scan the log to get the url with session parameter and using wget to do the actual download.

You'll need to replace <username> and <password> with valid ones to login to Oracle site.

Change values of jdkTag and jdkFileLink to get the jdk version you want to download.

oraclejdk.js

var casper = require('casper').create({
  verbose: true,
  logLevel: 'info',  // debug
  pageSettings: {
    userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
    loadImages: false,
    loadPlugins: false
  }
});

// login info
var loginUrl='http://www.oracle.com/webapps/redirect/signon?nexturl=https://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html';
var username='<username>';
var password='<password>';

// accept license page info
var jdkUrl='http://www.oracle.com/technetwork/';
var jdkTag='jdk-8u121-oth-JPR';

// download jdk info
var jdkFileLink='jdk-8u121-oth-JPRXXXjdk-8u121-linux-x64.tar.gz';

// open login page
casper.start(loginUrl);

casper.thenEvaluate(function(username, password) {
//  this.capture('loginPage.png', {top:0, left:0, width:600, height:800});
    document.querySelector("#sso_username").value = username;
    document.querySelector("#ssopassword").value = password;
    doLogin(document.LoginForm);
}, {
     username: username,
     password: password
});

// login to oracle site
casper.then(function() {
  this.waitForUrl(jdkUrl, function() {
//    this.capture('jdkPage.png', {top:0, left:0, width:1200, height:800});
    this.evaluate(function(jdkTag) {
      disableDownloadAnchors(document, false, jdkTag);
      hideAgreementDiv(document, jdkTag);
      writeSessionCookie('oraclelicense', 'accept-securebackup-cookie');
    }, {
        jdkTag: jdkTag
    });
  }, null, null, 5000);
});

// accept license
casper.then(function() {
  this.waitFor(function checkLink() {
    return this.evaluate(function(jdkTag) {
      return (document.getElementById('agreementDiv' + jdkTag).getAttribute('style') === 'visibility: hidden;');
    }, {
        jdkTag: jdkTag
    });
  }, function then() {
//    this.capture('acceptedLicense.png', {top:0, left:0, width:1200, height:800});
    downlink = this.evaluate(function(jdkFileLink) {
      var jdkElement = document.getElementById(jdkFileLink);
      if (jdkElement) {
        var jdkLink = jdkElement.getAttribute("href");
        jdkElement.click();
        return jdkLink;
      }
    }, {
      jdkFileLink: jdkFileLink
    });
  }, null, 5000);
});

casper.run();

download.sh

#!/bin/bash

url=$(casperjs --web-security=no oraclejdk.js |grep "http://download.oracle.com/otn/java/jdk" $() | sed -e 's/^.*: //')
jdk=$(echo "${url}" | sed -e 's/^.*jdk-/jdk/' |sed -e 's/?.*//')
wget -O "${jdk}" "${url}"


问:
help figuring out math formula for performance gains
I'm trying to write a report to recommend moving transaction logs to a separate physical drive but I need to provide some numbers. I have some queries from a profile that was done last month. I'm trying to determine the reduction % of the duration. I know that it can't be 100% exact but a very close numbert will suffice.

Query 1
Reads: 325229284
Writes: 85989
Duration: 840732

Query 2
Reads: 558955611
Writes: 87066
Duration: 1015697

Query 3
Reads: 422966141
Writes: 85087
Duration: 918225

currently reads and writes happen on the same drive. I want to move them so reads are one drive and writes are another. I tried to figure it out assuming writes are 20% slower than reads but didn't average in seek times. I was getting between 7%-15% but have no idea if those figures are correct. Assuming drive seek time is avg 1ms.

答:
Thoughts:

The read/write correlation is usually nothing to do with logs. It's sorting in tempdb, spools etc.

You'd need one extra volume per database LDF: otherwise you still have massive head movement and many databases write to one volume

If you aren't using a SAN, then to do this you'll have less disks per volumes.

What could be beneficial is moving tempdb to separate volumes. SQL Server 2005+ really spank tempdb compared to older versions (eg triggers use tempdb rather than the logs)

MDF/LDF split is often for recovery: you can back up the tail of the log if the data volume fails

If a query has 422,966,141 reads then fix your code and indexes. A separate log drive is re-arranging deck chairs on the titanic.


问:
Office.js: Can I set the fill of a range of cells from a 2d array?
So far, with office.js, I'm getting used to this pattern, where you assign an array of data to a corresponding excel range:

```<code> range.values = [["Eurasia", "29.96", "0.25", "15-Feb" ]];
 range.numberFormat = [[null, null, null, "m/d/yyyy;@"]];
</code>```

However, I'm trying to change the background color of a range of cells using different colors in different cells and I already have a 2d array of colors which pertain to each cell.

As far as I can tell, it looks like you can assign the fill color by looping over every single cell one by one:

```<code>    var rowCount = selectionRange.values.length;
    var columnCount = selectionRange.values[0].length;
    for (var row = 0; row < rowCount; row++) {
        for (var column = 0; column < columnCount; column ++) {
            if (selectionRange.values[row][column] > 50) {
                selectionRange.getCell(row, column)
                    .format.fill.color = "yellow";
            }
        }
    }
</code>```

Or by assinging a single color to an entire range:

```<code>range.format.fill.color = "yellow";
</code>```

But I'm looking for something like:

```<code>range.fill = [["yellow", "red", "red", "white"]];
</code>```

It seems like there'd be an option similar to how you set values or numberFormat, but I haven't been able to find it.

Does this exist, or do I need to set it one by one?

答:
For the formatting properties (and basically, non-arrays), you do have to set one cell at a time.

We have an item on the backlog to allow array-like reading and setting of these properties, but we don't have them yet.  I'll bring it up again to the team, but it's not at the forefront of the queue.

Depending on the size of your array (and essentially, how many ranges you are creating inside of the one Excel.run call), there may be some perf implications.  If you run into issues there, let me know, and I can provide more info (I recommend opening a separate thread for it, though).

By the way, there are some fun samples of setting multiple formats at a time shown as snippet in Script Lab.

Body:
So far, with office.js, I'm getting used to this pattern, where you assign an array of data to a corresponding excel range:

 range.values = [["Eurasia", "29.96", "0.25", "15-Feb" ]];
 range.numberFormat = [[null, null, null, "m/d/yyyy;@"]];

However, I'm trying to change the background color of a range of cells using different colors in different cells and I already have a 2d array of colors which pertain to each cell.

As far as I can tell, it looks like you can assign the fill color by looping over every single cell one by one:

    var rowCount = selectionRange.values.length;
    var columnCount = selectionRange.values[0].length;
    for (var row = 0; row < rowCount; row++) {
        for (var column = 0; column < columnCount; column ++) {
            if (selectionRange.values[row][column] > 50) {
                selectionRange.getCell(row, column)
                    .format.fill.color = "yellow";
            }
        }
    }

Or by assinging a single color to an entire range:

range.format.fill.color = "yellow";

But I'm looking for something like:

range.fill = [["yellow", "red", "red", "white"]];

It seems like there'd be an option similar to how you set values or numberFormat, but I haven't been able to find it.

Does this exist, or do I need to set it one by one?


问:
Does it make sense to use a timestamp before saving or when saving to database
Question is pretty forward and it is bothering me for quite some time now. Perhaps any of you has an interesting view on this matter.

When creating an object lets say a memo.
This memo has a string (for the text obviously)
And a user id who has edited said text.

And this memo object is going to be saved to the database.

Is it common to add the current time to the object (eg. add a DateTime field / property) and save that object to db?

Or use the the current time of the database eg. when the row is inserted DateTime.Now in DB?

答: I feel it would not make much difference though it really depends on your requirement and project architecture. If you are interested in showing the time to user and you use some queue or background worker to insert row to DB (that is there could be some difference in time between creation of object and insertion into SQL), then it perhaps make sense to get the time at the time of creation of object. Else, if it only for record keeping then DB timestamp should be fine.</p>


问:
Prioritizing case in mysql
I want to prioritize the status part. Everything which is not repported should appear first. Regardless date. But now, It orders eveything after date. How can I prioritize the first case 'not repported part'? The rest of the list should appear after date.

```<code>SELECT * FROM list
        ORDER BY date DESC,
CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1
        WHEN day= 'Monday' THEN 2
        WHEN day= 'Tuesday' THEN 3
        WHEN day= 'Wednesday' THEN 4
        WHEN day= 'Thursdau' THEN 5
        WHEN day= 'Friday' THEN 6
        WHEN day= 'Saturday' THEN 7 WHEN
        day= 'Sunday' THEN 8 END ASC
        limit 1,20 ";
</code>```

I want something like this.

```<code>------------------------------
DATE----DAY-------STATUS------
2011---Monday-----Not reported
2015---Sunday-----Not reported
2010---Wednedday--Not reported
2016---Monday---------Reported
2015---Monday---------Reported
2014---Tuesday--------Reported
2013---Sunday---------Reported
------------------------------
</code>```

答:
You have two order statements. One for the date, and one for your booking status. Mysql will first order according to your first order statement, and then according to your second order statement. So switching the order statements solves your problem. In addition there is the "ELSE" keyword for "CASE"s in mysql.

In total I would write it like this:

```<code>SELECT *
FROM list
ORDER BY
    CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1
        ELSE 2
    END ASC,
    date DESC
LIMIT 1,20
</code>```

(Im not so sure where your "bookings" table now comes from, but I left it there. You might miss a JOIN clause)

Title: Prioritizing case in mysql

Body:
I want to prioritize the status part. Everything which is not repported should appear first. Regardless date. But now, It orders eveything after date. How can I prioritize the first case 'not repported part'? The rest of the list should appear after date.

SELECT * FROM list
        ORDER BY date DESC,
CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1
        WHEN day= 'Monday' THEN 2
        WHEN day= 'Tuesday' THEN 3
        WHEN day= 'Wednesday' THEN 4
        WHEN day= 'Thursdau' THEN 5
        WHEN day= 'Friday' THEN 6
        WHEN day= 'Saturday' THEN 7 WHEN
        day= 'Sunday' THEN 8 END ASC
        limit 1,20 ";

I want something like this.

------------------------------
DATE----DAY-------STATUS------
2011---Monday-----Not reported
2015---Sunday-----Not reported
2010---Wednedday--Not reported
2016---Monday---------Reported
2015---Monday---------Reported
2014---Tuesday--------Reported
2013---Sunday---------Reported
------------------------------

Body:
You have two order statements. One for the date, and one for your booking status. Mysql will first order according to your first order statement, and then according to your second order statement. So switching the order statements solves your problem. In addition there is the "ELSE" keyword for "CASE"s in mysql.

In total I would write it like this:

SELECT *
FROM list
ORDER BY
    CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1
        ELSE 2
    END ASC,
    date DESC
LIMIT 1,20

(Im not so sure where your "bookings" table now comes from, but I left it there. You might miss a JOIN clause)


答:
AWS will spin up a JVM and instantiate an instance of your code on the first request. AWS has an undocumented spin down time, where if you do not invoke your Lambda again within this time limit, it will shut down the JVM. You will notice these initial requests can take significantly longer but once your function is "warmed up", then it will be much quicker.

So to directly answer your question, your instance will be reused if the next request comes in quick enough. Otherwise, a new instance will be stood up.

A simple Lambda function that can illustrate this point:

```<code>/**
 * A Lambda handler to see where this runs and when instances are reused.
 */
public class LambdaStatus {

    private String hostname;
    private AtomicLong counter;

    public LambdaStatus() throws UnknownHostException {
        this.counter = new AtomicLong(0L);
        this.hostname = InetAddress.getLocalHost().getCanonicalHostName();
    }

    public void handle(Context context) {
        counter.getAndIncrement();
        context.getLogger().log("hostname=" + hostname + ",counter=" + counter.get());
    }
}
</code>```

Logs from invoking the above.

```<code>22:49:20   hostname=ip-10-12-169-156.ec2.internal,counter=1
22:49:27   hostname=ip-10-12-169-156.ec2.internal,counter=2
22:49:39   hostname=ip-10-12-169-156.ec2.internal,counter=3
01:19:05   hostname=ip-10-33-101-18.ec2.internal,counter=1
</code>```

Title: AWS Java Lambda local variables vs object variables

Body:
I am trying to find answer to a very specific question. Trying to go through documentation but so far no luck.

Imagine this piece of code

@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
    Request request = parseRequest(input);

    List<String> validationErrors = validate(request);

    if (validationErrors.size() == 0){
        ordersManager.getOrderStatusForStore(orderId, storeId);
    } else {
        generateBadRequestResponse(output, "Invalid Request", null);
    }
}

private List<String> validate(Request request) {
    orderId = request.getPathParameters().get(PATH_PARAM_ORDER_ID);
    programId = request.getPathParameters().get(PATH_PARAM_STORE_ID);
    return new ArrayList<>();
}

Here, I am storing orderId and storeId in field variables. Is this okay? I am not sure if AWS will cache this function and hence cache the field variables or would it initiate a new Java object for every request. If its a new object, then storing in field variable is fine but not sure.

Body:
AWS will spin up a JVM and instantiate an instance of your code on the first request. AWS has an undocumented spin down time, where if you do not invoke your Lambda again within this time limit, it will shut down the JVM. You will notice these initial requests can take significantly longer but once your function is "warmed up", then it will be much quicker.

So to directly answer your question, your instance will be reused if the next request comes in quick enough. Otherwise, a new instance will be stood up.

A simple Lambda function that can illustrate this point:

/**
 * A Lambda handler to see where this runs and when instances are reused.
 */
public class LambdaStatus {

    private String hostname;
    private AtomicLong counter;

    public LambdaStatus() throws UnknownHostException {
        this.counter = new AtomicLong(0L);
        this.hostname = InetAddress.getLocalHost().getCanonicalHostName();
    }

    public void handle(Context context) {
        counter.getAndIncrement();
        context.getLogger().log("hostname=" + hostname + ",counter=" + counter.get());
    }
}

Logs from invoking the above.

22:49:20   hostname=ip-10-12-169-156.ec2.internal,counter=1
22:49:27   hostname=ip-10-12-169-156.ec2.internal,counter=2
22:49:39   hostname=ip-10-12-169-156.ec2.internal,counter=3
01:19:05   hostname=ip-10-33-101-18.ec2.internal,counter=1


问:
Can't find palette tab in Android studio
I can't see palette tab in Android studio , here is image:  Any help please?

答: If you double click on your .xml file tab at the top it will maximize the designer window. Then on the left you can drag the window to shrink and it will reveal the palette. Then just click on the tab on the left to open the project window. The palette can be shrunk to 0 width.</p>


问:
.net cf - launch explorer programmatically
I am trying to launch explorer programmatically from my .Net CF Window application. But its throwing win32 exception. I have used same kind of code in desktop .Net version, and it always worked.
(I am using Windows CE 5 and .Net CF 3.5 )

Following code throws Win32 Exception,

```<code>Process.Start("\\", null);
</code>```

Unfortunately, I am using the code like this :-(

```<code>try
{ Process.Start("\\", null); }
catch { }
</code>```

答:
In order to kick off a web browser navigation to a URL, I have always directly set the argument of the Start method to the url itself. Please try the following to see if it helps in .NET CF"

Process.Start("http://www.yahoo.com", null);

i.e.

Process.Start([url_variable], null);

Body:
I am trying to launch explorer programmatically from my .Net CF Window application. But its throwing win32 exception. I have used same kind of code in desktop .Net version, and it always worked.
(I am using Windows CE 5 and .Net CF 3.5 )

Following code throws Win32 Exception,

Process.Start("\\", null);

Unfortunately, I am using the code like this :-(

try
{ Process.Start("\\", null); }
catch { }


问:
ios uisegmentedcontrol with different sizes
I wish use a uisegmentedcontrol in my app with 3 segments but not with the same size, the first and the third smaller than the second...
is this possible? how can I do this?
thanks</p>

答:
Try this code it helped me: </p>

```<code>segmentedControl.apportionsSegmentWidthsByContent = true
</code>```

Body:
Try this code it helped me:

segmentedControl.apportionsSegmentWidthsByContent = true


问:
How would someone connect their MLAB mongodb database to robomongo when MLAB only provides string URI's
I have been a mongochef user for a while, and setting up URI connections with mongochef is super easy. However this is not the case with robomongo.

How would someone connect their MLAB mongodb database to robobongo when MLAB uses string URI's to connect users to their databases?

in the configuration setup for robomongo it looks like it favors ip addresses and ports as the connection method and does not provide a URI format

答:
lets say you have following uri

```<code>mongodb://<dbuser>:<dbpassword>@ds111111.mlab.com:55191/<dbName>
</code>```

where dbuser and dbpassword are users for the database.

In robomongo, in the Connection tab enter following in the Address box:

```<code>ds111111.mlab.com
</code>```

and for the port box

```<code>55191
</code>```

Go to the Authentication tab. Click on 'Perform authentication'. Enter database name,  username,  and password . Let the auth mechanism be SCRAM-SHA-1

Here are some snapshots

Body:
lets say you have following uri

mongodb://<dbuser>:<dbpassword>@ds111111.mlab.com:55191/<dbName>

where dbuser and dbpassword are users for the database.

In robomongo, in the Connection tab enter following in the Address box:

ds111111.mlab.com

and for the port box

55191

Go to the Authentication tab. Click on 'Perform authentication'. Enter database name,  username,  and password . Let the auth mechanism be SCRAM-SHA-1

Here are some snapshots


问:
Can it be assumed that `pthread_cond_signal` will wake the signaled thread atomically with regards to the mutex bond to the condition variable?
Quoting POSIX:

The pthread_cond_broadcast() or pthread_cond_signal() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits; however, if predictable scheduling behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal().

"If predictable scheduling behavior is required". This could/would hint that locking the mutex bound to the condition variable right before calling pthread_cond_signal() should guarantee that the signaled thread will be woken up before any other thread manages to lock this mutex. Is this correct?

答:
No, there is no guarantee the signalled thread will be waken up. Worse, if in the signalling thread you have sequence:

```<code>while(run_again) {
    pthread_mutex_lock(&mutex);
    /* prepare data */
    pthread_mutex_unlock(&mutex);
    pthread_cond_broadcast(&cond);
}
</code>```

there is reasonable chance control would never be passed to other threads waiting on mutex because of logic in the scheduler. Some examples to play with you can find in this answer.

Body:
No, there is no guarantee the signalled thread will be waken up. Worse, if in the signalling thread you have sequence:

while(run_again) {
    pthread_mutex_lock(&mutex);
    /* prepare data */
    pthread_mutex_unlock(&mutex);
    pthread_cond_broadcast(&cond);
}

there is reasonable chance control would never be passed to other threads waiting on mutex because of logic in the scheduler. Some examples to play with you can find in this answer.


问:
Javascript class methods versus properties
I've seen code using Javascript classes use the following form (example is React):

```<code>class UserProfile extends Component {
  state = {
    open: false
  }

  handleOpen = () => {
    this.setState({ open: true })
  }
}
</code>```

Why is handleOpen implemented as a property which is set to a function instead of something like:

```<code>class UserProfile extends Component {
  state = {
    open: false
  }

  handleOpen() {
    this.setState({ open: true })
  }
}
</code>```

Thanks in advance!

答:
That's also a function, but it's called an arrow function and works slightly differently from the "traditional" implementation. It was introduced with ECMAScript 6.

Here's what the MDN docs says:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

One of the major benefits is that you wouldn't need to bind this to that function, because arrow functions do not have their own this object:

Until arrow functions, every new function defined its own this value

This guarantees scope safety; it's impossible to use the incorrect this by accident. It is arguably also slightly more readable.

A drawback however would be that arrow functions are anonymous, meaning that it would be harder to do a stack trace when you get an error in your code.But for React applications we can use devtool:'cheap-module-eval-source-map' from babel to easily find bugs in our stack trace.

Body:
I've seen code using Javascript classes use the following form (example is React):

class UserProfile extends Component {
  state = {
    open: false
  }

  handleOpen = () => {
    this.setState({ open: true })
  }
}

Why is handleOpen implemented as a property which is set to a function instead of something like:

class UserProfile extends Component {
  state = {
    open: false
  }

  handleOpen() {
    this.setState({ open: true })
  }
}

Thanks in advance!

ContentLicense: CC BY-SA 4.0


问:
Run lagged regressions for finance data
I am trying to run lagged regression for each of the 30 assets in my data frame.

My table looks like this:

```<code> date          rx1   rx2   rx3
    1930-01-31  0     0     0
    1930-02-28  0     0    -0.3
    1930-03-31  0     0    -0.1
    ....              -0.1  ...
    1975-02-28  -0.4  -0.2  ...
    2016-12-31  -0.03  ...  ...
</code>```

Then I tried to run lagged regressions with this line(dataframe:Rx3.df):

```<code>model <- dyn$lm(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1, 2))
</code>```

But I kept getting this result that does not make any sense:

```<code>Call:
lm(formula = dyn(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1,
    2)))

Coefficients:
       (Intercept)  lag(Rx3.df$rx1, 1)  lag(Rx3.df$rx1, 2)
         3.297e-16           1.000e+00                  NA
</code>```

Can anyone figure out the problem? Thanks!

答:
It looks like your time series is not being lagged at all. That is also why you get a coefficient of 1 for the first regressor.

To solve your problem you can either use the lag / lead functions of the dplyr package (depends on the format of your data):

```<code>> library(dplyr)
> x <- 1:10
> stats::lag(x)
[1]  1  2  3  4  5  6  7  8  9 10
attr(,"tsp")
[1] 0 9 1
> dplyr::lead(x)
[1]  2  3  4  5  6  7  8  9 10 NA
> dplyr::lag(x)
[1] NA  1  2  3  4  5  6  7  8  9
</code>```

or the lag function for a zoo time series:

```<code>> library(zoo)
> y <- zoo(1:10)
> stats::lag(y, 1, na.pad = TRUE)
 1  2  3  4  5  6  7  8  9 10
 2  3  4  5  6  7  8  9 10 NA
> stats::lag(y, -1,  na.pad = TRUE)
 1  2  3  4  5  6  7  8  9 10
NA  1  2  3  4  5  6  7  8  9
</code>```

Title: Run lagged regressions for finance data

Body:
I am trying to run lagged regression for each of the 30 assets in my data frame.

My table looks like this:

 date          rx1   rx2   rx3
    1930-01-31  0     0     0
    1930-02-28  0     0    -0.3
    1930-03-31  0     0    -0.1
    ....              -0.1  ...
    1975-02-28  -0.4  -0.2  ...
    2016-12-31  -0.03  ...  ...

Then I tried to run lagged regressions with this line(dataframe:Rx3.df):

model <- dyn$lm(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1, 2))

But I kept getting this result that does not make any sense:

Call:
lm(formula = dyn(Rx3.df$rx1 ~ lag(Rx3.df$rx1, 1) + lag(Rx3.df$rx1,
    2)))

Coefficients:
       (Intercept)  lag(Rx3.df$rx1, 1)  lag(Rx3.df$rx1, 2)
         3.297e-16           1.000e+00                  NA

Can anyone figure out the problem? Thanks!

Body:
It looks like your time series is not being lagged at all. That is also why you get a coefficient of 1 for the first regressor.

To solve your problem you can either use the lag / lead functions of the dplyr package (depends on the format of your data):

> library(dplyr)
> x <- 1:10
> stats::lag(x)
[1]  1  2  3  4  5  6  7  8  9 10
attr(,"tsp")
[1] 0 9 1
> dplyr::lead(x)
[1]  2  3  4  5  6  7  8  9 10 NA
> dplyr::lag(x)
[1] NA  1  2  3  4  5  6  7  8  9

or the lag function for a zoo time series:

> library(zoo)
> y <- zoo(1:10)
> stats::lag(y, 1, na.pad = TRUE)
 1  2  3  4  5  6  7  8  9 10
 2  3  4  5  6  7  8  9 10 NA
> stats::lag(y, -1,  na.pad = TRUE)
 1  2  3  4  5  6  7  8  9 10
NA  1  2  3  4  5  6  7  8  9


问:
Wordpress Issue with Walker Class
What does an Illegal offset type in isset or empty, I have never ran into this error message before? Could you explain this message to me, please?

Have also place code that learning how to do in here the reviews

```<code>  <?php
  if (has_nav_menu('primary_navigation')) :
    wp_nav_menu( array(
      'theme_location' => 'primary_navigation',
      'menu_class' => 'menu',
      'menu_class' => 'mobile-menu',
      'walker' => new  Walker_Nav_Primary (),
      )
    );
  endif;
  ?>

class Walker_Nav_Primary extends Walker {
  function start_lvl( &$output, $depth = 0, $args = array() ) { //ul
    $indent = str_repeat("\t",$depth);
    $submenu = ($depth > 0) ? ' sub-menu' : '';
    $output .= "\n$indent<ul class=\"fallback$submenu depth_$depth\">\n";
  }
</code>```

Warning: Illegal offset type in isset or empty in /Users/brandonpowell/sites/valet/wordpress-development/web/wp/wp-includes/class-wp-walker.php on line 140

答:
This error happen when you use Walker instead of Walker_Nav_Menu in extends. You should use this instead:

```<code>class Walker_Nav_Primary extends Walker_Nav_Menu {
</code>```

Walker_Nav_Menu heritate itself of Walker class, and provide the proper properties / methods for your own walker class.

Title: Wordpress Issue with Walker Class

Body:
What does an Illegal offset type in isset or empty, I have never ran into this error message before? Could you explain this message to me, please?

Have also place code that learning how to do in here the reviews

  <?php
  if (has_nav_menu('primary_navigation')) :
    wp_nav_menu( array(
      'theme_location' => 'primary_navigation',
      'menu_class' => 'menu',
      'menu_class' => 'mobile-menu',
      'walker' => new  Walker_Nav_Primary (),
      )
    );
  endif;
  ?>

class Walker_Nav_Primary extends Walker {
  function start_lvl( &$output, $depth = 0, $args = array() ) { //ul
    $indent = str_repeat("\t",$depth);
    $submenu = ($depth > 0) ? ' sub-menu' : '';
    $output .= "\n$indent
\n";
  }

Warning: Illegal offset type in isset or empty in /Users/brandonpowell/sites/valet/wordpress-development/web/wp/wp-includes/class-wp-walker.php on line 140

Body:
This error happen when you use Walker instead of Walker_Nav_Menu in extends. You should use this instead:

class Walker_Nav_Primary extends Walker_Nav_Menu {

Walker_Nav_Menu heritate itself of Walker class, and provide the proper properties / methods for your own walker class.


问:
Agile testing / traditional testing methods
What are the agile testing methods? And what are the traditional testing methods?</p>

答:
I am not shure if there are any "testmethods" that are special to agile.

Of course there is "testdriven" (tdd) and "behaviordriven" (bdd) development but i donot see these as "testing methods".

Unittests are not special to agile or traditional.

As @khachik mentioned it: there is offen a huge difference when (in the develpment process) the tests are desigend and applied.

Traditional = Waterfall or V-Modell: Test are done in the end (if at all)

Agile : Test should be written before the code is written.


问:
How to detect vertical planes in ARKit?
How is it possible to implement a vertical plane detection (i.e. for walls)?</p>

```<code>let configuration = ARWorldTrackingSessionConfiguration()
configuration.planeDetection = .horizontal //TODO
</code>```

答:
Edit: This is now supported as of ARKit 1.5 (iOS 11.3). Simply use .vertical. I have kept the previous post below for historical purposes.

TL;DR

Vertical plane detection is not (yet) a feature that exists in ARKit. The .horizontal suggests that this feature could be being worked on and might be added in the future. If it was just a Boolean value, this would suggest that it is final.

Confirmation

This suspicion was confirmed by a conversation that I had with an Apple engineer at WWDC17.

Explanation

You could argue that creating an implementation for this would be difficult as there are infinitely many more orientations for a vertical plane rather than a horizontal one, but as rodamn said, this is probably not the case.

From rodamn’s comment:
At its simplest, a plane is defined to be three coplanar points. You have a surface candidate once there are sufficient detected coplanar features detected along a surface (vertical, horizontal, or at any arbitrary angle). It's just that the normal for horizontals will be along the up/down axis, while vertical's normals will be parallel to the ground plane. The challenge is that unadorned drywall tends to generate few visual features, and plain walls may often go undetected. I strongly suspect that this is why the .vertical feature is not yet released.

However, there is a counter argument to this. See comments from rickster for more information.

Title: How to detect vertical planes in ARKit?

Body:
How is it possible to implement a vertical plane detection (i.e. for walls)?

let configuration = ARWorldTrackingSessionConfiguration()
configuration.planeDetection = .horizontal //TODO


问:
Missing Carriage Return in Docker for Mac Containers
All of a sudden all of my docker/docker-compose exec/run commands are printing logs that are lacking a carriage return making command line impossible to read due to indentation (see photos below).

I re-installed docker to factory settings, but that didn't fix anything.

where else should I look to solve this sort of problem?

Update
This is an active issue in docker-for-mac.

I just updated to 17.06.0-rc1-ce-mac13 and that is when I started having the problems.

Also, can you leave a comment if you are voting to close?

答:
As mentioned above this is a defect in the Edge version of Docker for OSX:

Version 17.06.0-rc1-ce-mac13 (18169)
  Channel: edge

If you unintentionally selected the edge channel, or no longer need its bleeding edge features simply switch back to the stable channel.

Go to Docker -> Preferences and at the bottom it should say "The is an edge version. You can switch to stable".

Click stable then select OK in the dialog that pops up next.

Download the stable .dmg file from https://download.docker.com/mac/stable/Docker.dmg

Quit your running docker

Open the dmg file

Select if you want to replace the current edge docker or replace it

Open Docker with Finder - it will tell you it is going to uninstall the beta version and restart the app with a warning that you will lose your containers and settings.

Press Continue and Restart and complete the installation

Welcome back from the edge!

You are now back to the stable channel and stable version of Docker.

Be prepared to rebuild all your containers before you can use them again.

Share and enjoy!


问:
Selecting different columns with VBA
I have a worksheet with 22 columns of data and I need to copy and paste the first column and individual columns starting at column 3 to new worksheets in the same workbook.  For example, I would select column A and column C and copy those two columns to a new worksheet.  Then, I would go back to the initial worksheet and select column A and column D and copy just those two columns to a new worksheet, etc.

The code below iterates over all of the columns but it always selects a continuous range instead of just column A and the next column in the series.  My initial code is below:

```<code>Sub CashFlowColumnTabSplit()

ActiveSheet.Name = "Main"

For i = 3 To 22
    Range(Columns(1), Columns(i)).Select
    Selection.Copy
    Sheets.Add After:=ActiveSheet
    Range("A1").Select
    ActiveSheet.Paste
    Sheets("Main").Select
Next i

End Sub
</code>```

答:
Try:</p>

```<code>Sub CashFlowColumnTabSplit()
Dim Source_Sheet As Worksheet
Dim Target_Sheet As Worksheet
Dim i As Long

    Set Source_Sheet = ThisWorkbook.Sheets("Main")

    For i = 3 To 22
        Set Target_Sheet = ThisWorkbook.Sheets.Add(After:=Source_Sheet)
        Application.Union(Source_Sheet.Columns(1), Source_Sheet.Columns(i)).Copy
        Target_Sheet.Range("A1").PasteSpecial xlPasteAll
    Next i

End Sub
</code>```

Title: Selecting different columns with VBA

Body:
I have a worksheet with 22 columns of data and I need to copy and paste the first column and individual columns starting at column 3 to new worksheets in the same workbook.  For example, I would select column A and column C and copy those two columns to a new worksheet.  Then, I would go back to the initial worksheet and select column A and column D and copy just those two columns to a new worksheet, etc.

The code below iterates over all of the columns but it always selects a continuous range instead of just column A and the next column in the series.  My initial code is below:

Sub CashFlowColumnTabSplit()

ActiveSheet.Name = "Main"

For i = 3 To 22
    Range(Columns(1), Columns(i)).Select
    Selection.Copy
    Sheets.Add After:=ActiveSheet
    Range("A1").Select
    ActiveSheet.Paste
    Sheets("Main").Select
Next i

End Sub

Body:
Try:

Sub CashFlowColumnTabSplit()
Dim Source_Sheet As Worksheet
Dim Target_Sheet As Worksheet
Dim i As Long

    Set Source_Sheet = ThisWorkbook.Sheets("Main")

    For i = 3 To 22
        Set Target_Sheet = ThisWorkbook.Sheets.Add(After:=Source_Sheet)
        Application.Union(Source_Sheet.Columns(1), Source_Sheet.Columns(i)).Copy
        Target_Sheet.Range("A1").PasteSpecial xlPasteAll
    Next i

End Sub


问:
azure service fabric vsts release (deployment) error Application type of application '' doesn't match the application type
Getting this error:

Application type of application '' doesn't match the application type in the application manifest of the new application package. Please ensure that the application being upgraded has the same application type.

My application is small and contains only 2 services. If I deploy manually from Visual Studio 2017 it's working fine. But when I deploy from a successful build in VSTS I'm getting the above error. I used the same publish profile both in manual and vsts release.

Any idea?

Additional details from the logs:

2017-06-06T16:00:59.2449160Z ##[debug]INPUT_OVERRIDEPUBLISHPROFILESETTINGS: 'false'
2017-06-06T16:01:00.9096138Z ##[debug]Join-Path "C:\Program Files\Microsoft Service Fabric\bin\fabric\fabric.code" "ServiceFabricServiceModel.xsd"
2017-06-06T16:01:00.9146136Z ##[debug]C:\Program Files\Microsoft Service Fabric\bin\fabric\fabric.code\ServiceFabricServiceModel.xsd
2017-06-06T16:01:00.9156210Z ##[debug]Length: 94
2017-06-06T16:01:00.9166135Z ##[debug]
2017-06-06T16:01:00.9186137Z ##[debug]Test-Path "C:\Program Files\Microsoft Service Fabric\bin\fabric\fabric.code\ServiceFabricServiceModel.xsd"
2017-06-06T16:01:00.9216373Z ##[debug]True
2017-06-06T16:01:00.9226141Z ##[debug]
2017-06-06T16:01:03.5668693Z ##[debug]Leaving D:\a\_tasks\ServiceFabricDeploy_c6650aa0-185b-11e6-a47d-df93e7a34c64\1.3.9\deploy.ps1.
2017-06-06T16:01:03.5767636Z ##[debug]Caught exception from task script.
2017-06-06T16:01:03.5787644Z ##[debug]Error record:
2017-06-06T16:01:03.6307491Z ##[debug]Application type of application '' doesn't match the application type in the application manifest of the new application package. Please ensure that the application being upgraded has the same application type.
2017-06-06T16:01:03.6317836Z ##[debug]At D:\a\_tasks\ServiceFabricDeploy_c6650aa0-185b-11e6-a47d-df93e7a34c64\1.3.9\ServiceFabricSDK\Publish-UpgradedServiceFabricApplication.ps1:195 char:17
2017-06-06T16:01:03.6329753Z ##[debug]+                 throw $errMsg
2017-06-06T16:01:03.6338786Z ##[debug]+                 ~~~~~~~~~~~~~
2017-06-06T16:01:03.6350377Z ##[debug]    + CategoryInfo          : OperationStopped: (Application typ...plication type.:String) [], RuntimeException
2017-06-06T16:01:03.6360412Z ##[debug]    + FullyQualifiedErrorId : Application type of application '' doesn't match the application type in the application     manifest of the new application package. Please ensure that the application being upgraded has the same applicati    on type.
2017-06-06T16:01:03.6370408Z ##[debug]
2017-06-06T16:01:03.6380417Z ##[debug]Script stack trace:
2017-06-06T16:01:03.6410418Z ##[debug]at Publish-UpgradedServiceFabricApplication, D:\a\_tasks\ServiceFabricDeploy_c6650aa0-185b-11e6-a47d-df93e7a34c64\1.3.9\ServiceFabricSDK\Publish-UpgradedServiceFabricApplication.ps1: line 195
2017-06-06T16:01:03.6420417Z ##[debug]at

答: I found the root cause and it's so silly. It's really easy to missed this as you can't see the whole textbox values in vsts unless you drag your mouse up to the end. The parameters is also pointing to publish profiles which is wrong and I corrected that.


问:
How to prevent pathlib’s Path.glob from returning files when the glob ends in a slash?
The the new Path.glob from pathlib seems to behave differently from the old glob.glob when the glob pattern ends in a slash it seems.

```<code>In [1]: from pathlib import Path

In [2]: from glob import glob

In [3]: glob('webroot/*/')
Out[3]: ['webroot/2017-06-07/']

In [4]: list(Path().glob('webroot/*/'))
Out[4]:
[PosixPath('webroot/.keep'),
 PosixPath('webroot/2017-06-07'),
 PosixPath('webroot/matches.2017-06-07.json')]
</code>```

Is that by design, some compatibility issue I haven’t encountered? And is there a way to stop it from doing that?

For now I’ll work around it with:

```<code>[path for path in Path().glob('webroot/*/') if path.is_dir()]
</code>```

答:
There's an open bug about this:

https://bugs.python.org/issue22276

No resolution yet.

Your workaround looks fine, although if you don't mind also including the 'webroot' directory itself you may prefer using a ** glob:

```<code>>>> list(Path('webroot').glob('**'))
[PosixPath('webroot'), PosixPath('webroot/2017-06-07')]
</code>```

Body:
The the new Path.glob from pathlib seems to behave differently from the old glob.glob when the glob pattern ends in a slash it seems.

In [1]: from pathlib import Path

In [2]: from glob import glob

In [3]: glob('webroot/*/')
Out[3]: ['webroot/2017-06-07/']

In [4]: list(Path().glob('webroot/*/'))
Out[4]:
[PosixPath('webroot/.keep'),
 PosixPath('webroot/2017-06-07'),
 PosixPath('webroot/matches.2017-06-07.json')]

Is that by design, some compatibility issue I haven’t encountered? And is there a way to stop it from doing that?

For now I’ll work around it with:

[path for path in Path().glob('webroot/*/') if path.is_dir()]

Body:
There's an open bug about this:

https://bugs.python.org/issue22276

No resolution yet.

Your workaround looks fine, although if you don't mind also including the 'webroot' directory itself you may prefer using a ** glob:

>>> list(Path('webroot').glob('**'))
[PosixPath('webroot'), PosixPath('webroot/2017-06-07')]


问:
Git stash silently hides/deletes staged changes
Problem:

```<code>$ git status -s
MM myfile
$ git stash save
$ git show stash@{0}
# Only shows unstaged changes NOT staged changes

# To debug:
$ GIT_TRACE=2 git stash show
trace: exec: 'git-stash' 'show'
trace: run_command: 'git-stash' 'show'
trace: built-in: git 'rev-parse' '--git-dir'
trace: built-in: git 'rev-parse' '--show-toplevel'
trace: built-in: git 'config' '--get-colorbool' 'color.interactive'
trace: built-in: git 'config' '--get-color' 'color.interactive.help' 'red bold'
trace: built-in: git 'config' '--get-color' '' 'reset'
trace: built-in: git 'rev-parse' '--no-flags' '--symbolic' '--sq'
trace: built-in: git 'rev-parse' '--symbolic-full-name' 'refs/stash'
trace: built-in: git 'diff' '--stat' 'aaaa' 'bbbb'
trace: run_command: 'pager'
trace: exec: 'pager'
$ git diff --stat aaaa bbbb
# Shows both staged and unstaged changes
$ git stash apply --index
$ git status -s
MM myfile
</code>```

Why doesn't git show stash@{0} not show the staged changes that were supposed to be part of the stash? It appears that git-stash is silently hiding the staged changes in a stash.

答:
This is because git show stash@{0} is is the wrong command.  You want git stash show stash@{0}.

Unfortunately for stash usage, git show is a perfectly good command, and when you ask it to show a merge commit, it shows a combined diff.  And, internally, stash commits have the form (but not the normal substance) of a merge commit, so that a combined diff is rarely any good at all—so git show is happy to show them, but shows them as empty.

Since git stash show is really easy to typo/think-o as git show stash, you get very bad behavior.  Just remember that when you see nothing, it may be a case of inverted word order.

(It's also worth noting here that git stash show compares the stashed work-tree against the stash's parent.  There is no git stash command to show the stashed index vs anything.  To see the index vs the parent, use git diff stash@{number}^1 stash@{number}^2.)

Body:
Problem:

$ git status -s
MM myfile
$ git stash save
$ git show stash@{0}
# Only shows unstaged changes NOT staged changes

# To debug:
$ GIT_TRACE=2 git stash show
trace: exec: 'git-stash' 'show'
trace: run_command: 'git-stash' 'show'
trace: built-in: git 'rev-parse' '--git-dir'
trace: built-in: git 'rev-parse' '--show-toplevel'
trace: built-in: git 'config' '--get-colorbool' 'color.interactive'
trace: built-in: git 'config' '--get-color' 'color.interactive.help' 'red bold'
trace: built-in: git 'config' '--get-color' '' 'reset'
trace: built-in: git 'rev-parse' '--no-flags' '--symbolic' '--sq'
trace: built-in: git 'rev-parse' '--symbolic-full-name' 'refs/stash'
trace: built-in: git 'diff' '--stat' 'aaaa' 'bbbb'
trace: run_command: 'pager'
trace: exec: 'pager'
$ git diff --stat aaaa bbbb
# Shows both staged and unstaged changes
$ git stash apply --index
$ git status -s
MM myfile

Why doesn't git show stash@{0} not show the staged changes that were supposed to be part of the stash? It appears that git-stash is silently hiding the staged changes in a stash.


问:
converting this hierachy into xml? confused
i havent really worked with xml before, but i was wondering how could turn this hierachy into an xml format, if that makes sense :)) thanks</p>

```<code>agent
       agentname
       email
       allproperty
         aproperty
               postcode
               price
               imagefilename
               visits
        aproperty
               postcode
               price
               imagefilename
               visits
       aproperty
               postcode
               price
              imagefilename
              visits
</code>```

答:
Can't you do a thing like this?</p>

```<code><agent>
    <name>agentName</name>
    <email>agentEmail</email>
    <properties>
        <property>
            <postcode>myPostcode</postcode>
            ...
        </property>
        ...
    </properties>
</agent>
</code>```

Body:
i havent really worked with xml before, but i was wondering how could turn this hierachy into an xml format, if that makes sense :)) thanks

agent
       agentname
       email
       allproperty
         aproperty
               postcode
               price
               imagefilename
               visits
        aproperty
               postcode
               price
               imagefilename
               visits
       aproperty
               postcode
               price
              imagefilename
              visits

Body:
Can't you do a thing like this?

<agent>
    <name>agentName</name>
    <email>agentEmail</email>
    <properties>
        <property>
            <postcode>myPostcode</postcode>
            ...
        </property>
        ...
    </properties>
</agent>


答:
It's about the context of this inside of your method. If you would implement it like your second example, this won't reference the component instance, using the arrow function like in your first example this references the component instance. (Due to not using React.createClass).

For your second example you have to do this.handleOpen = this.handleOpen.bind(this) inside your constructor.

EDIT: For details about arrow functions see the answer from Chris.

Title: Javascript class methods versus properties