问:
getaddrinfo: nodename nor servname provided, or not known
I have a Ruby on Rails application that I am deploying on a computer running Mac OS X 10.6. The code where the problem arises is run by a delayed_job. The problem only occurs when it is run through delayed_job. If I run it within a console (rails console production) or call the API directly through cURL, it works without any problems. Also, the entire process works without issue in my development environment.

Basically, the code works in one place, but for some reason, fails where it has to work. I've searched and found a few resources, but none of the suggestions apply or make any difference. When I log into the server and run the commands, everything works. But for some reason when they are run/started by Capistrano, it doesn't work.

Any help is greatly appreciated.

Important notes:

Ruby version: 1.9.2-p0

Rails version: 3.0.1

delayed_job version: latest (from collectiveidea/delayed_job)

rest-client version: 1.6.1

Code:

```<code>class CallApi < Struct.new(:num)
  def perform
    log "Entering perform"
    apinum = num || 5
    log "ApiNum = #{apinum}"
    results = attempt(2,10) do
      ActiveSupport::JSON.decode(RestClient.get(API_URL, {:params => {:apinum => apinum}}))
    end
    log "Results retrieved. (count: #{results.count})"
  end

  def log(message)
    Delayed::Worker.logger.info "[CallApi] #{Time.now} - #{message}"
  end
end
</code>```

Environment Config (note: the url is fake, but of the same form as the real one):

```<code>API_URL = "http://api.example.org/api_endpoint"
# Originally, I had "http://" before the beginning, but found a
# post mentioning that Net::Http.start didn't like that.
# So I tried it both ways.
# The same error occurs regardless of if the "http://" is there.
</code>```

Call where the error happens:

```<code>RestClient.get(API_URL, {:params => {:apinum => apinum}})
</code>```

Error:

```<code>getaddrinfo: nodename nor servname provided, or not known
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `initialize'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `open'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `block in connect'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/timeout.rb:44:in `timeout'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/timeout.rb:87:in `timeout'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `connect'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:626:in `start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient/request.rb:166:in `transmit'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient/request.rb:60:in `execute'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient/request.rb:31:in `execute'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient.rb:68:in `get'
/private/var/www/project-gemset/releases/20101109002137/lib/call_api.rb:7:in `block in perform'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/attempt-0.2.0/lib/attempt.rb:70:in `attempt'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/attempt-0.2.0/lib/attempt.rb:114:in `attempt'
/private/var/www/project-gemset/releases/20101109002137/lib/call_api.rb:6:in `perform'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/backend/base.rb:77:in `invoke_job'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:118:in `block (2 levels) in run'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/timeout.rb:57:in `timeout'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:118:in `block in run'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/benchmark.rb:309:in `realtime'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:117:in `run'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:176:in `reserve_and_run_one_job'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:102:in `block in work_off'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:101:in `times'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:101:in `work_off'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:76:in `block (2 levels) in start'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/benchmark.rb:309:in `realtime'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:75:in `block in start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:72:in `loop'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:72:in `start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:100:in `run'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:79:in `block in run_process'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:250:in `call'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:250:in `block in start_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/daemonize.rb:199:in `call'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/daemonize.rb:199:in `call_as_daemon'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:254:in `start_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:294:in `start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:159:in `block (2 levels) in start_all'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:158:in `fork'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:158:in `block in start_all'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:157:in `each'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:157:in `start_all'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/controller.rb:80:in `run'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons.rb:193:in `block in run_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/cmdline.rb:112:in `call'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/cmdline.rb:112:in `catch_exceptions'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons.rb:192:in `run_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:78:in `run_process'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:72:in `block in daemonize'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:70:in `times'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:70:in `daemonize'
script/delayed_job:5:in `'
</code>```

答:
I got the same error when I check the localhost is set in hosts file it is somehow not set. Setting localhost to 127.0.0.1 solved it.</p>

```<code>sudo vi /etc/hosts
>>

127.0.0.1       localhost
</code>```

Body:
I have a Ruby on Rails application that I am deploying on a computer running Mac OS X 10.6. The code where the problem arises is run by a delayed_job. The problem only occurs when it is run through delayed_job. If I run it within a console (rails console production) or call the API directly through cURL, it works without any problems. Also, the entire process works without issue in my development environment.

Basically, the code works in one place, but for some reason, fails where it has to work. I've searched and found a few resources, but none of the suggestions apply or make any difference. When I log into the server and run the commands, everything works. But for some reason when they are run/started by Capistrano, it doesn't work.

Any help is greatly appreciated.

Important notes:

Ruby version: 1.9.2-p0

Rails version: 3.0.1

delayed_job version: latest (from collectiveidea/delayed_job)

rest-client version: 1.6.1

Code:

class CallApi < Struct.new(:num)
  def perform
    log "Entering perform"
    apinum = num || 5
    log "ApiNum = #{apinum}"
    results = attempt(2,10) do
      ActiveSupport::JSON.decode(RestClient.get(API_URL, {:params => {:apinum => apinum}}))
    end
    log "Results retrieved. (count: #{results.count})"
  end

  def log(message)
    Delayed::Worker.logger.info "[CallApi] #{Time.now} - #{message}"
  end
end

Environment Config (note: the url is fake, but of the same form as the real one):

API_URL = "http://api.example.org/api_endpoint"
# Originally, I had "http://" before the beginning, but found a
# post mentioning that Net::Http.start didn't like that.
# So I tried it both ways.
# The same error occurs regardless of if the "http://" is there.

Call where the error happens:

RestClient.get(API_URL, {:params => {:apinum => apinum}})

Error:

getaddrinfo: nodename nor servname provided, or not known
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `initialize'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `open'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `block in connect'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/timeout.rb:44:in `timeout'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/timeout.rb:87:in `timeout'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:644:in `connect'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/net/http.rb:626:in `start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient/request.rb:166:in `transmit'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient/request.rb:60:in `execute'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient/request.rb:31:in `execute'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/rest-client-1.6.1/lib/restclient.rb:68:in `get'
/private/var/www/project-gemset/releases/20101109002137/lib/call_api.rb:7:in `block in perform'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/attempt-0.2.0/lib/attempt.rb:70:in `attempt'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/attempt-0.2.0/lib/attempt.rb:114:in `attempt'
/private/var/www/project-gemset/releases/20101109002137/lib/call_api.rb:6:in `perform'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/backend/base.rb:77:in `invoke_job'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:118:in `block (2 levels) in run'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/timeout.rb:57:in `timeout'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:118:in `block in run'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/benchmark.rb:309:in `realtime'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:117:in `run'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:176:in `reserve_and_run_one_job'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:102:in `block in work_off'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:101:in `times'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:101:in `work_off'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:76:in `block (2 levels) in start'
/Users/api/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/benchmark.rb:309:in `realtime'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:75:in `block in start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:72:in `loop'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/worker.rb:72:in `start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:100:in `run'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:79:in `block in run_process'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:250:in `call'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:250:in `block in start_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/daemonize.rb:199:in `call'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/daemonize.rb:199:in `call_as_daemon'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:254:in `start_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application.rb:294:in `start'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:159:in `block (2 levels) in start_all'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:158:in `fork'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:158:in `block in start_all'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:157:in `each'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/application_group.rb:157:in `start_all'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/controller.rb:80:in `run'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons.rb:193:in `block in run_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/cmdline.rb:112:in `call'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons/cmdline.rb:112:in `catch_exceptions'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/gems/daemons-1.1.0/lib/daemons.rb:192:in `run_proc'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:78:in `run_process'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:72:in `block in daemonize'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:70:in `times'
/Users/api/.rvm/gems/ruby-1.9.2-p0@project-gemset/bundler/gems/delayed_job-aba9905764c2/lib/delayed/command.rb:70:in `daemonize'
script/delayed_job:5:in `'

Body:
I got the same error when I check the localhost is set in hosts file it is somehow not set. Setting localhost to 127.0.0.1 solved it.

sudo vi /etc/hosts
>>

127.0.0.1       localhost


来源: stackexchange

问:
Yii2 Gii : Add autocomplete and class name generation to custom template
I recently began creating my own Gii templates, in this case, for CRUD.

Now I noticed, when creating a Model with Gii you have an autocomplete for the table name and, after this is selected, the Model class name is automatically generated as well.

How do I implement this behavior for my CRUD templates as well? I have already created a custom CRUD generator for my template:

```<code>namespace app\templates\gii\crud\custom;

class Generator extends \yii\gii\generators\crud\Generator
{
    // ...
}
</code>```

What do I have to include to:

Include autocomplete to select an existing Model class to create the CRUD operations for

Automatically generate the SearchModel name based on the previously selected Model class (e.g. app\model\CategoryModel becomes app\model\CategorySearchModel)

答: If create only template, do not need extend generator. You can use same Gii generator. Only need in config attach to gii your template.  Creating templates described in: https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/topics-creating-your-own-templates.md</p>

ContentLicense: CC BY-SA 3.0

Body:
I recently began creating my own Gii templates, in this case, for CRUD.

Now I noticed, when creating a Model with Gii you have an autocomplete for the table name and, after this is selected, the Model class name is automatically generated as well.

How do I implement this behavior for my CRUD templates as well? I have already created a custom CRUD generator for my template:

namespace app\templates\gii\crud\custom;

class Generator extends \yii\gii\generators\crud\Generator
{
    // ...
}

What do I have to include to:

Include autocomplete to select an existing Model class to create the CRUD operations for

Automatically generate the SearchModel name based on the previously selected Model class (e.g. app\model\CategoryModel becomes app\model\CategorySearchModel)


问:
Deep Link Kit regex for zero or more
I am trying to use Deep Link Kit to route both of these paths:

```<code>myapp://page/2        // <- doesn't work
myapp://page/2/7      //<- works
</code>```

The route handler I've registered at the moment is:

```<code>router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number/:commentID(.*)")
</code>```

I added the (.*) for the regex of zero or more comment IDs. However this doesn't seem to make any difference as it only works when you have both the :number and :commentID defined. I've also tried myapp://page/2/ but that doesn't work either. Any help would be appreciated.

UPDATE

One solution is to register the two routes separately:

```<code>router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number")
router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number/:commentID")
</code>```

but ideally, I'd be able to use regex.

答:
I counter this problem too, after combine you solution I came up with this solution

```<code>router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number/?:commentID(.*)")
</code>```

That will ignore the second /, and your commentID will be set with empty string

Title: Deep Link Kit regex for zero or more

Body:
I am trying to use Deep Link Kit to route both of these paths:

myapp://page/2        // <- doesn't work
myapp://page/2/7      //<- works

The route handler I've registered at the moment is:

router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number/:commentID(.*)")

I added the (.*) for the regex of zero or more comment IDs. However this doesn't seem to make any difference as it only works when you have both the :number and :commentID defined. I've also tried myapp://page/2/ but that doesn't work either. Any help would be appreciated.

UPDATE

One solution is to register the two routes separately:

router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number")
router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number/:commentID")

but ideally, I'd be able to use regex.

Body:
I counter this problem too, after combine you solution I came up with this solution

router.registerHandlerClass(AppRouteHandler.self, forRoute: "page/:number/?:commentID(.*)")

That will ignore the second /, and your commentID will be set with empty string


答:
I use the following pattern to convert query variables from  to an object containing key:value pairs. Code is placed at the top of script.js:

    var getVars = {};

    (function(){
        var scripts, currentScript, queryString;

        scripts = document.getElementsByTagName('script');
        currentScript = scripts[ scripts.length - 1 ];
        queryString = currentScript.getAttribute('src').split("?").pop().split('&');
        for(var i=0;i<queryString.length;i++){
            var keyVal = queryString[i].split('=');
            getVars[ keyVal[0] ] = keyVal[1];
        }

    }());
    // console.info( getVars );
    // Object { foo="bar", baz="zing"}```

This probably won't work with deferred / asynchronously added script elements, as it relies on immediate code execution.

ContentLicense: CC BY-SA 2.5

Title: In Javascript, is it possible to pass a variable into <script> "src" parameter?

Body: Is it possible in Javascript to pass a variable through the src parameter? ie.

Body:
I use the following pattern to convert query variables from <script src="script.js?foo=bar&baz=zing"></script> to an object containing key:value pairs. Code is placed at the top of script.js:

    var getVars = {};

    (function(){
        var scripts, currentScript, queryString;

        scripts = document.getElementsByTagName('script');
        currentScript = scripts[ scripts.length - 1 ];
        queryString = currentScript.getAttribute('src').split("?").pop().split('&');
        for(var i=0;i<queryString.length;i++){
            var keyVal = queryString[i].split('=');
            getVars[ keyVal[0] ] = keyVal[1];
        }

    }());
    // console.info( getVars );
    // Object { foo="bar", baz="zing"}

This probably won't work with deferred / asynchronously added script elements, as it relies on immediate code execution.

ContentLicense: CC BY-SA 4.0


问:
Practical applications of homomorphic encryption algorithms?
It appears there there were interesting things going on in cryptography: the first homomorphic encryption scheme appeared recently (explanation, HT). Roughly speaking, it is a way of encoding x into f(x) such that you can compute f(x+y) easily knowing f(x) and f(y) even though you can't easily restore x and y (and same for f(x*y)).

What are practical applications for schemes of this type (once their security has been established)? To me, it appears they could make writing algorithms for manipulating private data much easier.

Here are my thoughts:

electronic voting

checking the integrity of private data

is there a chance that would help privacy in general?

Example: I have accounts with Banks A, B, C. Entity X wants to confirm I have more than $1000 total; it would happily accept statements from Banks A, B, C or D, but unfortunately I don't have enough money in any single account. Bank A encrypts the info about my $500 dollars with my public key; similarly, Banks B and C encrypt the info that I have $200 and $300 respectively. They send these data to X who adds them to some number which I demonstrate to be in fact encrypted $1000 (by encrypting $1000 with my public key and demonstrating that the result is the same). I have proved something without disclosing to X how much money I have in each account.

Another example: Good citizens X_1, ... , X_n are teaming up to select one of two candidates, one of which is latte-drinking liberAl while another is a Bible-bearing gun lover (all names are fictional). They decide they want the voting to be private but quick. They send their votes in the vector format (1, vote_A, vote_B, vote_None) encrypted to the Election Commission which adds them publicly and obtains the result in the form (count, count_A, count_B, count_None). After checking that count = count_A + count_B + count_None, the officials declare the victory of one of the candidates, after which the election is declared invalid by the judge for some reason unrelated to electronic voting and fought in the court for the next 10 years, but, hey, that's not my problem anyway.

Notes:
- I believe those particular example was possible with RSA even before, since it only requires homomorphicity in one operation.  The hope is that we can have radically more interesting things with more operations -- so, come up with examples!

I would especially like to see answers containing code and/or developing frameworks that have a chance of being used in practice, the reason being SO is not a theoretical computer science discussion board.

The homomorphic algorithm, to repeat what was said below in comments, allows to to create a program that would manage data without knowing them. Unfortunately, the types of programs are somewhat limited: you can't have if (x=0) ... because x is encrypted, and each step is very slow (there are some lattices involved).

答:
Some banking applications maybe become faster with the help of Homomorphic Encryption.

They can perform operations with encrypted data on cloud instead of taking it from cloud to local and putting again on cloud. Also no need to encrypt-decrypt-perform operations-encrypt pipeline, encrypt-perform operations would be OK.


问:
Will a Java thread ID stay the same for the full stack?
If I call Thread.currentThread().getId(), I get a long representing the current thread ID.

I'm using the thread ID for a user-threadId mapping in a SessionContext class I am writing. When a user makes an API call to the backend, I store the current threadId against their userId, so then at any point I can call SessionContext.getUserId(), and it will use the threadId to map me back to the user. However this approach won't work if the result of Thread.currentThread().getId() changes at any point in the stack.

My question is, will this ID remain unchanged for the full stack?

答:
The documentation is pretty clear about it:

Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.

I think that's the whole point of an id — that it remains the same for its lifetime.


问:
Change scrollbar position in TextBox?
If I want to change the position of a TextBox's scrollbar, what do I need to do besides this:

```<code>SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
</code>```

This function only changes the scrollbar position, but it doesn't update the actual TextBox (so the scrollbar "scrolls", but the text doesn't). Any suggestions? I'm using Windows Forms and .NET 4, with Visual Studio 2008.

答:
First, define a constant value:

```<code>const int EM_LINESCROLL = 0x00B6;
</code>```

Then, declare two external methods of user32.dll:

```<code>[DllImport("user32.dll")]
static extern int SetScrollPos(IntPtr hWnd, int nBar,
                               int nPos, bool bRedraw);
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int wMsg,
                               int wParam, int lParam);
</code>```

Finally, use these methods to do the real thing:

```<code>SetScrollPos(myTextBox.Handle,1,myTextBox.Lines.Length-1,true);
SendMessage(myTextBox.Handle,EM_LINESCROLL,0,
                             myTextBox.Lines.Length-1);
</code>```

You may also use GetScrollPos() for scroll position saving when textbox is updated:

```<code>[DllImport("user32.dll")]
static extern int GetScrollPos(IntPtr hWnd, int nBar);
</code>```

Title: Change scrollbar position in TextBox?

Body:
If I want to change the position of a TextBox's scrollbar, what do I need to do besides this:

SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

This function only changes the scrollbar position, but it doesn't update the actual TextBox (so the scrollbar "scrolls", but the text doesn't). Any suggestions? I'm using Windows Forms and .NET 4, with Visual Studio 2008.

Body:
First, define a constant value:

const int EM_LINESCROLL = 0x00B6;

Then, declare two external methods of user32.dll:

[DllImport("user32.dll")]
static extern int SetScrollPos(IntPtr hWnd, int nBar,
                               int nPos, bool bRedraw);
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int wMsg,
                               int wParam, int lParam);

Finally, use these methods to do the real thing:

SetScrollPos(myTextBox.Handle,1,myTextBox.Lines.Length-1,true);
SendMessage(myTextBox.Handle,EM_LINESCROLL,0,
                             myTextBox.Lines.Length-1);

You may also use GetScrollPos() for scroll position saving when textbox is updated:

[DllImport("user32.dll")]
static extern int GetScrollPos(IntPtr hWnd, int nBar);


问:
Multiple dex files define Lcom/google/android/gms/internal/zzau
I get the error com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzau; when i run my app
The gradle files are

app.gradle

```<code>dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:support-v4:21.0.3'
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.0'
compile 'com.android.support:cardview-v7:21.0.0'
compile 'com.google.android.gms:play-services:7.0.+'
compile 'com.android.support:mediarouter-v7:21.0.3'
compile 'com.squareup:otto:1.3.5'
compile 'com.squareup.picasso:picasso:2.3.4'
compile 'com.squareup.okhttp:okhttp:2.2.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.github.ksoichiro:android-observablescrollview:1.4.0'
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
compile 'com.facebook.android:facebook-android-sdk:4.1.0'
compile 'com.parse.bolts:bolts-android:1.+'
compile 'com.edmodo:rangebar:1.0.0'
compile 'com.melnykov:floatingactionbutton:1.3.0'
compile project(':library_viewpager')
compile project(':androidHorizontalListView')
compile project(':CastCompanionLibrary')
compile project(':mobihelp_sdk_android_v1.4')
compile fileTree(include: 'Parse-*.jar', dir: 'libs')
compile files('libs/Parse-1.9.2.jar')
compile files('libs/GoogleConversionTrackingSdk-2.2.2.jar')
}
</code>```

CastCompanionLibrary

```<code>dependencies {
compile 'com.android.support:appcompat-v7:22.+'
compile 'com.android.support:mediarouter-v7:22.+'
compile 'com.google.android.gms:play-services-cast:7.5.0'
}
</code>```

How do i fix this? i guess the error occurs because i use google play services in both the module and the app. but the versions are different. is that causing an issue?

答:
I had the same problem but mine was cause by firebase-ui newest version 2.0.0. So I downgraded to 1.2.0 and added the following line to Project level build.gradle file:</p>

```<code>allprojects {
    repositories {
        jcenter()

        // Add the following code
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}
</code>```

Body:
I get the error com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzau; when i run my app
The gradle files are

app.gradle

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:support-v4:21.0.3'
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.0'
compile 'com.android.support:cardview-v7:21.0.0'
compile 'com.google.android.gms:play-services:7.0.+'
compile 'com.android.support:mediarouter-v7:21.0.3'
compile 'com.squareup:otto:1.3.5'
compile 'com.squareup.picasso:picasso:2.3.4'
compile 'com.squareup.okhttp:okhttp:2.2.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.github.ksoichiro:android-observablescrollview:1.4.0'
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
compile 'com.facebook.android:facebook-android-sdk:4.1.0'
compile 'com.parse.bolts:bolts-android:1.+'
compile 'com.edmodo:rangebar:1.0.0'
compile 'com.melnykov:floatingactionbutton:1.3.0'
compile project(':library_viewpager')
compile project(':androidHorizontalListView')
compile project(':CastCompanionLibrary')
compile project(':mobihelp_sdk_android_v1.4')
compile fileTree(include: 'Parse-*.jar', dir: 'libs')
compile files('libs/Parse-1.9.2.jar')
compile files('libs/GoogleConversionTrackingSdk-2.2.2.jar')
}

CastCompanionLibrary

dependencies {
compile 'com.android.support:appcompat-v7:22.+'
compile 'com.android.support:mediarouter-v7:22.+'
compile 'com.google.android.gms:play-services-cast:7.5.0'
}

How do i fix this? i guess the error occurs because i use google play services in both the module and the app. but the versions are different. is that causing an issue?

Body:
I had the same problem but mine was cause by firebase-ui newest version 2.0.0. So I downgraded to 1.2.0 and added the following line to Project level build.gradle file:

allprojects {
    repositories {
        jcenter()

        // Add the following code
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}


问:
Assigning value to undefined in JavaScript
I was writing some code in JavaScript. When I accidentally came across this.

```<code>undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error
</code>```

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.

答:
From MDN:

undefined is a property of the global object; i.e., it is a variable
  in global scope. The initial value of undefined is the primitive value
  undefined.

Hence, you can assign the value to undefined unlike true and null which are reserved keywords. Note that this is the same case with NaN as well which is again not a reserved keyword and hence, you can assign any value to it.

Just to add more to this, it doesn't matter even if you are assigning a value to undefined, it will not write to it as it is a readonly property.

Quoting from MDN again.

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a
  non-configurable, non-writable property per the ECMAScript 5
  specification. Even when this is not the case, avoid overriding it.

Prefer using strict-mode in your JavaScript by declaring "use strict" at the very top of the file or inside a function to avoid such things. Using something like

```<code>"use strict";
undefined = 'test'; //will raise an error, refer to [1]
</code>```

[1] VM1082:2 Uncaught TypeError: Cannot assign to read
  only property 'undefined' of object '#'

Body:
I was writing some code in JavaScript. When I accidentally came across this.

undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.

Body:
From MDN:

undefined is a property of the global object; i.e., it is a variable
  in global scope. The initial value of undefined is the primitive value
  undefined.

Hence, you can assign the value to undefined unlike true and null which are reserved keywords. Note that this is the same case with NaN as well which is again not a reserved keyword and hence, you can assign any value to it.

Just to add more to this, it doesn't matter even if you are assigning a value to undefined, it will not write to it as it is a readonly property.

Quoting from MDN again.

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a
  non-configurable, non-writable property per the ECMAScript 5
  specification. Even when this is not the case, avoid overriding it.

Prefer using strict-mode in your JavaScript by declaring "use strict" at the very top of the file or inside a function to avoid such things. Using something like

"use strict";
undefined = 'test'; //will raise an error, refer to [1]

[1] VM1082:2 Uncaught TypeError: Cannot assign to read
  only property 'undefined' of object '#'


问:
What's the most efficient way to search words in this kind of file by Ruby
I have a file like:

```<code>Fruit.Store={
    #blabla
    "customer-id:12345,item:store/apple" = 10;   #blabla
    "customer-id:23456,item:store/banana" = 10;   #blabla
    "customer-id:23456,item:store/watermelon" = 10;
    #blabla
    "customer-id:67890,item:store/watermelon" = 10;
}
</code>```

Except the comments, each line has the same format: customer-id and item:store/ are fixed, and customer-id is a 5-digit number. There are about 1000 unique lines in the file. When "12345" and "apple" are input, the first line should be returned. What's the most efficient way to solve this problem by Ruby? Thank you!

答:
What's the most efficient way to solve this problem by Ruby?

(Assuming you can load the whole dataset in memory at once and keep it there.)

On load, transform your file into a hash of this shape.

```<code>data = {
  [12345, 'apple'] => 10,
  [23456, 'banana'] => 10,
  ...
}
</code>```

Then you just do this:

```<code>data[[12345, 'apple']] # => 10 or nil (if not found)
</code>```

This gives you O(1) lookups. You can't get more efficient than this.

If you want to work on the file directly, then you can read file line-by-line and try detect matching line, as shown in @mudasobwa's answer. The lookups in that case are much less efficient, but, on the other hand, it requires no preprocessing. So if you just want to do one lookup, that might be more efficient overall.

Body:
I have a file like:

Fruit.Store={
    #blabla
    "customer-id:12345,item:store/apple" = 10;   #blabla
    "customer-id:23456,item:store/banana" = 10;   #blabla
    "customer-id:23456,item:store/watermelon" = 10;
    #blabla
    "customer-id:67890,item:store/watermelon" = 10;
}

Except the comments, each line has the same format: customer-id and item:store/ are fixed, and customer-id is a 5-digit number. There are about 1000 unique lines in the file. When "12345" and "apple" are input, the first line should be returned. What's the most efficient way to solve this problem by Ruby? Thank you!

Body:
What's the most efficient way to solve this problem by Ruby?

(Assuming you can load the whole dataset in memory at once and keep it there.)

On load, transform your file into a hash of this shape.

data = {
  [12345, 'apple'] => 10,
  [23456, 'banana'] => 10,
  ...
}

Then you just do this:

data[[12345, 'apple']] # => 10 or nil (if not found)

This gives you O(1) lookups. You can't get more efficient than this.

If you want to work on the file directly, then you can read file line-by-line and try detect matching line, as shown in @mudasobwa's answer. The lookups in that case are much less efficient, but, on the other hand, it requires no preprocessing. So if you just want to do one lookup, that might be more efficient overall.


问:
How many users is too much when using session variables?
I'm currently using session variables as a cache to cut down the calls to the database.

I'm wondering at about how many concurrent users does this stop working at? 1,000, 10,000 ....100,000??? Also will iis start flaking out at a certain load? And are there
any alternatives?

I know it depends on how much data I'm storing per user, but I want to hear from other peoples experiences.

I do have it setup so that when the code tries to access a timed out session that it reloads from the database.

I'm currently using iis6 but I could easily use iis7 if it handles sessions better.

Edit: Yes I'm using application variables for non user specific data.

答:
If you have more than 124,889 users, your server will begin to be unresponsive.

Edit: if your data does not change and can be re-used, try caching it in an application scoped variable, i.e. reference data.

OwnerDisplayName: Donny V

LastEditorDisplayName: Donny V

OwnerDisplayName: Jobo

LastEditorDisplayName: Jobo


问:
Python: Set param for columns and values pypyodbc - executemany
I have this situation where I created a method that will insert rows in database. I provide to that method columns, values and table name.

COLUMNS = [['NAME','SURNAME','AGE'],['SURNAME','NAME','AGE']]

  VALUES = [['John','Doe',56],['Doe','John',56]]

  TABLE = 'people'

This is how I would like to pass but it doesn't work:

```<code>db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = "insert into %s (?) VALUES(?)" % TABLE
cursor.executemany([sql,[COLUMNS[0],VALUES[0]],[COLUMNS[1],VALUES[1]]])
db.commit()
</code>```

This is how it will pass query but problem is that I must have predefined column names and that's not good because what if the other list has different column sort? Than the name will be in surname and surname in name.

```<code>db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = 'insert into %s (NAME,SURNAME,AGE) VALUES (?,?,?)'
cursor.executemany(sql,[['John','Doe',56],['Doe','John',56]])
db.commit()
</code>```

I hope I explained it clearly enough.
Ps. COLUMNS and VALUES are extracted from json dictionary

[{'NAME':'John','SURNAME':'Doe','AGE':56...},{'SURNAME':'Doe','NAME':'John','AGE':77...}]

if that helps.

SOLUTION:

```<code>class INSERT(object):

    def __init__(self):
        self.BASE_COL = ''

    def call(self):
        GATHER_DATA =  [{'NAME':'John','SURNAME':'Doe','AGE':56},{'SURNAME':'Doe','NAME':'John','AGE':77}]
        self.BASE_COL = ''
        TABLE = 'person'

        #check dictionary keys
        for DATA_EVAL in GATHER_DATA:

            if self.BASE_COL == '': self.BASE_COL = DATA_EVAL.keys()
            else:
                if self.BASE_COL != DATA_EVAL.keys():
                    print ("columns in DATA_EVAL.keys() have different columns")
                    #send mail or insert to log  or remove dict from list
                    exit(403)

        #if everything goes well make an insert
        columns = ','.join(self.BASE_COL)
        sql = 'insert into %s (%s) VALUES (?,?,?)' % (TABLE, columns)
        db = DB_CONN.MSSQL()
        cursor = db.cursor()
        cursor.executemany(sql, [DATA_EVAL.values() for DATA_EVAL in GATHER_DATA])
        db.commit()

if __name__ == "__main__":
    ins = INSERT()
    ins.call()
</code>```

答:
You could take advantage of the non-random nature of key-value pair listing for python dictionaries.
You should check that all items in the json array of records have the same fields, otherwise you'll run into an exception in your query.

```<code>columns = ','.join(records[0].keys())
sql = 'insert into %s (%s) VALUES (?,?,?)' % (TABLE, columns)
cursor.executemany(sql,[record.values() for record in records])
</code>```

References:

https://stackoverflow.com/a/835430/5189811

Body:
I have this situation where I created a method that will insert rows in database. I provide to that method columns, values and table name.

COLUMNS = [['NAME','SURNAME','AGE'],['SURNAME','NAME','AGE']]

  VALUES = [['John','Doe',56],['Doe','John',56]]

  TABLE = 'people'

This is how I would like to pass but it doesn't work:

db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = "insert into %s (?) VALUES(?)" % TABLE
cursor.executemany([sql,[COLUMNS[0],VALUES[0]],[COLUMNS[1],VALUES[1]]])
db.commit()

This is how it will pass query but problem is that I must have predefined column names and that's not good because what if the other list has different column sort? Than the name will be in surname and surname in name.

db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = 'insert into %s (NAME,SURNAME,AGE) VALUES (?,?,?)'
cursor.executemany(sql,[['John','Doe',56],['Doe','John',56]])
db.commit()

I hope I explained it clearly enough.
Ps. COLUMNS and VALUES are extracted from json dictionary

[{'NAME':'John','SURNAME':'Doe','AGE':56...},{'SURNAME':'Doe','NAME':'John','AGE':77...}]

if that helps.

SOLUTION:

class INSERT(object):

    def __init__(self):
        self.BASE_COL = ''

    def call(self):
        GATHER_DATA =  [{'NAME':'John','SURNAME':'Doe','AGE':56},{'SURNAME':'Doe','NAME':'John','AGE':77}]
        self.BASE_COL = ''
        TABLE = 'person'

        #check dictionary keys
        for DATA_EVAL in GATHER_DATA:

            if self.BASE_COL == '': self.BASE_COL = DATA_EVAL.keys()
            else:
                if self.BASE_COL != DATA_EVAL.keys():
                    print ("columns in DATA_EVAL.keys() have different columns")
                    #send mail or insert to log  or remove dict from list
                    exit(403)

        #if everything goes well make an insert
        columns = ','.join(self.BASE_COL)
        sql = 'insert into %s (%s) VALUES (?,?,?)' % (TABLE, columns)
        db = DB_CONN.MSSQL()
        cursor = db.cursor()
        cursor.executemany(sql, [DATA_EVAL.values() for DATA_EVAL in GATHER_DATA])
        db.commit()

if __name__ == "__main__":
    ins = INSERT()
    ins.call()

Body:
You could take advantage of the non-random nature of key-value pair listing for python dictionaries.
You should check that all items in the json array of records have the same fields, otherwise you'll run into an exception in your query.

columns = ','.join(records[0].keys())
sql = 'insert into %s (%s) VALUES (?,?,?)' % (TABLE, columns)
cursor.executemany(sql,[record.values() for record in records])

References:

https://stackoverflow.com/a/835430/5189811


问:
springboot read tomcat-context.xml
Hi we got a spring application running on tomcat application-server. I want to add integration tests with Springboot in JUnit. I now got the problem that the embedded tomcat server does not store our datasource and therefore it cannot be looked up... If the server configuration does not have a datasource defined we got a fallback "context.xml" in our resources that should be used. But the embedded tomcat is not reading this configuration and I just cannot figure out, how to do this.
The following is the point of failure in my JUnit Test, since it cannot find this JNDI-Name in the embedded tomcat:

```<code>@Bean
public DataSource dataSource()
{
  return new JndiDataSourceLookup().getDataSource("jdbc/myDB");
}
</code>```

the fallback context.xml looks like this:

```<code><Context>
<!-- HSQL -->
   <Resource name="jdbc/myDB" auth="Container"
             type="javax.sql.DataSource" driverClassName="org.hsqldb.jdbcDriver"
             url="jdbc:hsqldb:mem:mymemdb;shutdown=true" username="SA" password=""
             maxTotal="100" maxIdle="5" maxWaitMillis="10000"/>

   <Manager pathname=""/>
</Context>
</code>```

how can I push this file into the embedded tomcat on startup?

答:
Spring Boot offer many ways to externalize your configuration...

You can define your datasource properties in your tomcat/conf/Catalina/<host> context descriptors.

You could define your jndi name:

```<code><Context>
    <Parameter name="spring.datasource.jndi-name" value="/pathToYourDatasource" />
</Context>
</code>```

Or define the datasource:

```<code><Context>
    <Parameter name="spring.datasource.url" value="your url" />
    <Parameter name="spring.datasource.username" value="your username" />
    <Parameter name="spring.datasource.password" value="your password" />
</Context>
</code>```

Even define the path to an application.properties and set here your configuration:

```<code><Context>
    <Parameter name="spring.config.location" value="/path/to/application.properties" />
</Context>
</code>```

This way is not necessary set programmatically your hardcoded datasource and you can put another database configuration for testing in src/test/resources/application.properties:

```<code>spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
</code>```

Title: springboot read tomcat-context.xml

Body:
Hi we got a spring application running on tomcat application-server. I want to add integration tests with Springboot in JUnit. I now got the problem that the embedded tomcat server does not store our datasource and therefore it cannot be looked up... If the server configuration does not have a datasource defined we got a fallback "context.xml" in our resources that should be used. But the embedded tomcat is not reading this configuration and I just cannot figure out, how to do this.
The following is the point of failure in my JUnit Test, since it cannot find this JNDI-Name in the embedded tomcat:

@Bean
public DataSource dataSource()
{
  return new JndiDataSourceLookup().getDataSource("jdbc/myDB");
}

the fallback context.xml looks like this:

<Context>

   <Resource name="jdbc/myDB" auth="Container"
             type="javax.sql.DataSource" driverClassName="org.hsqldb.jdbcDriver"
             url="jdbc:hsqldb:mem:mymemdb;shutdown=true" username="SA" password=""
             maxTotal="100" maxIdle="5" maxWaitMillis="10000"/>

   <Manager pathname=""/>
</Context>

how can I push this file into the embedded tomcat on startup?

Body:
Spring Boot offer many ways to externalize your configuration...

You can define your datasource properties in your tomcat/conf/Catalina/<host> context descriptors.

You could define your jndi name:

<Context>
    <Parameter name="spring.datasource.jndi-name" value="/pathToYourDatasource" />
</Context>

Or define the datasource:

<Context>
    <Parameter name="spring.datasource.url" value="your url" />
    <Parameter name="spring.datasource.username" value="your username" />
    <Parameter name="spring.datasource.password" value="your password" />
</Context>

Even define the path to an application.properties and set here your configuration:

<Context>
    <Parameter name="spring.config.location" value="/path/to/application.properties" />
</Context>

This way is not necessary set programmatically your hardcoded datasource and you can put another database configuration for testing in src/test/resources/application.properties:

spring.datasource.url=
spring.datasource.username=
spring.datasource.password=


问:
Serialize Javaparser objects with Jackson Json
I'm trying to serialize Javaparser objects with Jackson JSON, but it's pretty complicated as it is a third party library (I can't change/annotate the code) and there are circular dependencies within it.

My project is structured as such :

An object Analysis contains some lists of WrappedNode that may reference each other. Each WrappedNode contains a JavaParser CallableDeclaration.

When I try to map my Analysis, I've got an error :

```<code>JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.github.javaparser.metamodel.PropertyMetaModel["containingNodeMetaModel"]->com.github.javaparser.metamodel.SimpleNameMetaModel["declaredPropertyMetaModels"]->java.util.ArrayList[0]->com.github.javaparser.metamodel.PropertyMetaModel["containingNodeMetaModel"]...
</code>```

So, to get rid of the infinite recursion, I know I have to use @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id"), which I did on my WrappedNode class, but I think I should also annotate JavaParser classes using Mix-in annotations.

The problem is that there is a lot of fields and a lot of classes, and I don't know which ones to annotate.

Thank's for your help !

答: You can just use the JsonPrinter class provided by JavaParser. It is a very recent addition (from version 3.2.8 I think) and it could not be perfect but you can use it super, super easily</p>

Body:
I'm trying to serialize Javaparser objects with Jackson JSON, but it's pretty complicated as it is a third party library (I can't change/annotate the code) and there are circular dependencies within it.

My project is structured as such :

An object Analysis contains some lists of WrappedNode that may reference each other. Each WrappedNode contains a JavaParser CallableDeclaration.

When I try to map my Analysis, I've got an error :

JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.github.javaparser.metamodel.PropertyMetaModel["containingNodeMetaModel"]->com.github.javaparser.metamodel.SimpleNameMetaModel["declaredPropertyMetaModels"]->java.util.ArrayList[0]->com.github.javaparser.metamodel.PropertyMetaModel["containingNodeMetaModel"]...

So, to get rid of the infinite recursion, I know I have to use @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id"), which I did on my WrappedNode class, but I think I should also annotate JavaParser classes using Mix-in annotations.

The problem is that there is a lot of fields and a lot of classes, and I don't know which ones to annotate.

Thank's for your help !


问:
How to have two password fields controlled by one checkbox?
```<code><form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
  document.write(
    '<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
    'Show the password as I type'
  );
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
  (kc >= 97 && kc <= 122 && sk) ||
  (kc >= 65 && kc <= 90 && !sk)
) {
  document.getElementById('capsalert').style.display = 'inline';
}
else {
  document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);

document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
</code>```

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

```<code><script>
function changeType()
{
    document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>

<body>
<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
</code>```

答:
Most of the answers didn't work.  One or two I left untried because they meant greater changes to my code than I wanted.  I ended up finding yet another method to reveal the passwords: "Show password as text" control

I adapted the method there to my multiple password fields scenario:

```<code><input type="checkbox" onchange="document.getElementById('gpwd').type = this.checked ? 'text' : 'password'; document.getElementById('pwd1').type = this.checked ? 'text' : 'password'; document.getElementById('pwd2').type = this.checked ? 'text' : 'password'"> Reveal passwords
</code>```

Body:
<form>
<fieldset>
Password: CAPS LOCK = on

<input type="password" id="pwd">

Password2:

<input type="password" id="pwd2">
</fieldset>
</form>

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>

Body:
Most of the answers didn't work.  One or two I left untried because they meant greater changes to my code than I wanted.  I ended up finding yet another method to reveal the passwords: "Show password as text" control

I adapted the method there to my multiple password fields scenario:

<input type="checkbox" onchange="document.getElementById('gpwd').type = this.checked ? 'text' : 'password'; document.getElementById('pwd1').type = this.checked ? 'text' : 'password'; document.getElementById('pwd2').type = this.checked ? 'text' : 'password'"> Reveal passwords


问:
Only Office does not support custom delimiter for Importing CSV
Recently, I import a CSV using Only Office Desktop Edition, but it doesn't allow custom delimiter such as |.
Please support this feature.

答:
OnlyOffice Documentserver support custom delimiters from version 4.4.

OnlyOffice DesktipEditors will be released with support of thome soon.


问:
JavaScriptDateTimeConverter gives different result on server
The code below works fine on local machine. On the other side, on server, it shifts date 1 day left.

```<code>JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
</code>```

The value returning from database is: 2010-09-16 00:00:00.000

JsonSerializer gives 2010-09-16 on local and gives 2010-09-15 on server..

any ideas?

To clarify the problem i made a simple test;

```<code>string str = JsonConvert.SerializeObject(Convert.ToDateTime("2010-09-16 00:00:00.000"), new JavaScriptDateTimeConverter());
Response.Write(str);
</code>```

this code produce different results on different machines.. Why?

new Date(1284584400000) and new Date(1284588000000) or

Wed Sep 15 2010 23:00:00 and Thu Sep 16 2010 00:00:00

答:
It's a timezone issue. By default JavaScriptDateTimeConverter uses UTC dates. You need to create a SerializerSettings object, and set </p>

```<code>settings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
</code>```

Body:
The code below works fine on local machine. On the other side, on server, it shifts date 1 day left.

JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());

The value returning from database is: 2010-09-16 00:00:00.000

JsonSerializer gives 2010-09-16 on local and gives 2010-09-15 on server..

any ideas?

To clarify the problem i made a simple test;

string str = JsonConvert.SerializeObject(Convert.ToDateTime("2010-09-16 00:00:00.000"), new JavaScriptDateTimeConverter());
Response.Write(str);

this code produce different results on different machines.. Why?

new Date(1284584400000) and new Date(1284588000000) or

Wed Sep 15 2010 23:00:00 and Thu Sep 16 2010 00:00:00

Body:
It's a timezone issue. By default JavaScriptDateTimeConverter uses UTC dates. You need to create a SerializerSettings object, and set

settings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;


问:
vue-resource interceptor for auth headers
I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.

I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:

```<code>methods: {
    getUser () {
      this.$http.get('http://localhost:8000/api/user',
      {
        headers: {
          'Authorization': 'Bearer eyJ0e.....etc',
          'Accept': 'application/json'
        }
      }).then((response) => {
        this.name = response.data.name
      });
    },
</code>```

However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.

Based on the vue-resource readme I am trying this in my main.js:

```<code>Vue.use(VueResource)

Vue.http.interceptors.push((request, next) => {
  request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
  request.headers['Accept'] = 'application/json'
  next()
})
</code>```

And then back in my component I now just have:

```<code>this.$http.get('http://localhost:8000/api/user').then((response) => {
    this.name = response.data.name
});
</code>```

Problem:

When I specify the headers in the get itself, I get a successful response, but when I pass them through the interceptor I get back a 401 Unauthorized from the server. How can I fix this to respond successfully while using the interceptor?

Edit:
When I use dev-tools to view the outgoing requests I see the following behavior:

When making the request by supplying the headers to $http.get, I make a successful OPTIONS request and then a successful GET request with the Authentication header being supplied to the GET request.

However, when I remove the headers from the $http.get directly and move them to the interceptor, I only make a GET request and the GET does not contain the Authentication header, thus it comes back as a 401 Unauthorized.

答:
Add this option:

```<code>Vue.http.options.credentials = true;
</code>```

And use the interceptors for global way:

```<code>Vue.http.interceptors.push(function(request, next) {

request.headers['Authorization'] = 'Basic abc' //Base64
request.headers['Accept'] = 'application/json'
next()
</code>```

});

Body:
I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.

I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:

methods: {
    getUser () {
      this.$http.get('http://localhost:8000/api/user',
      {
        headers: {
          'Authorization': 'Bearer eyJ0e.....etc',
          'Accept': 'application/json'
        }
      }).then((response) => {
        this.name = response.data.name
      });
    },

However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.

Based on the vue-resource readme I am trying this in my main.js:

Vue.use(VueResource)

Vue.http.interceptors.push((request, next) => {
  request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
  request.headers['Accept'] = 'application/json'
  next()
})

And then back in my component I now just have:

this.$http.get('http://localhost:8000/api/user').then((response) => {
    this.name = response.data.name
});

Problem:

When I specify the headers in the get itself, I get a successful response, but when I pass them through the interceptor I get back a 401 Unauthorized from the server. How can I fix this to respond successfully while using the interceptor?

Edit:
When I use dev-tools to view the outgoing requests I see the following behavior:

When making the request by supplying the headers to $http.get, I make a successful OPTIONS request and then a successful GET request with the Authentication header being supplied to the GET request.

However, when I remove the headers from the $http.get directly and move them to the interceptor, I only make a GET request and the GET does not contain the Authentication header, thus it comes back as a 401 Unauthorized.

Body:
Add this option:

Vue.http.options.credentials = true;

And use the interceptors for global way:

Vue.http.interceptors.push(function(request, next) {

request.headers['Authorization'] = 'Basic abc' //Base64
request.headers['Accept'] = 'application/json'
next()

});


问:
javascript - functions and equations confusion
```<code> var number = prompt('Input a number!');
 var n = number;
   function getList() {

 for (var n = 1; n <= 17; n++) {

   if (n % 3 == 0 || n % 5 == 0)
     console.log (n);
   }
 }

console.log(getList());
console.log((n*(n+1))/2);

//equation for summation: (n*(n+1))/2
</code>```

I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.

I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?

The answer is supposed to be 60. Any clue? Thanks!

答:
var number = prompt('Input a number!');
 function getList() {
  var sum = 0;
  for (var n = 1; n <= number; n++) {
   if (n % 3 == 0 || n % 5 == 0)
     sum+=n;
   }
  return sum;
 }
console.log(getList());```

it will return sum of all the number which is divisible by 3 or 5 in between 1 and entered number

Body:
 var number = prompt('Input a number!');
 var n = number;
   function getList() {

 for (var n = 1; n <= 17; n++) {

   if (n % 3 == 0 || n % 5 == 0)
     console.log (n);
   }
 }

console.log(getList());
console.log((n*(n+1))/2);

//equation for summation: (n*(n+1))/2

I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.

I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?

The answer is supposed to be 60. Any clue? Thanks!

Body:
var number = prompt('Input a number!');
 function getList() {
  var sum = 0;
  for (var n = 1; n <= number; n++) {
   if (n % 3 == 0 || n % 5 == 0)
     sum+=n;
   }
  return sum;
 }
console.log(getList());

it will return sum of all the number which is divisible by 3 or 5 in between 1 and entered number


问:
Javascript - returning concatenates instead of sum of variables from input
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

```<code><input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>
</code>```

JavaScript

```<code>var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});
</code>```

JSFiddle Demo

答:
You are adding a NaN data type to an Number data type. So you need to restrict it before you perform your addition operation.

Please check this one

```<code>var totalvalue = 0;
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        if(isNaN($(this).val()) || $(this).val() != ''){
            totalvalue = totalvalue + parseInt($(this).val());
      }
  });
  $("#totalvalue").val(totalvalue);

});
</code>```

Body:
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

<input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>

JavaScript

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});

JSFiddle Demo

Body:
You are adding a NaN data type to an Number data type. So you need to restrict it before you perform your addition operation.

Please check this one

var totalvalue = 0;
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        if(isNaN($(this).val()) || $(this).val() != ''){
            totalvalue = totalvalue + parseInt($(this).val());
      }
  });
  $("#totalvalue").val(totalvalue);

});


问:
Multiple aggregate functions in Java 8 Stream API
I have a class defined like

```<code>public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}
</code>```

I would like to perform the following SQL statement using Java 8 Stream API.

```<code>SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate
</code>```

I tried :

```<code>Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....
</code>```

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

答:
You can chain multiple attributes like this:

```<code>Collection<TimePeriodCalc> collector = result.stream().collect(Collectors.groupingBy(p -> p.getAtDate(), Collectors.averagingInt(p -> p.getOccupancy())));
</code>```

If you want more, you get the idea.

Body:
I have a class defined like

public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}

I would like to perform the following SQL statement using Java 8 Stream API.

SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate

I tried :

Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

Body:
You can chain multiple attributes like this:

Collection<TimePeriodCalc> collector = result.stream().collect(Collectors.groupingBy(p -> p.getAtDate(), Collectors.averagingInt(p -> p.getOccupancy())));

If you want more, you get the idea.


问:
Firebase Analytics custom events params
I am completely new to Firebase analytics. I am trying to send an event which shows statistics about my API call.

```<code>endTime = System.currentTimeMillis() - startTime;

// [START event]
Bundle params = new Bundle();
params.putString(FirebaseConstants.PHONE_NUMBER, Utility.getPhone());
params.putLong(FirebaseConstants.DURATION, endTime);
FirebaseAnalytics
            .getInstance(getContext())
            .logEvent(FirebaseConstants.BALANCE_CHECK, params);
// [END event]
</code>```

But I only see the name of the event, number of users and occurrence count. 24 hours have already passed and I don't see my custom properties. For reference, I want to see a phone number(Utility.getPhone()) and the time which API call takes(endtime). Maybe it is possible that it does not send anything because I created custom params in my FirebaseConstans class

答:
As of https://support.google.com/firebase/answer/7397304?hl=en&ref_topic=6317489, you need to register your parameters before they can be shown

When you first set up custom parameters, a data card for it will be added to your event detail report. However, it may take up to 24 hours for any data to appear.

Title: Firebase Analytics custom events params

Body:
I am completely new to Firebase analytics. I am trying to send an event which shows statistics about my API call.

endTime = System.currentTimeMillis() - startTime;

// [START event]
Bundle params = new Bundle();
params.putString(FirebaseConstants.PHONE_NUMBER, Utility.getPhone());
params.putLong(FirebaseConstants.DURATION, endTime);
FirebaseAnalytics
            .getInstance(getContext())
            .logEvent(FirebaseConstants.BALANCE_CHECK, params);
// [END event]

But I only see the name of the event, number of users and occurrence count. 24 hours have already passed and I don't see my custom properties. For reference, I want to see a phone number(Utility.getPhone()) and the time which API call takes(endtime). Maybe it is possible that it does not send anything because I created custom params in my FirebaseConstans class


问:
What are the best practices to encrypt passwords stored in MySql using PhP?
I am seeking advice on how to securely store passwords in MySQL using PHP.

Overlooking the limitations of PHP itself, I want to know more about salting, hashing, and encrypting these bad boys.

Obviously people will continue to use weak passwords unless forced to do otherwise, but it's how I am storing them that is important to me. My user's passwords are far more important to me than the database itself, and as such I want to keep them in such a way that it will be painstaking and monotonous for any script kiddie trying reverse. Obviously with due diligence just about anything can be defeated, but I wouldn't mind making this particularly bothersome.

There are two scenarios we are looking at.

The kiddie has a complete copy of the database.

The kiddie has a complete copy of the PHP used to craft the password, and the database.

Any and all advice on this topic is graciously appreciated.

答:
If your users are over the internet, OpenId would be one of your best options. http://openid.net/

If your users are on your network, can you do Integrated Security?

In other words.. do not store their passwords.


问:
What is the absolute path of the Hadoop filesystem
I can access hadoop fs -ls /
and I would like to know the absolute path of above /

I knew the / is a format looks like: "hdfs://host:port/"
I also knew it is the value of the setting fs.defaultFS in core-site.xml.

However, I checked my core-site.xml, and did not find fs.defaultFS's value.
There must be a default value of fs.defaultFS, what is it?

答:
You can find the default value in the file core-default.xml, it is usually
    file:///

Check core-site.xml for the value which is set by the user to override the default value which if present would something like

```<code><property>
  <name>fs.defaultFS</name>
  <value>hdfs://host:port</value>
</property>
</code>```

the value can even be a service configured.

It is the default prefix of the Hadoop file system, by default it might look for file:// which is your local file system.

Body:
You can find the default value in the file core-default.xml, it is usually
    file:///

Check core-site.xml for the value which is set by the user to override the default value which if present would something like

<property>
  <name>fs.defaultFS</name>
  <value>hdfs://host:port</value>
</property>

the value can even be a service configured.

It is the default prefix of the Hadoop file system, by default it might look for file:// which is your local file system.


问:
How to get the last number of a string using selenium webdriver
1 - 2 of 2

Above is my text. This is from paging of a web application. How do i extract the last number of the above text. SO i will get the count of list in that page and i can run a loop with respect to the number.

答:
You can use substring

Let's consider your example. You have a String 1 - 2 of 2 (pagination probably)
Each of individual character is a specified index of a String

1 = 0
space = 1
 - = 2
space = 3
etc.

String has a set of methods to perform various tasks. One of them is length() which gives you number of characters in your String

What you can do is to pass your length of String to substring.

Example:
myString.substring(0,1) will give you results of 1
myString.substring(0,myString.length()) wil give you results of 1 - 2 of 5

Additional info: myString.length() is an int type so you can perform math operations like + or -
myString.substring(0,myString.length()-1) will give you results of 1 - 2 of

I gave you the tools, now it's time for you to find the solutions.


问:
Eclipse Maven project structure
I am fairly new to maven. In Eclipse, I created a maven project
Inside this I can see src/main/java and src/test/java also there is one more src folder which again contains main and test folder. Here I am confused in which src folder I need to write the code. What is the main benefit of using main and test folder? Why there are two main and two src folder

答: They are one and the same. If you look at the directory using Windows Explorer or via the command line, you will see that there is only one src/main/java and one src/test/java. The folders you are seeing below are like how you view it in Explorer, as folders and files. The one you are seeing up top is a Java representation of the folders, which are package names. Your production code goes in main while your test code goes in test. In other words the class under test are located in main while the test class is located in test.

Title: Eclipse Maven project structure


问:
Custom landing page for SaaS application
I am building a SaaS based web application, to which users can connect using their own domain and apply their company branding to it.

How can I customize the landing page of my application based on domain from which it is being accessed. There is no login information to identify the customer.

Thanks.

答:
You can try to put in your iframe such code:

```<code><script>
    var wantedUrl = (window.location != window.parent.location)
                    ? document.referrer
                    : document.location.href;
    var wantedUrlEsc = escape(wantedUrl);
    var newEl = document.createElement('script');
    newEl.src = "https://your.server.com?wantedUrlEsc=" + wantedUrlEsc;

    document.getElementsByTagName('head')[0].appendChild(newEl);
    // or document.head.appendChild(newEl) in modern browsers
</script>
</code>```

and on server side you can try read and decode the wantedUrlEsc parameter.

Good luck!

Body:
You can try to put in your iframe such code:

<script>
    var wantedUrl = (window.location != window.parent.location)
                    ? document.referrer
                    : document.location.href;
    var wantedUrlEsc = escape(wantedUrl);
    var newEl = document.createElement('script');
    newEl.src = "https://your.server.com?wantedUrlEsc=" + wantedUrlEsc;

    document.getElementsByTagName('head')[0].appendChild(newEl);
    // or document.head.appendChild(newEl) in modern browsers
</script>

and on server side you can try read and decode the wantedUrlEsc parameter.

Good luck!


问:
Assigning value to undefined in JavaScript
I was writing some code in JavaScript. When I accidentally came across this.

```<code>undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error
</code>```

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.

答:
You can not declare a variable with the name of reserved words(keywords) in any language either it's scripting or programming.

if you want to use this you can use _ underscore at the very first of the varibale name.

like: _true , _null or _anythingwhatyouwant

Body:
I was writing some code in JavaScript. When I accidentally came across this.

undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.


问:
Server 2008 EventLog levels
Pre-2008 event log entries (of type EVENTLOGRECORD) had an EventType member that could be EVENTLOG_ERROR_TYPE, EVENTLOG_AUDIT_FAILURE, etc.

Since Vista, now there are Level and Keyword values instead of EventType.  I've searched high and low for what values Level and Keyword could hold but can't find any references.

Are there any official docs on this?  I'd hate to try and guess by looking at a lot of existing event log entries and hoping I guess right.

Thanks!

EDIT:  Found some docs

http://msdn.microsoft.com/en-us/library/aa382793(v=VS.85).aspx

ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/wes/wes/eventmanifestschema_keywordtype_complextype.htm

答:
I don't have the SDK header files in front of me, but I found the following information for the EventLogRecord managed class:

EventLogRecord.Level

EventLogRecord.Keywords

Title: Server 2008 EventLog levels


问:
Not initialized variable in tensorflow
I am trying to write a machine learning program. The idea was to train a model (defined in q_model) which could be trained with RMSProp. I report here a really simplified version of my code, which is not working.

```<code>import tensorflow as tf
import numpy as np

#--------------------------------------
# Model definition
#--------------------------------------

# Let's use a simple nn for the Q value function

W = tf.Variable(tf.random_normal([3,10],dtype=tf.float64), name='W')
b = tf.Variable(tf.random_normal([10],dtype=tf.float64), name='b')

def q_model(X,A):
    input = tf.concat((X,A), axis=1)
    return tf.reduce_sum( tf.nn.relu(tf.matmul(input, W) + b), axis=1)

#--------------------------------------
# Model and model initializer
#--------------------------------------

optimizer = tf.train.RMSPropOptimizer(0.9)
init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)

#--------------------------------------
# Learning
#--------------------------------------

x = np.matrix(np.random.uniform((0.,0.),(1.,1.), (1000,2)))
a = np.matrix(np.random.uniform((0),(1), 1000)).T
y = np.matrix(np.random.uniform((0),(1), 1000)).T

y_batch , x_batch, a_batch = tf.placeholder("float64",shape=(None,1), name='y'), tf.placeholder("float64",shape=(None,2), name='x'), tf.placeholder("float64",shape=(None,1), name='a')
error = tf.reduce_sum(tf.square(y_batch - q_model(x_batch,a_batch))) / 100.
train = optimizer.minimize(error)

indx = range(1000)
for i in range(100):
    # batches
    np.random.shuffle(indx)
    indx = indx[:100]
    print sess.run({'train':train}, feed_dict={'x:0':x[indx],'a:0':a[indx],'y:0':y[indx]})
</code>```

The error is:

```<code>Traceback (most recent call last):
  File "/home/samuele/Projects/GBFQI/test/tf_test.py", line 45, in <module>
    print sess.run({'train':train}, feed_dict={'x:0':x[indx],'a:0':a[indx],'y:0':y[indx]})
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 789, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 997, in _run
    feed_dict_string, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1132, in _do_run
    target_list, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1152, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value b/RMSProp
     [[Node: RMSProp/update_b/ApplyRMSProp = ApplyRMSProp[T=DT_DOUBLE, _class=["loc:@b"], use_locking=false, _device="/job:localhost/replica:0/task:0/cpu:0"](b, b/RMSProp, b/RMSProp_1, RMSProp/update_b/Cast, RMSProp/update_b/Cast_1, RMSProp/update_b/Cast_2, RMSProp/update_b/Cast_3, gradients/add_grad/tuple/control_dependency_1)]]

Caused by op u'RMSProp/update_b/ApplyRMSProp', defined at:
  File "/home/samuele/Projects/GBFQI/test/tf_test.py", line 38, in <module>
    train = optimizer.minimize(error)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 325, in minimize
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 456, in apply_gradients
    update_ops.append(processor.update_op(self, grad))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 97, in update_op
    return optimizer._apply_dense(g, self._v)  # pylint: disable=protected-access
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/rmsprop.py", line 140, in _apply_dense
    use_locking=self._use_locking).op
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/gen_training_ops.py", line 449, in apply_rms_prop
    use_locking=use_locking, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value b/RMSProp
     [[Node: RMSProp/update_b/ApplyRMSProp = ApplyRMSProp[T=DT_DOUBLE, _class=["loc:@b"], use_locking=false, _device="/job:localhost/replica:0/task:0/cpu:0"](b, b/RMSProp, b/RMSProp_1, RMSProp/update_b/Cast, RMSProp/update_b/Cast_1, RMSProp/update_b/Cast_2, RMSProp/update_b/Cast_3, gradients/add_grad/tuple/control_dependency_1)]]
</code>```

I cannot explain myself this error since the model is initialized, and actually if I run

```<code>print sess.run(q_model(x,a))
</code>```

the model is working as expected without raising any error.

EDIT:

My question is different from this question. I was already aware of

```<code>init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)
</code>```

but I didn't know that it should have been performed after the optimization too.

答:
You need to put this piece of code:

```<code>init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)
</code>```

after having created these tensors:

```<code>y_batch , x_batch, a_batch = tf.placeholder("float64",shape=(None,1), name='y'), tf.placeholder("float64",shape=(None,2), name='x'), tf.placeholder("float64",shape=(None,1), name='a')
error = tf.reduce_sum(tf.square(y_batch - q_model(x_batch,a_batch))) / 100.
train = optimizer.minimize(error)

init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)
</code>```

Otherwise the hidden variables added to the Graph when calling the optimiser.minimize method won't be initialised.

Meantime, the call to print sess.run(q_model(x,a)) works because the variables used by this part of the Graph have been all initialised.

BTW: Use tf.global_variables_initializer rather than tf.initialize_all_variables.

EDIT:

To perform a selective initialisation, you could do something like that:

```<code>with tf.variable_scope("to_be_initialised"):
    train = optimizer.minimize(error)

sess.run(tf.variables_initializer(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='to_be_initialised')))
</code>```

Title: Not initialized variable in tensorflow

Body:
I am trying to write a machine learning program. The idea was to train a model (defined in q_model) which could be trained with RMSProp. I report here a really simplified version of my code, which is not working.

import tensorflow as tf
import numpy as np

#--------------------------------------
# Model definition
#--------------------------------------

# Let's use a simple nn for the Q value function

W = tf.Variable(tf.random_normal([3,10],dtype=tf.float64), name='W')
b = tf.Variable(tf.random_normal([10],dtype=tf.float64), name='b')

def q_model(X,A):
    input = tf.concat((X,A), axis=1)
    return tf.reduce_sum( tf.nn.relu(tf.matmul(input, W) + b), axis=1)

#--------------------------------------
# Model and model initializer
#--------------------------------------

optimizer = tf.train.RMSPropOptimizer(0.9)
init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)

#--------------------------------------
# Learning
#--------------------------------------

x = np.matrix(np.random.uniform((0.,0.),(1.,1.), (1000,2)))
a = np.matrix(np.random.uniform((0),(1), 1000)).T
y = np.matrix(np.random.uniform((0),(1), 1000)).T

y_batch , x_batch, a_batch = tf.placeholder("float64",shape=(None,1), name='y'), tf.placeholder("float64",shape=(None,2), name='x'), tf.placeholder("float64",shape=(None,1), name='a')
error = tf.reduce_sum(tf.square(y_batch - q_model(x_batch,a_batch))) / 100.
train = optimizer.minimize(error)

indx = range(1000)
for i in range(100):
    # batches
    np.random.shuffle(indx)
    indx = indx[:100]
    print sess.run({'train':train}, feed_dict={'x:0':x[indx],'a:0':a[indx],'y:0':y[indx]})

The error is:

Traceback (most recent call last):
  File "/home/samuele/Projects/GBFQI/test/tf_test.py", line 45, in <module>
    print sess.run({'train':train}, feed_dict={'x:0':x[indx],'a:0':a[indx],'y:0':y[indx]})
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 789, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 997, in _run
    feed_dict_string, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1132, in _do_run
    target_list, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1152, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value b/RMSProp
     [[Node: RMSProp/update_b/ApplyRMSProp = ApplyRMSProp[T=DT_DOUBLE, _class=["loc:@b"], use_locking=false, _device="/job:localhost/replica:0/task:0/cpu:0"](b, b/RMSProp, b/RMSProp_1, RMSProp/update_b/Cast, RMSProp/update_b/Cast_1, RMSProp/update_b/Cast_2, RMSProp/update_b/Cast_3, gradients/add_grad/tuple/control_dependency_1)]]

Caused by op u'RMSProp/update_b/ApplyRMSProp', defined at:
  File "/home/samuele/Projects/GBFQI/test/tf_test.py", line 38, in <module>
    train = optimizer.minimize(error)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 325, in minimize
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 456, in apply_gradients
    update_ops.append(processor.update_op(self, grad))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 97, in update_op
    return optimizer._apply_dense(g, self._v)  # pylint: disable=protected-access
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/rmsprop.py", line 140, in _apply_dense
    use_locking=self._use_locking).op
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/gen_training_ops.py", line 449, in apply_rms_prop
    use_locking=use_locking, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value b/RMSProp
     [[Node: RMSProp/update_b/ApplyRMSProp = ApplyRMSProp[T=DT_DOUBLE, _class=["loc:@b"], use_locking=false, _device="/job:localhost/replica:0/task:0/cpu:0"](b, b/RMSProp, b/RMSProp_1, RMSProp/update_b/Cast, RMSProp/update_b/Cast_1, RMSProp/update_b/Cast_2, RMSProp/update_b/Cast_3, gradients/add_grad/tuple/control_dependency_1)]]

I cannot explain myself this error since the model is initialized, and actually if I run

print sess.run(q_model(x,a))

the model is working as expected without raising any error.

EDIT:

My question is different from this question. I was already aware of

init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)

but I didn't know that it should have been performed after the optimization too.

Body:
You need to put this piece of code:

init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)

after having created these tensors:

y_batch , x_batch, a_batch = tf.placeholder("float64",shape=(None,1), name='y'), tf.placeholder("float64",shape=(None,2), name='x'), tf.placeholder("float64",shape=(None,1), name='a')
error = tf.reduce_sum(tf.square(y_batch - q_model(x_batch,a_batch))) / 100.
train = optimizer.minimize(error)

init = tf.initialize_all_variables()
sess = tf.Session()

sess.run(init)

Otherwise the hidden variables added to the Graph when calling the optimiser.minimize method won't be initialised.

Meantime, the call to print sess.run(q_model(x,a)) works because the variables used by this part of the Graph have been all initialised.

BTW: Use tf.global_variables_initializer rather than tf.initialize_all_variables.

EDIT:

To perform a selective initialisation, you could do something like that:

with tf.variable_scope("to_be_initialised"):
    train = optimizer.minimize(error)

sess.run(tf.variables_initializer(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='to_be_initialised')))


问:
Capture Click event of button with image in WPF
I'm new to WPF and created a draggable button with an image inside - which works nicely...but I can't seem to capture the onClick of the button which contains the image?

```<code><Window x:Class="PAD.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PAD"
    mc:Ignorable="d"
    Title="C2D" Height="134" Width="134" WindowStyle="None" Background="Transparent" Foreground="Transparent" BorderBrush="Transparent" BorderThickness="0" ResizeMode="NoResize" AllowsTransparency="True">
<Grid x:Name="ClickIcon" Background="Transparent" >

    <Button x:Name="dialButton" HorizontalAlignment="Left" VerticalAlignment="Top" Width="130" Height="130" Foreground="Transparent" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" >
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <Ellipse Fill="Transparent"/>
                    <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <Image x:Name="phoneIcon"  Width="128" Height="128" Source="c:\users\chapmd1\documents\visual studio 2015\Projects\PAD\PAD\red-phone-icon_300205.png" MouseDown="image_MouseDown" />
                </Grid>
            </ControlTemplate>
        </Button.Template>

    </Button>

 private void image_MouseDown(object sender, MouseButtonEventArgs e)
    {
            this.DragMove();

    }
</code>```

I tried the onClick on the Button, but nothing got captured?

答:
Not sure what you want to achieve, but in case you want to Drag the Window while the button is pressed and then afterwards do something else then you can do it like this:</p>

```<code> private void image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        while (e.ButtonState == MouseButtonState.Pressed)
        {
          this.DragMove();
          Debug.WriteLine("Dragged!");
        }

        var image = sender as Image;
        object parent = FindParent(image);
        while (parent != null && parent.GetType() != typeof(Button))
        {
            parent = FindParent((FrameworkElement)parent);
        }

        var bt = parent as Button;
        if(bt != null)
        bt.ClickMode = ClickMode.Press;
    }

    private void DialButton_OnClick(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("Clicked!");
    }

    DependencyObject FindParent(FrameworkElement ui)
    {
        return ui.TemplatedParent;
    }
}
</code>```

Body:
I'm new to WPF and created a draggable button with an image inside - which works nicely...but I can't seem to capture the onClick of the button which contains the image?

<Window x:Class="PAD.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PAD"
    mc:Ignorable="d"
    Title="C2D" Height="134" Width="134" WindowStyle="None" Background="Transparent" Foreground="Transparent" BorderBrush="Transparent" BorderThickness="0" ResizeMode="NoResize" AllowsTransparency="True">
<Grid x:Name="ClickIcon" Background="Transparent" >

    <Button x:Name="dialButton" HorizontalAlignment="Left" VerticalAlignment="Top" Width="130" Height="130" Foreground="Transparent" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" >
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <Ellipse Fill="Transparent"/>
                    <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <Image x:Name="phoneIcon"  Width="128" Height="128" Source="c:\users\chapmd1\documents\visual studio 2015\Projects\PAD\PAD\red-phone-icon_300205.png" MouseDown="image_MouseDown" />
                </Grid>
            </ControlTemplate>
        </Button.Template>

    </Button>

 private void image_MouseDown(object sender, MouseButtonEventArgs e)
    {
            this.DragMove();

    }

I tried the onClick on the Button, but nothing got captured?

Body:
Not sure what you want to achieve, but in case you want to Drag the Window while the button is pressed and then afterwards do something else then you can do it like this:

 private void image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        while (e.ButtonState == MouseButtonState.Pressed)
        {
          this.DragMove();
          Debug.WriteLine("Dragged!");
        }

        var image = sender as Image;
        object parent = FindParent(image);
        while (parent != null && parent.GetType() != typeof(Button))
        {
            parent = FindParent((FrameworkElement)parent);
        }

        var bt = parent as Button;
        if(bt != null)
        bt.ClickMode = ClickMode.Press;
    }

    private void DialButton_OnClick(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("Clicked!");
    }

    DependencyObject FindParent(FrameworkElement ui)
    {
        return ui.TemplatedParent;
    }
}