问:
Searchkick index is empty after reindexing from model
When I try to reindex records from inside a model it ends up setting an empty index on elasticsearch server.

So, I have a Course model which has many Instructors.
Now, I have this callback method inside instructor.rb model which tries to reindex whenever something is updated on Instructor.

```<code>class Instructor < ActiveRecord::Base
belongs_to :teacher, :class_name => "User", :foreign_key => "user_id"
belongs_to :instructorable, polymorphic: true
after_commit :reindex_course

private

  def reindex_course
     Course.reindex_course
  end
end
</code>```

course.rb model looks like this:

```<code>    class Course < ActiveRecord::Base
        has_many :instructors, as: :instructorable, dependent: :destroy

searchkick word_start: [ :name, :description, :instructor_name]

def search_data
      {
      name: name,
      description: description,
      searchable: searchable,
      }.merge(
        instructor_name: instructors.includes(:teacher).pluck(:'users.name').reject(&:nil?),
      institute_id: creator.try(:institute_id)
)
            def self.reindex_course
                index = Course.reindex(async: true, refresh_interval: "5s")
                Course.search_index.promote(index[:index_name], update_refresh_interval: true)
                Course.search_index.clean_indices
              end
    end
</code>```

Creating a new Instructor leads to reindexing of records

```<code>Instructor.create(user_id: 4009,instructorable_id: 4792, instructorable_type:"ScheduledCourse")
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_aliases response_code=200 return_code=ok total_time=0.630504
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development_20171204162604885 response_code=200 return_code=ok total_time=0.922072
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_alias/courses_development response_code=200 return_code=ok total_time=0.29790799999999995
       (5.0ms)  SELECT MIN("courses"."id") FROM "courses" LEFT OUTER JOIN "users" ON "users"."id" = "courses"."creator_id" LEFT OUTER JOIN "units" ON "units"."course_id" = "courses"."id" LEFT OUTER JOIN "instructors" ON "instructors"."instructorable_id" = "courses"."id" AND "instructors"."instructorable_type" = $1  [["instructorable_type", "Course"]]
       (4.4ms)  SELECT MAX("courses"."id") FROM "courses" LEFT OUTER JOIN "users" ON "users"."id" = "courses"."creator_id" LEFT OUTER JOIN "units" ON "units"."course_id" = "courses"."id" LEFT OUTER JOIN "instructors" ON "instructors"."instructorable_id" = "courses"."id" AND "instructors"."instructorable_type" = $1  [["instructorable_type", "Course"]]
    Enqueued Searchkick::BulkReindexJob (Job ID: d710eff3-5e39-4347-b02a-5459bfd4b1be) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>1, :min_id=>2, :max_id=>1001}
    Enqueued Searchkick::BulkReindexJob (Job ID: f0bf5866-f3da-42dd-9132-2de23735fbf4) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>2, :min_id=>1002, :max_id=>2001}
    Enqueued Searchkick::BulkReindexJob (Job ID: 348e07b8-a85a-4a9f-a2f2-d2b70416d2bf) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>3, :min_id=>2002, :max_id=>3001}
    Enqueued Searchkick::BulkReindexJob (Job ID: e40f2a33-e2f7-4f77-9416-920d84e285e7) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>4, :min_id=>3002, :max_id=>4001}
    Enqueued Searchkick::BulkReindexJob (Job ID: 18b357c1-cd53-4836-8aaf-4c97dde56281) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>5, :min_id=>4002, :max_id=>5001}
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development_20171204162604885/_settings response_code=200 return_code=ok total_time=0.372641
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_alias/courses_development response_code=200 return_code=ok total_time=0.333225
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_aliases response_code=200 return_code=ok total_time=0.42405099999999996
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_aliases response_code=200 return_code=ok total_time=0.382619
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development_20171204162504480 response_code=200 return_code=ok total_time=0.408705
</code>```

Now when I run this query:

```<code>Searchkick.search search_params[:search], operator: "or",
           index_name: [Course],
           where:{institute_id: institute_id, searchable: true},
           fields: ['name^100','instructor_name^100','description^50'],
           match: :word_start, misspellings: {edit_distance: 2},
           page: search_params[:page],per_page: 20,
           order: {_score: :desc}
</code>```

I get an empty response:

```<code>ETHON: performed EASY effective_url=http://xx:xxxx@xy.xyz.xx.xyz/elasticsearch/courses_development/_search response_code=200 return_code=ok total_time=0.733799
  Search (738.0ms)  curl http://xx.xxx.xx.xxx:80/courses_development/_search?pretty -d '{"query":{"bool":{"must":{"dis_max":{"queries":[{"bool":{"must":{"bool":{"should":[{"match":{"name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"instructor_name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"description.word_start":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"description.word_start":{"query":"Elasticsearch","boost":50.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"description.analyzed":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}}}}]}},"filter":[{"term":{"institute_id":113}},{"term":{"searchable":true}}]}},"size":1000,"from":0,"timeout":"11s","_source":false}'
=> #<Searchkick::Results:0x007fcb8c9cb378
 @klass=nil,
 @options=
  {:page=>1,
   :per_page=>1000,
   :padding=>0,
   :load=>true,
   :includes=>nil,
   :model_includes=>nil,
   :json=>false,
   :match_suffix=>:word_start,
   :highlighted_fields=>[],
   :misspellings=>true},
 @response=
  {"took"=>1,
   "timed_out"=>false,
   "_shards"=>{"total"=>5, "successful"=>5, "skipped"=>0, "failed"=>0},
   "hits"=>{"total"=>0, "max_score"=>nil, "hits"=>[]}}>
</code>```

However, when i run Course.reindex(from console or model) or RAILS_ENV=development bundle exec rake searchkick:reindex CLASS=Course --trace form terminal it again starts working.

```<code>[33] pry(main)> Searchkick.search "Elasticsearch", operator: "or",index_name: [Course],where:{institute_id: 113, searchable: true},fields: ['name^100','instructor_name^100','description^50'],match: :word_start,misspellings: {edit_distance: 2}
ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development/_search response_code=200 return_code=ok total_time=0.57072
  Search (573.5ms)  curl http://xxx.xx.xx.xxx:80/courses_development/_search?pretty -d '{"query":{"bool":{"must":{"dis_max":{"queries":[{"bool":{"must":{"bool":{"should":[{"match":{"name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"instructor_name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"description.word_start":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"description.word_start":{"query":"Elasticsearch","boost":50.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"description.analyzed":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}}}}]}},"filter":[{"term":{"institute_id":113}}]}},"size":1000,"from":0,"timeout":"11s","_source":false}'
=> #<Searchkick::Results:0x007fcb8f2893a0
 @klass=nil,
 @options=
  {:page=>1,
   :per_page=>1000,
   :padding=>0,
   :load=>true,
   :includes=>nil,
   :model_includes=>nil,
   :json=>false,
   :match_suffix=>:word_start,
   :highlighted_fields=>[],
   :misspellings=>true},
 @response=
  {"took"=>32,
   "timed_out"=>false,
   "_shards"=>{"total"=>5, "successful"=>5, "skipped"=>0, "failed"=>0},
   "hits"=>
    {"total"=>2,
     "max_score"=>19030.512,
     "hits"=>
      [{"_index"=>"courses_development_20171204170257200",
        "_type"=>"course",
        "_id"=>"4792",
        "_score"=>19030.512},
       {"_index"=>"courses_development_20171204170257200",
        "_type"=>"course",
        "_id"=>"4782",
        "_score"=>14400.825}]}}>
</code>```

答:
```<code>        def self.reindex_course
            index = Course.reindex(async: true, refresh_interval: "5s")
            Course.search_index.promote(index[:index_name], update_refresh_interval: true)
            Course.search_index.clean_indices
          end
</code>```

Looks like calling Course.search_index.clean_indices in the last line would clean old indices.  I think you may want to call it in the first line, or do not call it at all.

Body:
When I try to reindex records from inside a model it ends up setting an empty index on elasticsearch server.

So, I have a Course model which has many Instructors.
Now, I have this callback method inside instructor.rb model which tries to reindex whenever something is updated on Instructor.

class Instructor < ActiveRecord::Base
belongs_to :teacher, :class_name => "User", :foreign_key => "user_id"
belongs_to :instructorable, polymorphic: true
after_commit :reindex_course

private

  def reindex_course
     Course.reindex_course
  end
end

course.rb model looks like this:

    class Course < ActiveRecord::Base
        has_many :instructors, as: :instructorable, dependent: :destroy

searchkick word_start: [ :name, :description, :instructor_name]

def search_data
      {
      name: name,
      description: description,
      searchable: searchable,
      }.merge(
        instructor_name: instructors.includes(:teacher).pluck(:'users.name').reject(&:nil?),
      institute_id: creator.try(:institute_id)
)
            def self.reindex_course
                index = Course.reindex(async: true, refresh_interval: "5s")
                Course.search_index.promote(index[:index_name], update_refresh_interval: true)
                Course.search_index.clean_indices
              end
    end

Creating a new Instructor leads to reindexing of records

Instructor.create(user_id: 4009,instructorable_id: 4792, instructorable_type:"ScheduledCourse")
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_aliases response_code=200 return_code=ok total_time=0.630504
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development_20171204162604885 response_code=200 return_code=ok total_time=0.922072
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_alias/courses_development response_code=200 return_code=ok total_time=0.29790799999999995
       (5.0ms)  SELECT MIN("courses"."id") FROM "courses" LEFT OUTER JOIN "users" ON "users"."id" = "courses"."creator_id" LEFT OUTER JOIN "units" ON "units"."course_id" = "courses"."id" LEFT OUTER JOIN "instructors" ON "instructors"."instructorable_id" = "courses"."id" AND "instructors"."instructorable_type" = $1  [["instructorable_type", "Course"]]
       (4.4ms)  SELECT MAX("courses"."id") FROM "courses" LEFT OUTER JOIN "users" ON "users"."id" = "courses"."creator_id" LEFT OUTER JOIN "units" ON "units"."course_id" = "courses"."id" LEFT OUTER JOIN "instructors" ON "instructors"."instructorable_id" = "courses"."id" AND "instructors"."instructorable_type" = $1  [["instructorable_type", "Course"]]
    Enqueued Searchkick::BulkReindexJob (Job ID: d710eff3-5e39-4347-b02a-5459bfd4b1be) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>1, :min_id=>2, :max_id=>1001}
    Enqueued Searchkick::BulkReindexJob (Job ID: f0bf5866-f3da-42dd-9132-2de23735fbf4) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>2, :min_id=>1002, :max_id=>2001}
    Enqueued Searchkick::BulkReindexJob (Job ID: 348e07b8-a85a-4a9f-a2f2-d2b70416d2bf) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>3, :min_id=>2002, :max_id=>3001}
    Enqueued Searchkick::BulkReindexJob (Job ID: e40f2a33-e2f7-4f77-9416-920d84e285e7) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>4, :min_id=>3002, :max_id=>4001}
    Enqueued Searchkick::BulkReindexJob (Job ID: 18b357c1-cd53-4836-8aaf-4c97dde56281) to Sidekiq(searchkick) with arguments: {:class_name=>"Course", :index_name=>"courses_development_20171204162604885", :batch_id=>5, :min_id=>4002, :max_id=>5001}
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development_20171204162604885/_settings response_code=200 return_code=ok total_time=0.372641
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_alias/courses_development response_code=200 return_code=ok total_time=0.333225
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_aliases response_code=200 return_code=ok total_time=0.42405099999999996
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/_aliases response_code=200 return_code=ok total_time=0.382619
    ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development_20171204162504480 response_code=200 return_code=ok total_time=0.408705

Now when I run this query:

Searchkick.search search_params[:search], operator: "or",
           index_name: [Course],
           where:{institute_id: institute_id, searchable: true},
           fields: ['name^100','instructor_name^100','description^50'],
           match: :word_start, misspellings: {edit_distance: 2},
           page: search_params[:page],per_page: 20,
           order: {_score: :desc}

I get an empty response:

ETHON: performed EASY effective_url=http://xx:xxxx@xy.xyz.xx.xyz/elasticsearch/courses_development/_search response_code=200 return_code=ok total_time=0.733799
  Search (738.0ms)  curl http://xx.xxx.xx.xxx:80/courses_development/_search?pretty -d '{"query":{"bool":{"must":{"dis_max":{"queries":[{"bool":{"must":{"bool":{"should":[{"match":{"name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"instructor_name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"description.word_start":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"description.word_start":{"query":"Elasticsearch","boost":50.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"description.analyzed":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}}}}]}},"filter":[{"term":{"institute_id":113}},{"term":{"searchable":true}}]}},"size":1000,"from":0,"timeout":"11s","_source":false}'
=> #<Searchkick::Results:0x007fcb8c9cb378
 @klass=nil,
 @options=
  {:page=>1,
   :per_page=>1000,
   :padding=>0,
   :load=>true,
   :includes=>nil,
   :model_includes=>nil,
   :json=>false,
   :match_suffix=>:word_start,
   :highlighted_fields=>[],
   :misspellings=>true},
 @response=
  {"took"=>1,
   "timed_out"=>false,
   "_shards"=>{"total"=>5, "successful"=>5, "skipped"=>0, "failed"=>0},
   "hits"=>{"total"=>0, "max_score"=>nil, "hits"=>[]}}>

However, when i run Course.reindex(from console or model) or RAILS_ENV=development bundle exec rake searchkick:reindex CLASS=Course --trace form terminal it again starts working.

[33] pry(main)> Searchkick.search "Elasticsearch", operator: "or",index_name: [Course],where:{institute_id: 113, searchable: true},fields: ['name^100','instructor_name^100','description^50'],match: :word_start,misspellings: {edit_distance: 2}
ETHON: performed EASY effective_url=http://xx:xx@xxx.xx.xx.xxx/elasticsearch/courses_development/_search response_code=200 return_code=ok total_time=0.57072
  Search (573.5ms)  curl http://xxx.xx.xx.xxx:80/courses_development/_search?pretty -d '{"query":{"bool":{"must":{"dis_max":{"queries":[{"bool":{"must":{"bool":{"should":[{"match":{"name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"instructor_name.word_start":{"query":"Elasticsearch","boost":100.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"instructor_name.analyzed":{"query":"Elasticsearch","boost":1000.0,"operator":"or","analyzer":"searchkick_word_search"}}}}},{"bool":{"must":{"bool":{"should":[{"match":{"description.word_start":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}},{"match":{"description.word_start":{"query":"Elasticsearch","boost":50.0,"operator":"or","analyzer":"searchkick_word_search","fuzziness":2,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"should":{"match":{"description.analyzed":{"query":"Elasticsearch","boost":500.0,"operator":"or","analyzer":"searchkick_word_search"}}}}}]}},"filter":[{"term":{"institute_id":113}}]}},"size":1000,"from":0,"timeout":"11s","_source":false}'
=> #<Searchkick::Results:0x007fcb8f2893a0
 @klass=nil,
 @options=
  {:page=>1,
   :per_page=>1000,
   :padding=>0,
   :load=>true,
   :includes=>nil,
   :model_includes=>nil,
   :json=>false,
   :match_suffix=>:word_start,
   :highlighted_fields=>[],
   :misspellings=>true},
 @response=
  {"took"=>32,
   "timed_out"=>false,
   "_shards"=>{"total"=>5, "successful"=>5, "skipped"=>0, "failed"=>0},
   "hits"=>
    {"total"=>2,
     "max_score"=>19030.512,
     "hits"=>
      [{"_index"=>"courses_development_20171204170257200",
        "_type"=>"course",
        "_id"=>"4792",
        "_score"=>19030.512},
       {"_index"=>"courses_development_20171204170257200",
        "_type"=>"course",
        "_id"=>"4782",
        "_score"=>14400.825}]}}>

Body:
        def self.reindex_course
            index = Course.reindex(async: true, refresh_interval: "5s")
            Course.search_index.promote(index[:index_name], update_refresh_interval: true)
            Course.search_index.clean_indices
          end

Looks like calling Course.search_index.clean_indices in the last line would clean old indices.  I think you may want to call it in the first line, or do not call it at all.


来源: stackexchange

问:
Is it possible to show model help text as a title attribute on forms in Django?
I want to show the model field help_text as an HTML title attribute in a form, instead of it being appended to the end of the line, as is the default.

I like all the information about a model Field being in one place (in the Model definition itself), and would therefore not like to specify a custom title for each widget. It is okay, however, if there is a way to specify that the title attribute of each of widgets should be equal to the value of help_text. Is that possible? I'm looking for something to the effect of:

```<code>widgets = {'url':TextInput(attrs={'title': help_text})}
</code>```

The only other way I can think of doing this, is to make custom widgets for every single one of the built-in Widget types. Is there an easier, lazier way to achieve the same effect?

Using Javascript is also an option, but that would really only be a very far-off last resort. I'm thinking that this has to be a rather common use-case; how have you guys handled it in the past?

答:
```<code>Model._meta.get_field('field').help_text
</code>```

In your case

```<code>widgets = {'url':TextInput(attrs={'title': Model._meta.get_field('url').help_text})}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to show the model field help_text as an HTML title attribute in a form, instead of it being appended to the end of the line, as is the default.

I like all the information about a model Field being in one place (in the Model definition itself), and would therefore not like to specify a custom title for each widget. It is okay, however, if there is a way to specify that the title attribute of each of widgets should be equal to the value of help_text. Is that possible? I'm looking for something to the effect of:

widgets = {'url':TextInput(attrs={'title': help_text})}

The only other way I can think of doing this, is to make custom widgets for every single one of the built-in Widget types. Is there an easier, lazier way to achieve the same effect?

Using Javascript is also an option, but that would really only be a very far-off last resort. I'm thinking that this has to be a rather common use-case; how have you guys handled it in the past?

Body:
Model._meta.get_field('field').help_text

In your case

widgets = {'url':TextInput(attrs={'title': Model._meta.get_field('url').help_text})}


问:
multiple ng-repeat is no work
using angularJs, code like this:

```<code> <td ng-repeat="i in data.numArr3">
    <select ng-model="num{{i}}"  ng-change="change()">
        <option  ng-repeat="item in data.numArr3" value="{{item}}">{{item}}</option>
    </select>
</td>
</code>```

controller:

```<code>$scope.data = {
    numArr2: [0,1,2,3,4,5,6,7,8,9,10],

    numArr3: ["-0",-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],
    }
</code>```

It won't work;
I just want to create 11 selects, which have same options.
thanks~

答:
You can do this using controllerAs

change your controller to ng-controller="myCtrl as vm"

access scope variable like this

```<code>ng-repeat="i in vm.data.numArr3"
</code>```

Demo

var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
var vm = this;
vm.num ={}
vm.data = {
    numArr2: [0,1,2,3,4,5,6,7,8,9,10],

    numArr3: ["-0",-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<table>
  <tr>
   <td ng-repeat="i in vm.data.numArr3">
    <select ng-model="vm.num[i]"  ng-change="vm.change()">
        <option  ng-repeat="item in vm.data.numArr3" value="{{item}}">{{item}}</option>
    </select>
   </td>
  </tr>
</table>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: multiple ng-repeat is no work

Body:
using angularJs, code like this:

    <select ng-model="num{{i}}"  ng-change="change()">
        <option  ng-repeat="item in data.numArr3" value="{{item}}">{{item}}</option>
    </select>

controller:

$scope.data = {
    numArr2: [0,1,2,3,4,5,6,7,8,9,10],

    numArr3: ["-0",-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],
    }

It won't work;
I just want to create 11 selects, which have same options.
thanks~

Body:
You can do this using controllerAs

change your controller to ng-controller="myCtrl as vm"

access scope variable like this

ng-repeat="i in vm.data.numArr3"

Demo

var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
var vm = this;
vm.num ={}
vm.data = {
    numArr2: [0,1,2,3,4,5,6,7,8,9,10],

    numArr3: ["-0",-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<table>
  <tr>
   <td ng-repeat="i in vm.data.numArr3">
    <select ng-model="vm.num[i]"  ng-change="vm.change()">
        <option  ng-repeat="item in vm.data.numArr3" value="{{item}}">{{item}}</option>
    </select>
   </td>
  </tr>
</table>
</div>


问:
Initial job has not accepted any resources
My question is similar to other posters reporting on "Initial job has not accepted any resources". I read their suggestions and still not able to submit the job from Java. I am wondering if somebody with more experience installing Spark sees an obvious miss or knows how to troubleshoot this?

Spark : check your cluster UI to ensure that workers are registered.

My configuration is as follows:
(VM Fedora)
MASTER: version 2.0.2, prebuilt w/ hadoop.
WORKER: single instance.

(Host/Windows Java app)
Client is a sample JavaApp, configured with

```<code>conf.set("spark.cores.max","1");
conf.set("spark.shuffle.service.enabled", "false");
conf.set("spark.dynamicAllocation.enabled", "false");
</code>```

Attached is a snapshot of Spark UI. As far as I can tell my job is received, submitted and running. It also appears that I am not over-utilizing CPU and RAM.

Java(client) console reports

```<code>12:15:47.816 DEBUG parentName: , name: TaskSet_0, runningTasks: 0
12:15:48.815 DEBUG parentName: , name: TaskSet_0, runningTasks: 0
12:15:49.806 WARN Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
12:15:49.816 DEBUG parentName: , name: TaskSet_0, runningTasks: 0
12:15:50.816 DEBUG parentName: , name: TaskSet_0, runningTasks: 0
</code>```

Spark worker log reports.

```<code>16/11/22 12:16:34 INFO Worker: Asked to launch executor app-20161122121634-0012/0 for Simple
Application
16/11/22 12:16:34 INFO SecurityManager: Changing modify acls groups to:
16/11/22 12:16:34 INFO SecurityManager: SecurityManager: authentication disabled; ui acls dis
abled; users  with view permissions: Set(john); groups with view permissions: Set(); users
 with modify permissions: Set(john); groups with modify permissions: Set()
16/11/22 12:16:34 INFO ExecutorRunner: Launch command: "/apps/jdk1.8.0_101/jre/bin/java" "-cp " "/apps/spark-2.0.2-bin-hadoop2.7/conf/:/apps/spark-2.0.2-bin-hadoop2.7/jars/*" "-Xmx1024M" "-Dspark.driver.port=29015" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "spark://CoarseGrainedScheduler@192.168.56.1:29015" "--executor-id" "0" "--hostname" "192.168.56.103" "--cores" "1" "--app-id" "app-20161122121634-0012" "--worker-url" "spark://Worker@192.168.56.103:38701"
</code>```

答:
Do you have any firewall blocking communications? As stated in my other answer:

Apache Spark on Mesos: Initial job has not accepted any resources:

While most of other answers focuses on resource allocation (cores, memory) on spark slaves, I would like to highlight that firewall could cause exactly the same issue, especially when you are running spark on cloud platforms.

If you can find spark slaves in the web UI, you have probably opened the standard ports 8080, 8081, 7077, 4040. Nonetheless, when you actually run a job, it uses SPARK_WORKER_PORT, spark.driver.port and spark.blockManager.port which by default are randomly assigned. If your firewall is blocking these ports, the master could not retrieve any job-specific response from slaves and return the error.

You can run a quick test by opening all the ports and see whether the slave accepts jobs.

Body:
My question is similar to other posters reporting on "Initial job has not accepted any resources". I read their suggestions and still not able to submit the job from Java. I am wondering if somebody with more experience installing Spark sees an obvious miss or knows how to troubleshoot this?

Spark : check your cluster UI to ensure that workers are registered.

My configuration is as follows:
(VM Fedora)
MASTER: version 2.0.2, prebuilt w/ hadoop.
WORKER: single instance.

(Host/Windows Java app)
Client is a sample JavaApp, configured with

conf.set("spark.cores.max","1");
conf.set("spark.shuffle.service.enabled", "false");
conf.set("spark.dynamicAllocation.enabled", "false");

Attached is a snapshot of Spark UI. As far as I can tell my job is received, submitted and running. It also appears that I am not over-utilizing CPU and RAM.

Java(client) console reports

12:15:47.816 DEBUG parentName: , name: TaskSet_0, runningTasks: 0
12:15:48.815 DEBUG parentName: , name: TaskSet_0, runningTasks: 0
12:15:49.806 WARN Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
12:15:49.816 DEBUG parentName: , name: TaskSet_0, runningTasks: 0
12:15:50.816 DEBUG parentName: , name: TaskSet_0, runningTasks: 0

Spark worker log reports.

16/11/22 12:16:34 INFO Worker: Asked to launch executor app-20161122121634-0012/0 for Simple
Application
16/11/22 12:16:34 INFO SecurityManager: Changing modify acls groups to:
16/11/22 12:16:34 INFO SecurityManager: SecurityManager: authentication disabled; ui acls dis
abled; users  with view permissions: Set(john); groups with view permissions: Set(); users
 with modify permissions: Set(john); groups with modify permissions: Set()
16/11/22 12:16:34 INFO ExecutorRunner: Launch command: "/apps/jdk1.8.0_101/jre/bin/java" "-cp " "/apps/spark-2.0.2-bin-hadoop2.7/conf/:/apps/spark-2.0.2-bin-hadoop2.7/jars/*" "-Xmx1024M" "-Dspark.driver.port=29015" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "spark://CoarseGrainedScheduler@192.168.56.1:29015" "--executor-id" "0" "--hostname" "192.168.56.103" "--cores" "1" "--app-id" "app-20161122121634-0012" "--worker-url" "spark://Worker@192.168.56.103:38701"


问:
OpenCV doesn't save the video
I'm using the following code to read a video from file, apply the canny edge algorithm and write the modified video to a file. The code compiles and runs perfectly. But, the video is not written! I'm utterly confused. Please tell me what the error is.
The file is not created at all! OS: Ubuntu 12.10

Code for writing to the output file

Opening the output file

```<code>bool setOutput(const std::string &filename, int codec=0, double framerate=0.0, bool isColor=true) {

    outputFile= filename;
    extension.clear();

    if (framerate==0.0)
        framerate= getFrameRate(); // same as input

    char c[4];
    // use same codec as input
    if (codec==0) {
        codec= getCodec(c);
    }

    // Open output video
    return writer.open(outputFile, // filename
    codec, // codec to be used
    framerate,      // frame rate of the video
    getFrameSize(), // frame size
    isColor);       // color video?
}
</code>```

Writing the frame

```<code>void writeNextFrame (Mat& frame)
{
    writer.write (frame);
}
</code>```

And there's a separate run method which executes these

答: I had the same problem and I changed the codecs to DIVX. Now the video is saved in both .avi and .mp4 formats.</p>

Title: OpenCV doesn't save the video

Body:
I'm using the following code to read a video from file, apply the canny edge algorithm and write the modified video to a file. The code compiles and runs perfectly. But, the video is not written! I'm utterly confused. Please tell me what the error is.
The file is not created at all! OS: Ubuntu 12.10

Code for writing to the output file

Opening the output file

bool setOutput(const std::string &filename, int codec=0, double framerate=0.0, bool isColor=true) {

    outputFile= filename;
    extension.clear();

    if (framerate==0.0)
        framerate= getFrameRate(); // same as input

    char c[4];
    // use same codec as input
    if (codec==0) {
        codec= getCodec(c);
    }

    // Open output video
    return writer.open(outputFile, // filename
    codec, // codec to be used
    framerate,      // frame rate of the video
    getFrameSize(), // frame size
    isColor);       // color video?
}

Writing the frame

void writeNextFrame (Mat& frame)
{
    writer.write (frame);
}

And there's a separate run method which executes these


问:
Multiple media queries in css not working
I have multiple queries in my stylesheet where the code@media only screen and (min-width : 768px) and (max-width : 1024px) { } works perfectly fine but under it I have @media screen and (min-device-width : 176px) (max-device-width : 360px) {} does not work.

CSS:

```<code>@media only screen and (min-width : 768px) and (max-width : 1024px) {
body {background: red; } }

@media screen and (min-device-width : 176px) (max-device-width : 360px) {
body {background: green; } }
</code>```

答:
For multiple width for same style, use ,:

```<code>@media (max-width: 360px), (max-width: 768px) {

    /* style goes here */

}
</code>```

Body:
I have multiple queries in my stylesheet where the code@media only screen and (min-width : 768px) and (max-width : 1024px) { } works perfectly fine but under it I have @media screen and (min-device-width : 176px) (max-device-width : 360px) {} does not work.

CSS:

@media only screen and (min-width : 768px) and (max-width : 1024px) {
body {background: red; } }

@media screen and (min-device-width : 176px) (max-device-width : 360px) {
body {background: green; } }

Body:
For multiple width for same style, use ,:

@media (max-width: 360px), (max-width: 768px) {

    /* style goes here */

}


问:
Extract phone number from TextView text
I have a TextView with following words:

Google LLC is an 123 American multinational technology 456 company that specializes in Internet-related services and products. These include online advertising technologies, search, cloud computing, software, and hardware. Google was founded in 1998 by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University. Please call (123) 4444-3343

I want to make the number (123) 4444-3343 to a clickable one and taps it will have the user go to the calling mode.

I have tried following code:

```<code>textView.setAutoLinkMask(Linkify.PHONE_NUMBERS);
textView.setMovementMethod(LinkMovementMethod.getInstance());
</code>```

It doesn't work at all. I only want the (123) 4444-3343 to be clickable. How can I achieve this? Thanks.

答:
first option u have is to add in your XML android:autoLink="phone" to your textView

the second option u have is to use Html.fromHtml

```<code>txt.setText(Html.fromHtml("..." +
                "Please call <a href=\"tel:123-456-7890\">(123) 456-7890</a>"));
        txt.setMovementMethod(LinkMovementMethod.getInstance());
        txt.setAutoLinkMask(Linkify.PHONE_NUMBERS);
</code>```

another way is to use  ClickableSpan more info u can find here
How to set the part of the text view is clickable and here

Title: Extract phone number from TextView text

Body:
I have a TextView with following words:

Google LLC is an 123 American multinational technology 456 company that specializes in Internet-related services and products. These include online advertising technologies, search, cloud computing, software, and hardware. Google was founded in 1998 by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University. Please call (123) 4444-3343

I want to make the number (123) 4444-3343 to a clickable one and taps it will have the user go to the calling mode.

I have tried following code:

textView.setAutoLinkMask(Linkify.PHONE_NUMBERS);
textView.setMovementMethod(LinkMovementMethod.getInstance());

It doesn't work at all. I only want the (123) 4444-3343 to be clickable. How can I achieve this? Thanks.

Body:
first option u have is to add in your XML android:autoLink="phone" to your textView

the second option u have is to use Html.fromHtml

txt.setText(Html.fromHtml("..." +
                "Please call <a href=\"tel:123-456-7890\">(123) 456-7890</a>"));
        txt.setMovementMethod(LinkMovementMethod.getInstance());
        txt.setAutoLinkMask(Linkify.PHONE_NUMBERS);

another way is to use  ClickableSpan more info u can find here
How to set the part of the text view is clickable and here


问:
Storing multiple integers in a string
I am trying to store 5 integers into a string, but I am having trouble. Here is the code:

```<code>for (int a = 0; a < 5; a++)
        {
            string ans;
            int number;
            int num;
            number = rand() % 9 + 1;
            cout << number << " ";
            num = number;
            to_string(num);
            ans =+ num;
        }
</code>```

Essentially, I would like "ans" to be something along the lines of "12345" but when I run it, it either doesn't show anything or shows 5 boxes with question marks inside of them. Any help?

答:
to_string() returns a string.
You can simply try doing:
ans += to_string(num);

Or, better way to write your code for improved readability is to use a temporary string variable instead of an int num to store the number.

```<code>    string temp;
    string ans;
    for (int a = 0; a < 5; a++)
    {
        //string ans;
        int number;
        //int num;
        number = rand() % 9 + 1;
        cout << number << " ";
        //num = number;
        temp = to_string(number);
        ans += temp;
    }
</code>```

You do not want to declare your string ans inside the for loop because every time the loop runs, you ans will not hold the previous value anymore as it gets declared again.

Title: Storing multiple integers in a string

Body:
I am trying to store 5 integers into a string, but I am having trouble. Here is the code:

for (int a = 0; a < 5; a++)
        {
            string ans;
            int number;
            int num;
            number = rand() % 9 + 1;
            cout << number << " ";
            num = number;
            to_string(num);
            ans =+ num;
        }

Essentially, I would like "ans" to be something along the lines of "12345" but when I run it, it either doesn't show anything or shows 5 boxes with question marks inside of them. Any help?

Body:
to_string() returns a string.
You can simply try doing:
ans += to_string(num);

Or, better way to write your code for improved readability is to use a temporary string variable instead of an int num to store the number.

    string temp;
    string ans;
    for (int a = 0; a < 5; a++)
    {
        //string ans;
        int number;
        //int num;
        number = rand() % 9 + 1;
        cout << number << " ";
        //num = number;
        temp = to_string(number);
        ans += temp;
    }

You do not want to declare your string ans inside the for loop because every time the loop runs, you ans will not hold the previous value anymore as it gets declared again.


问:
Code to keep the command window open after code finishes executing
So I’m learning about C# with visual Studio, I wrote a small program kind of like a “hello world”,
I remember that with C++ md Java there is a conman you wrote at the end of your code o hav the command window stay on after the program finishes running. My question is, or C#, what is that code or command I’m supposed to write so that when I debug it and it runs the command window doesn’t closes after I finish with he user input? </p>

答:
You are looking for:

```<code>Console.Write("\nPress any key to continue... ");
Console.ReadLine();
</code>```

This will keep window open until you press Enter key

Body:
You are looking for:

Console.Write("\nPress any key to continue... ");
Console.ReadLine();

This will keep window open until you press Enter key


问:
Invalid Outside Procedure error with VBA
I am trying to combine several cells of data with the same label. There will either be 2 or 3 (also accounted for 1) repeated cells. I keep getting an invalid outside procedure error function. It highlights the "module module1" so I think it is something to do with defining my class, but I am not familar enough with VBA to figure it out. </p>

```<code>Module Module1
Public Sub Main()
    Dim num As Integer
    num = 2
    Dim val As Integer
    val = 2
    While num <= 5031
        If StrComp(Cells(num, 3).Value, Cells((num + 1), 3).Value, vbTextCompare) = 0 And StrComp(Cells(num, 3).Value, Cells((num + 1), 3).Value, vbTextCompare) = 0 Then
            Cells(val, 5) = Calls(num, 3).Value
            Cells(val, 6) = Add(Cells(num, 4).Value, Cells(num + 1, 4).Value, Cells(num + 2, 4).Value)
            num = num + 3
            val = val + 1
            End If
        ElseIf StrComp(Cells(num, 3).Value, Cells((num + 1), 3).Value, vbTextCompare) = 0 Then
            Cells(val, 5) = Calls(num, 3).Value
            Cells(val, 6) = Add(Cells(num, 4).Value, Cells(num + 1, 4).Value)
            num = num + 2
            val = val + 1
            End If
        Else
            Cells(val, 5) = Calls(num, 3).Value
            Cells(val, 6) = Cells(num, 4).Value
            num = num + 1
            val = val + 1
            End If

    Wend
End Sub
</code>```

答:
Delete the extra End If statements.  VBA If ... Then ... Else format is as follows:

```<code>If choice Then
    Statements...
ElseIf nextChoice Then
    Statements...
...as Many Elseif's as you need
Else
    Statements...
End If
</code>```

I believe that the VBA compiler is unable to recover from the extra End If statements

Body:
I am trying to combine several cells of data with the same label. There will either be 2 or 3 (also accounted for 1) repeated cells. I keep getting an invalid outside procedure error function. It highlights the "module module1" so I think it is something to do with defining my class, but I am not familar enough with VBA to figure it out.

Module Module1
Public Sub Main()
    Dim num As Integer
    num = 2
    Dim val As Integer
    val = 2
    While num <= 5031
        If StrComp(Cells(num, 3).Value, Cells((num + 1), 3).Value, vbTextCompare) = 0 And StrComp(Cells(num, 3).Value, Cells((num + 1), 3).Value, vbTextCompare) = 0 Then
            Cells(val, 5) = Calls(num, 3).Value
            Cells(val, 6) = Add(Cells(num, 4).Value, Cells(num + 1, 4).Value, Cells(num + 2, 4).Value)
            num = num + 3
            val = val + 1
            End If
        ElseIf StrComp(Cells(num, 3).Value, Cells((num + 1), 3).Value, vbTextCompare) = 0 Then
            Cells(val, 5) = Calls(num, 3).Value
            Cells(val, 6) = Add(Cells(num, 4).Value, Cells(num + 1, 4).Value)
            num = num + 2
            val = val + 1
            End If
        Else
            Cells(val, 5) = Calls(num, 3).Value
            Cells(val, 6) = Cells(num, 4).Value
            num = num + 1
            val = val + 1
            End If

    Wend
End Sub

Body:
Delete the extra End If statements.  VBA If ... Then ... Else format is as follows:

If choice Then
    Statements...
ElseIf nextChoice Then
    Statements...
...as Many Elseif's as you need
Else
    Statements...
End If

I believe that the VBA compiler is unable to recover from the extra End If statements


问:
How to write a complete binary tree predicate using Prolog
What is the algorithm of checking if a Binary tree is a complete binary tree? (Using Prolog).

For example:

```<code>?- complete(nil).
true.

?- complete(tree(1,nil,nil)).
true.

?- complete(tree(1,tree(2,nil,nil),nil)).
false.

?- complete(tree(1,tree(2,nil,nil),tree(3,nil,nil))).
true.
</code>```

答:
```<code>complete(T) :- complete(T, _).

complete(nil, 0).
complete(tree(_, L, R), N) :-
  complete(L, N1),
  complete(R, N1),
  N is N1 + 1.
</code>```

update:

It works for me:

```<code>?- complete(nil).
true.

?- complete(tree(1,nil,nil)).
true.

?- complete(tree(1,tree(2,nil,nil),nil)).
false.

?- complete(tree(1,tree(2,nil,nil),tree(3,nil,nil))).
true.
</code>```

Body:
What is the algorithm of checking if a Binary tree is a complete binary tree? (Using Prolog).

For example:

?- complete(nil).
true.

?- complete(tree(1,nil,nil)).
true.

?- complete(tree(1,tree(2,nil,nil),nil)).
false.

?- complete(tree(1,tree(2,nil,nil),tree(3,nil,nil))).
true.

Body:
complete(T) :- complete(T, _).

complete(nil, 0).
complete(tree(_, L, R), N) :-
  complete(L, N1),
  complete(R, N1),
  N is N1 + 1.

update:

It works for me:

?- complete(nil).
true.

?- complete(tree(1,nil,nil)).
true.

?- complete(tree(1,tree(2,nil,nil),nil)).
false.

?- complete(tree(1,tree(2,nil,nil),tree(3,nil,nil))).
true.


问:
I'm trying to clear the input field after the button is clicked
I need the input field to clear after the user clicks the button to convert the number they've entered. I'm having a difficult time figuring this out, if anyone can help i feel like it's a very simple solution but, I can't seem to wrap my head around it. </p>

```<code> (function () {
        //Constants
        const KM_TO_MILES = 0.625;
        const MILES_TO_KM = 1.6;

        var user = prompt("So..What's your name beautiful?");
        if (user === null) {
            alert("NOOOOO, you cancel me? meanie.")
            remove();
        }

        //on load function
        window.onload = function () {
            var result = document.getElementById("result");
            //display the user's name with a message prompt to continue to enter a distance
            result.innerHTML = "Okay, " + user + ", enter your distance and I will calculate for you, don't worry.";
            document.getElementById("convertBtn").onclick = startConvert;

        };
        //on load function done

        //conversion function
        function startConvert() {
            var placeholder = document.getElementById("distance").value;
            var distanceInput = document.getElementById("distance").value;
            var conversion = document.getElementById('List').value;
            document.getElementById("List").value;

            // If the user doesn't input a number run the alert
            if ((placeholder === "") || (conversion == "Select Types")) {

                alert("You didn't enter anything mate");
                // If the user inputs a number and clicks KM to M then calculate it and in the html page change the text to show the answer.
            } else if (conversion == "Kilometers to Miles") {

                document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * KM_TO_MILES + " miles.");

                // If the user inputs a number and clicks M to KM then calculate it and in the html page change the text to show the answer.
            } else if (conversion == "Miles to Kilometeres") {

                document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * MILES_TO_KM + " kilometers.");

            }

        }
        //conversion function done

    }());
</code>```

答:
```<code>document.getElementById('yourid').value = '';
</code>```

you call this event on your button click surely it'll be works

Body:
I need the input field to clear after the user clicks the button to convert the number they've entered. I'm having a difficult time figuring this out, if anyone can help i feel like it's a very simple solution but, I can't seem to wrap my head around it.

 (function () {
        //Constants
        const KM_TO_MILES = 0.625;
        const MILES_TO_KM = 1.6;

        var user = prompt("So..What's your name beautiful?");
        if (user === null) {
            alert("NOOOOO, you cancel me? meanie.")
            remove();
        }

        //on load function
        window.onload = function () {
            var result = document.getElementById("result");
            //display the user's name with a message prompt to continue to enter a distance
            result.innerHTML = "Okay, " + user + ", enter your distance and I will calculate for you, don't worry.";
            document.getElementById("convertBtn").onclick = startConvert;

        };
        //on load function done

        //conversion function
        function startConvert() {
            var placeholder = document.getElementById("distance").value;
            var distanceInput = document.getElementById("distance").value;
            var conversion = document.getElementById('List').value;
            document.getElementById("List").value;

            // If the user doesn't input a number run the alert
            if ((placeholder === "") || (conversion == "Select Types")) {

                alert("You didn't enter anything mate");
                // If the user inputs a number and clicks KM to M then calculate it and in the html page change the text to show the answer.
            } else if (conversion == "Kilometers to Miles") {

                document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * KM_TO_MILES + " miles.");

                // If the user inputs a number and clicks M to KM then calculate it and in the html page change the text to show the answer.
            } else if (conversion == "Miles to Kilometeres") {

                document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * MILES_TO_KM + " kilometers.");

            }

        }
        //conversion function done

    }());

Body:
document.getElementById('yourid').value = '';

you call this event on your button click surely it'll be works


问:
AVSpeechSynthesizer - emphasize certain words

Trying to add emphasis to specific words in text to speech.

```<code>import SpriteKit
import PlaygroundSupport
import AVFoundation

let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
let skview = SKView(frame: bounds)

PlaygroundPage.current.liveView = skview

var voices = [
   (volume: 0.5, rate: 0.5, text: "This is a "),
   (volume: 1.0, rate: 0.2, text: "HUGE"),
   (volume: 0.5, rate: 0.5, text: "deal") ]

   var utterances: [AVSpeechUtterance] = []
   for voice in voices {
       let utterance = AVSpeechUtterance(string: voice.text)
       utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
       utterance.volume = Float(voice.volume)
       utterance.rate = Float(voice.rate)
       utterance.preUtteranceDelay = 0
       utterance.postUtteranceDelay = 0
       utterances.append(utterance)
   }
   let synth = AVSpeechSynthesizer()
   for utterance in utterances {
       synth.speak(utterance)
   }
</code>```

I expect less of a pause between utterances. Above code should result in
"This is a .. HUGE .. Deal".

Whereas, the pauses are too long and the speech sounds disjointed (even though I have set the pre and post delays to 0).

"This is a ..... HUGE .... Deal".

Am I doing something wrong? Are there better techniques to add emphasis to speech?

This post on word stress suggests using ` symbol. However was looking for more effect.

答:
MacOS Cocoa Speech Synthesizer API supports TUNE format i.e. encoding of text with symbols for emphasis, volume changes, rate changes and other cool things. So I am going to synthesize my text to speech using Cocoa API, save as audio file and include the audio file as a resource in my iOS project. This of course will not work if the text to be spoken is dynamically generated within the iOS app.

Here is a Cocoa Playground to record the audio with emphasis.

```<code>import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let synth = NSSpeechSynthesizer(voice:         NSSpeechSynthesizer.VoiceName(rawValue: "com.apple.speech.synthesis.voice.samantha"))
synth?.volume = 0.5;
let saveURL = NSURL(fileURLWithPath: NSString(string: "~/Desktop/SpokenText.aiff").expandingTildeInPath);
synth?.startSpeaking( "This is a [[rate -100; volm + 0.5]]HUGE[[rate +100; volm - 0.5]]  deal", to:  saveURL as URL)
</code>```

Here is the Swift playground updated to play the saved audio file in iOS. Thanks to  response from Bill Chan over at discussion on playing AV within playground. (IMP: Import the recorded file as a resource in the playground first)

```<code>import SpriteKit
import PlaygroundSupport
import AVFoundation
let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
let skview = SKView(frame: bounds)
PlaygroundPage.current.liveView = skview
PlaygroundPage.current.needsIndefiniteExecution = true

let path = Bundle.main.path(forResource: "SpokenText", ofType: "aiff")!
let url = NSURL(fileURLWithPath: path)
var playerItem = AVPlayerItem(url: url as URL);
var player = AVPlayer(playerItem: playerItem)
var playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = bounds;
skview.layer.addSublayer(playerLayer)
player.play()
</code>```

Body:
Trying to add emphasis to specific words in text to speech.

import SpriteKit
import PlaygroundSupport
import AVFoundation

let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
let skview = SKView(frame: bounds)

PlaygroundPage.current.liveView = skview

var voices = [
   (volume: 0.5, rate: 0.5, text: "This is a "),
   (volume: 1.0, rate: 0.2, text: "HUGE"),
   (volume: 0.5, rate: 0.5, text: "deal") ]

   var utterances: [AVSpeechUtterance] = []
   for voice in voices {
       let utterance = AVSpeechUtterance(string: voice.text)
       utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
       utterance.volume = Float(voice.volume)
       utterance.rate = Float(voice.rate)
       utterance.preUtteranceDelay = 0
       utterance.postUtteranceDelay = 0
       utterances.append(utterance)
   }
   let synth = AVSpeechSynthesizer()
   for utterance in utterances {
       synth.speak(utterance)
   }

I expect less of a pause between utterances. Above code should result in
"This is a .. HUGE .. Deal".

Whereas, the pauses are too long and the speech sounds disjointed (even though I have set the pre and post delays to 0).

"This is a ..... HUGE .... Deal".

Am I doing something wrong? Are there better techniques to add emphasis to speech?

This post on word stress suggests using ` symbol. However was looking for more effect.

Body:
MacOS Cocoa Speech Synthesizer API supports TUNE format i.e. encoding of text with symbols for emphasis, volume changes, rate changes and other cool things. So I am going to synthesize my text to speech using Cocoa API, save as audio file and include the audio file as a resource in my iOS project. This of course will not work if the text to be spoken is dynamically generated within the iOS app.

Here is a Cocoa Playground to record the audio with emphasis.

import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let synth = NSSpeechSynthesizer(voice:         NSSpeechSynthesizer.VoiceName(rawValue: "com.apple.speech.synthesis.voice.samantha"))
synth?.volume = 0.5;
let saveURL = NSURL(fileURLWithPath: NSString(string: "~/Desktop/SpokenText.aiff").expandingTildeInPath);
synth?.startSpeaking( "This is a [[rate -100; volm + 0.5]]HUGE[[rate +100; volm - 0.5]]  deal", to:  saveURL as URL)

Here is the Swift playground updated to play the saved audio file in iOS. Thanks to  response from Bill Chan over at discussion on playing AV within playground. (IMP: Import the recorded file as a resource in the playground first)

import SpriteKit
import PlaygroundSupport
import AVFoundation
let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
let skview = SKView(frame: bounds)
PlaygroundPage.current.liveView = skview
PlaygroundPage.current.needsIndefiniteExecution = true

let path = Bundle.main.path(forResource: "SpokenText", ofType: "aiff")!
let url = NSURL(fileURLWithPath: path)
var playerItem = AVPlayerItem(url: url as URL);
var player = AVPlayer(playerItem: playerItem)
var playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = bounds;
skview.layer.addSublayer(playerLayer)
player.play()


问:
How to AutoSave as Cell Value with Command Button click in Vba Excel?
Looking to add a second function with the click of the command button in Excel with VBA code - first function populates data from worksheet one (an order form) to a database log in worksheet two.  Looking for the second function to be carried out to be an auto-save with cell value from the order form.  Thank you!</p>

```<code>Private Sub CommandButton1_Click()
    Dim OrderDate As String, PONumber As String, Vendor As String, ShipTo     As String, SKU As String
    Dim R As Long, LastSKURow As Long, NextDBRow As Long, OFrm As Worksheet, DB As Worksheet
    Set OFrm = Worksheets("Order Form 1")
    Set DB = Worksheets("Database")
    OrderDate = OFrm.Range("B3")
    PONumber = OFrm.Range("D3")
    Vendor = OFrm.Range("B7")
    ShipTo = OFrm.Range("D7")
    LastSKURow = OFrm.Cells(OFrm.Rows.Count, "F").End(xlUp).Row
    For R = 3 To LastSKURow
        SKU = OFrm.Range("F" & R).Value
        NextDBRow = DB.Cells(DB.Rows.Count, "A").End(xlUp).Row + 1
        DB.Range("A" & NextDBRow).Value = OrderDate
        DB.Range("B" & NextDBRow).Value = PONumber
        DB.Range("C" & NextDBRow).Value = Vendor
        DB.Range("D" & NextDBRow).Value = ShipTo
        DB.Range("E" & NextDBRow).Value = SKU
    Next R
    Application.ScreenUpdating = False
    Dim Path As String
    Dim filename As String
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,
        Path = "C:\PDF\"
        filename = OFrm.Range("D3")
        OFrm.SaveAs filename:=Path & filename & ".pdf", FileFormat:=xlPDF
        OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub
</code>```

答:
Sorry it took a few days, I've been quite busy.

Based on your previous comment this subroutine that I wrote should resolve your problem. I chose to save the file as a pdf with the assumption that you've set a print area to your form. I chose a pdf because you stated it was an order form and the assumption is that the form will not be edited later. I opted to it because it was a form and there may be some calculated fields attached to another sheet which would not work if you detached the worksheet. If however you decide that you just want a copy of the worksheet I've included the code for it as well. All you need to do is fill in the areas with the comments and attach this function to a command button :). Please let me know if you would like additional information about how to do this.

For the pdf function you can see the information here: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-exportasfixedformat-method-excel

For the Save As information you can see the information here: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/worksheet-saveas-method-excel

```<code>Public Sub savefile()

Dim wb As Workbook
Dim ws As Worksheet
Dim rngfilename As Range
Dim strSavePath As String

'assumptions:
'you are saving the file to a fixed location and the name of the file within the range is continually changing
'you have set the print areas

Set wb = Application.ActiveWorkbook
Set ws = wb.ActiveSheet
Set rngfilename = ws.Range("A1") 'the range that contains your filename
strSavePath = "C:/" 'the location that you would like to save your file

'ensure that there is a value within the filename field declared above
If rngfilename.Value = "" Or Len(rngfilename) = 0 Then
    MsgBox "You have not entered a filename"
    Exit Sub
End If

'if you do not have print areas set ignore print areas to true in the function bellow
ws.ExportAsFixedFormat xlTypePDF, strSavePath & rngfilename.Value, xlQualityStandard
'for the save as function
'ws.SaveAs strSavePathe & rngfilename.Value
End Sub
</code>```

Body:
Looking to add a second function with the click of the command button in Excel with VBA code - first function populates data from worksheet one (an order form) to a database log in worksheet two.  Looking for the second function to be carried out to be an auto-save with cell value from the order form.  Thank you!

Private Sub CommandButton1_Click()
    Dim OrderDate As String, PONumber As String, Vendor As String, ShipTo     As String, SKU As String
    Dim R As Long, LastSKURow As Long, NextDBRow As Long, OFrm As Worksheet, DB As Worksheet
    Set OFrm = Worksheets("Order Form 1")
    Set DB = Worksheets("Database")
    OrderDate = OFrm.Range("B3")
    PONumber = OFrm.Range("D3")
    Vendor = OFrm.Range("B7")
    ShipTo = OFrm.Range("D7")
    LastSKURow = OFrm.Cells(OFrm.Rows.Count, "F").End(xlUp).Row
    For R = 3 To LastSKURow
        SKU = OFrm.Range("F" & R).Value
        NextDBRow = DB.Cells(DB.Rows.Count, "A").End(xlUp).Row + 1
        DB.Range("A" & NextDBRow).Value = OrderDate
        DB.Range("B" & NextDBRow).Value = PONumber
        DB.Range("C" & NextDBRow).Value = Vendor
        DB.Range("D" & NextDBRow).Value = ShipTo
        DB.Range("E" & NextDBRow).Value = SKU
    Next R
    Application.ScreenUpdating = False
    Dim Path As String
    Dim filename As String
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,
        Path = "C:\PDF\"
        filename = OFrm.Range("D3")
        OFrm.SaveAs filename:=Path & filename & ".pdf", FileFormat:=xlPDF
        OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub

Body:
Sorry it took a few days, I've been quite busy.

Based on your previous comment this subroutine that I wrote should resolve your problem. I chose to save the file as a pdf with the assumption that you've set a print area to your form. I chose a pdf because you stated it was an order form and the assumption is that the form will not be edited later. I opted to it because it was a form and there may be some calculated fields attached to another sheet which would not work if you detached the worksheet. If however you decide that you just want a copy of the worksheet I've included the code for it as well. All you need to do is fill in the areas with the comments and attach this function to a command button :). Please let me know if you would like additional information about how to do this.

For the pdf function you can see the information here: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-exportasfixedformat-method-excel

For the Save As information you can see the information here: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/worksheet-saveas-method-excel

Public Sub savefile()

Dim wb As Workbook
Dim ws As Worksheet
Dim rngfilename As Range
Dim strSavePath As String

'assumptions:
'you are saving the file to a fixed location and the name of the file within the range is continually changing
'you have set the print areas

Set wb = Application.ActiveWorkbook
Set ws = wb.ActiveSheet
Set rngfilename = ws.Range("A1") 'the range that contains your filename
strSavePath = "C:/" 'the location that you would like to save your file

'ensure that there is a value within the filename field declared above
If rngfilename.Value = "" Or Len(rngfilename) = 0 Then
    MsgBox "You have not entered a filename"
    Exit Sub
End If

'if you do not have print areas set ignore print areas to true in the function bellow
ws.ExportAsFixedFormat xlTypePDF, strSavePath & rngfilename.Value, xlQualityStandard
'for the save as function
'ws.SaveAs strSavePathe & rngfilename.Value
End Sub


问:
Improve condition check
Need best  approach in the following scenario,

I've list of  attributes like source , destination, Yes/No as below:

```<code>Example:
source ,  destination , Yes/No
abc, bcd, Yes
abd, gdc, Yes
</code>```

In java  i can go with  condition like

```<code>if(Obj.getSource().equals("abc")) {
   if(Obj.getDest().equals("bcd")) {
      return true;
   }
}

if(Obj.getSource().equals("abd")) {
   if(Obj.getDest().equals("gdc")) {
      return true;
   }
}
</code>```

In this way i can handle the above case , based on the resultant Yes , i can handle my business logic.

But my approach was two many check  and , lines of codes to lengthy,
Please suggest me  good approach in java7 or java8.

答:
You can just combine all four conditions into one using logical operators. For example by using logical and && and logical or ||. It could then look like:

```<code>if ((first && second) || (third && fourth)) {
    return true;
}
</code>```

Or with all conditions substituted:

```<code>if ((Obj.getSource().equals("abc") && Obj.getDest().equals("bcd"))
        || (Obj.getSource().equals("abd") && Obj.getDest().equals("gdc"))) {
    return true;
}
</code>```

Note that you may memorize the result of Obj.getSource() and Obj.getDest() in a variable in order to save some performance and make the condition more readable by using that variable instead.

And if you would return false; in the other cases you could even completely leave out the whole if as you could directly return the boolean resulting after evaluating the condition (it evaluates to either true or false, no need to return true and false hardcoded then):

```<code>return (first && second) || (third && fourth);
</code>```

Title: Improve condition check

Body:
Need best  approach in the following scenario,

I've list of  attributes like source , destination, Yes/No as below:

Example:
source ,  destination , Yes/No
abc, bcd, Yes
abd, gdc, Yes

In java  i can go with  condition like

if(Obj.getSource().equals("abc")) {
   if(Obj.getDest().equals("bcd")) {
      return true;
   }
}

if(Obj.getSource().equals("abd")) {
   if(Obj.getDest().equals("gdc")) {
      return true;
   }
}

In this way i can handle the above case , based on the resultant Yes , i can handle my business logic.

But my approach was two many check  and , lines of codes to lengthy,
Please suggest me  good approach in java7 or java8.

Body:
You can just combine all four conditions into one using logical operators. For example by using logical and && and logical or ||. It could then look like:

if ((first && second) || (third && fourth)) {
    return true;
}

Or with all conditions substituted:

if ((Obj.getSource().equals("abc") && Obj.getDest().equals("bcd"))
        || (Obj.getSource().equals("abd") && Obj.getDest().equals("gdc"))) {
    return true;
}

Note that you may memorize the result of Obj.getSource() and Obj.getDest() in a variable in order to save some performance and make the condition more readable by using that variable instead.

And if you would return false; in the other cases you could even completely leave out the whole if as you could directly return the boolean resulting after evaluating the condition (it evaluates to either true or false, no need to return true and false hardcoded then):

return (first && second) || (third && fourth);


问:
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:exec (default) on project ors: The parameter 'executable' is missing or invalid
When i am trying to execute mvn -DskipTests=true -Passembly assembly:directory exec:exec command to make binary i am getting
 Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:exec (default) on project ors: The parameter 'executable' is missing or invalid error. i have also applied Source Target 1.8 inside configuration but still i am getting the same error.

```<code><profile>
      <id>execute</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
          <mainClass>org.marketcetera.ors.OrderRoutingSystem</mainClass>
          <systemProperties>
              <systemProperty>
                  <key>org.marketcetera.appDir</key>
                  <value>src/test/cmd_exec</value>
              </systemProperty>
          </systemProperties>
          <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <!-- Command-line execution of the ORS (with DB initialization). -->
    <profile>
      <id>executeDBInit</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
        <mainClass>org.marketcetera.ors.DBInit</mainClass>
        <arguments>
          <argument>org.marketcetera.ors.OrderRoutingSystem</argument>
        </arguments>
        <systemProperties>
          <systemProperty>
            <key>org.marketcetera.appDir</key>
            <value>src/test/cmd_exec</value>
          </systemProperty>
        </systemProperties>
        <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <!-- Command-line execution of the miniscule exchange. -->
    <profile>
      <id>exchange</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
        <mainClass>org.marketcetera.ors.exchange.Main</mainClass>
        <arguments>
          <argument>exchange.xml</argument>
        </arguments>
        <systemProperties>
          <systemProperty>
            <key>org.marketcetera.appDir</key>
            <value>src/test/cmd_exec</value>
          </systemProperty>
        </systemProperties>
        <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <!-- Security administration utility. -->
    <profile>
      <id>cli</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
        <mainClass>org.marketcetera.ors.security.ORSAdminCLI</mainClass>
        <!-- -Dexec.args="-u admin ..." -->
        <systemProperties>
          <systemProperty>
            <key>org.marketcetera.appDir</key>
            <value>src/test/cmd_exec</value>
          </systemProperty>
        </systemProperties>
        <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <!-- Assembly. -->
    <profile>
      <id>assembly</id>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
              <executions>
                  <execution>
                      <phase>package</phase>
                      <goals><goal>single</goal></goals>
                      <configuration>
                          <formats><format>dir</format></formats>
                          <descriptors>
                              <descriptor>src/main/assembly/assembly.xml</descriptor>
                          </descriptors>
                      </configuration>
                  </execution>
              </executions>
          </plugin>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <phase>package</phase>
                      <goals><goal>exec</goal></goals>
                      <configuration>
              <executable>${perl.path}</executable>
                          <arguments>
                              <argument>../tools/scripts/createScript.pl</argument>
                              <argument>${project.build.directory}/${project.artifactId}</argument>
                              <argument>ors</argument>
                              <argument>org.marketcetera.ors.OrderRoutingSystem</argument>
                              <argument>${project.build.directory}/${project.artifactId}</argument>
                              <argument>orsadmin</argument>
                              <argument>org.marketcetera.ors.security.ORSAdminCLI</argument>
                          </arguments>
                      </configuration>
                  </execution>
              </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
</code>```

答:
As of exec-maven-plugin version 1.6.0, it appears <configuration> sections within <execution> blocks are ignored unless you specify an id.

Try changing your command line, substituting exec:exec@foo for exec:exec with the plugin block changed to include an id foo as follows:

```<code>      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
          <executions>
              <execution>
                  <id>foo</id>
                  <phase>package</phase>
                  <goals><goal>exec</goal></goals>
                  <configuration>
          <executable>${perl.path}</executable>
                      <arguments>
                          <argument>../tools/scripts/createScript.pl</argument>
                          <argument>${project.build.directory}/${project.artifactId}</argument>
                          <argument>ors</argument>
                          <argument>org.marketcetera.ors.OrderRoutingSystem</argument>
                          <argument>${project.build.directory}/${project.artifactId}</argument>
                          <argument>orsadmin</argument>
                          <argument>org.marketcetera.ors.security.ORSAdminCLI</argument>
                      </arguments>
                  </configuration>
              </execution>
          </executions>
      </plugin>
</code>```

Body:
When i am trying to execute mvn -DskipTests=true -Passembly assembly:directory exec:exec command to make binary i am getting
 Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:exec (default) on project ors: The parameter 'executable' is missing or invalid error. i have also applied Source Target 1.8 inside configuration but still i am getting the same error.

<profile>
      <id>execute</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
          <mainClass>org.marketcetera.ors.OrderRoutingSystem</mainClass>
          <systemProperties>
              <systemProperty>
                  <key>org.marketcetera.appDir</key>
                  <value>src/test/cmd_exec</value>
              </systemProperty>
          </systemProperties>
          <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>executeDBInit</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
        <mainClass>org.marketcetera.ors.DBInit</mainClass>
        <arguments>
          <argument>org.marketcetera.ors.OrderRoutingSystem</argument>
        </arguments>
        <systemProperties>
          <systemProperty>
            <key>org.marketcetera.appDir</key>
            <value>src/test/cmd_exec</value>
          </systemProperty>
        </systemProperties>
        <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>exchange</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
        <mainClass>org.marketcetera.ors.exchange.Main</mainClass>
        <arguments>
          <argument>exchange.xml</argument>
        </arguments>
        <systemProperties>
          <systemProperty>
            <key>org.marketcetera.appDir</key>
            <value>src/test/cmd_exec</value>
          </systemProperty>
        </systemProperties>
        <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>cli</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <goals><goal>java</goal></goals>
                  </execution>
              </executions>
          <configuration>
        <mainClass>org.marketcetera.ors.security.ORSAdminCLI</mainClass>

        <systemProperties>
          <systemProperty>
            <key>org.marketcetera.appDir</key>
            <value>src/test/cmd_exec</value>
          </systemProperty>
        </systemProperties>
        <classpathScope>test</classpathScope>
          </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>assembly</id>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
              <executions>
                  <execution>
                      <phase>package</phase>
                      <goals><goal>single</goal></goals>
                      <configuration>
                          <formats><format>dir</format></formats>
                          <descriptors>
                              <descriptor>src/main/assembly/assembly.xml</descriptor>
                          </descriptors>
                      </configuration>
                  </execution>
              </executions>
          </plugin>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
              <executions>
                  <execution>
                      <phase>package</phase>
                      <goals><goal>exec</goal></goals>
                      <configuration>
              <executable>${perl.path}</executable>
                          <arguments>
                              <argument>../tools/scripts/createScript.pl</argument>
                              <argument>${project.build.directory}/${project.artifactId}</argument>
                              <argument>ors</argument>
                              <argument>org.marketcetera.ors.OrderRoutingSystem</argument>
                              <argument>${project.build.directory}/${project.artifactId}</argument>
                              <argument>orsadmin</argument>
                              <argument>org.marketcetera.ors.security.ORSAdminCLI</argument>
                          </arguments>
                      </configuration>
                  </execution>
              </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

Body:
As of exec-maven-plugin version 1.6.0, it appears <configuration> sections within <execution> blocks are ignored unless you specify an id.

Try changing your command line, substituting exec:exec@foo for exec:exec with the plugin block changed to include an id foo as follows:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
          <executions>
              <execution>
                  <id>foo</id>
                  <phase>package</phase>
                  <goals><goal>exec</goal></goals>
                  <configuration>
          <executable>${perl.path}</executable>
                      <arguments>
                          <argument>../tools/scripts/createScript.pl</argument>
                          <argument>${project.build.directory}/${project.artifactId}</argument>
                          <argument>ors</argument>
                          <argument>org.marketcetera.ors.OrderRoutingSystem</argument>
                          <argument>${project.build.directory}/${project.artifactId}</argument>
                          <argument>orsadmin</argument>
                          <argument>org.marketcetera.ors.security.ORSAdminCLI</argument>
                      </arguments>
                  </configuration>
              </execution>
          </executions>
      </plugin>


问:
Find missing element
I saw the following question:

Given an array A of integers, find an integer k that is not present in A. Assume that the integers are 32-bit signed integers.

How to solve it?

Thank you

//// update -- This is the provided solution - but I don't think it is correct ////
Consider a very simple hash function F(x)=x mod (n+1). we can build a bit-vector of length
n+1 that is initialized to 0 and for every element in A, we set bit F(A[i]) to 1.Since there are only n elements in the array, we can find the missing element easily.

I think the above solution is wrong.

For example,
A [ 2, 100, 4 ], then both 4 and 100 will match to the same place.

答:
If I'm interpreting the question correctly, (find any integer not in A) and n is the number of elements in A, then the answer is correct as given.

The fact that the hash function can have collisions doesn't really matter; By the pigeonhole principle in reverse, there will be some bit in the bit vector that is not set - because it has more bits than there are elements in A.  The corresponding value is an integer not in A.  In the case where the hash function has collisions, there will actually be more than one bit not set, which works in favor of the algorithm's correctness rather than against it.

To illustrate, here's how your example would work out:

```<code>A = [2, 100, 4]
n = length(A) = 3
f(x) = x mod 4
map(f,A) = [2, 0, 0]
</code>```

so the final bit vector will be:

```<code>[1,0,1,0]
</code>```

From there, we can arbitrarily choose any integer corresponding to any 0 bit, which in this case is any odd number.

Title: Find missing element

Body:
If I'm interpreting the question correctly, (find any integer not in A) and n is the number of elements in A, then the answer is correct as given.

The fact that the hash function can have collisions doesn't really matter; By the pigeonhole principle in reverse, there will be some bit in the bit vector that is not set - because it has more bits than there are elements in A.  The corresponding value is an integer not in A.  In the case where the hash function has collisions, there will actually be more than one bit not set, which works in favor of the algorithm's correctness rather than against it.

To illustrate, here's how your example would work out:

A = [2, 100, 4]
n = length(A) = 3
f(x) = x mod 4
map(f,A) = [2, 0, 0]

so the final bit vector will be:

[1,0,1,0]

From there, we can arbitrarily choose any integer corresponding to any 0 bit, which in this case is any odd number.


问:
Apache Spark and Mesos running on a single node
I am interested in testing Spark running on Mesos. I created a Hadoop 2.6.0 single-node cluster in my Virtualbox and installed Spark on it. I can successfully process files in HDFS using Spark.

Then I installed Mesos Master and Slave on the same node. I tried to run Spark as a framework in Mesos using these instructions. I get the following error with Spark:

WARN TaskSchedulerImpl: Initial job has not accepted any resources;

  check  your cluster UI to ensure that workers are registered and have
  sufficient resources

Sparkshell is successfully registered as a framework in the Mesos. Is there anything wrong with using a single-node setup? Or whether I need to add more Spark worker nodes?

I am very new to Spark and my aim is to just test Spark, HDFS, and Mesos.

答:
If you have allocated enough resources for spark slaves, the cause might be firewall blocking the communication. Take a look at my other answer:

Apache Spark on Mesos: Initial job has not accepted any resources


问:
Python Extract values from string and move onto next
I'm trying to extract strings that fit between the patterns '{"comments_disabled":' and '}},'
and then append whatever fits between these two patterns. (There could be 100+ occurances that match between these patterns.

The problem is that the code below just keeps extracting the first occurrence, how do I make it ignore what it previously appended to the userpost list and move onto the next?

```<code>from bs4 import BeautifulSoup
page = urlopen("https://www.instagram.com/explore/tags/fun/")
soup = BeautifulSoup(page,"html.parser")
title = soup.title
script = str(soup.findAll('script', type="text/javascript"))

userpost = list()

for text in script:
userpost.append(script[script.find('{"comments_disabled":')/
:script.find('}},')+2])
</code>```

答:
Try re.findall():

```<code>userpost = re.findall(r'{"comments disabled":(.*?)}},', script)
</code>```

Tested script:

```<code>import re

script = '''
{"comments disabled": one two }},
alpha beta
{"comments disabled": three four }},
{"comments disabled":
five six
}},
'''

userpost = re.findall(r'{"comments disabled":(.*?)}},', script, re.DOTALL)
print(userpost)
</code>```

Output:

```<code>[' one two ', ' three four ', '\nfive six\n']
</code>```

Body:
I'm trying to extract strings that fit between the patterns '{"comments_disabled":' and '}},'
and then append whatever fits between these two patterns. (There could be 100+ occurances that match between these patterns.

The problem is that the code below just keeps extracting the first occurrence, how do I make it ignore what it previously appended to the userpost list and move onto the next?

from bs4 import BeautifulSoup
page = urlopen("https://www.instagram.com/explore/tags/fun/")
soup = BeautifulSoup(page,"html.parser")
title = soup.title
script = str(soup.findAll('script', type="text/javascript"))

userpost = list()

for text in script:
userpost.append(script[script.find('{"comments_disabled":')/
:script.find('}},')+2])

Body:
Try re.findall():

userpost = re.findall(r'{"comments disabled":(.*?)}},', script)

Tested script:

import re

script = '''
{"comments disabled": one two }},
alpha beta
{"comments disabled": three four }},
{"comments disabled":
five six
}},
'''

userpost = re.findall(r'{"comments disabled":(.*?)}},', script, re.DOTALL)
print(userpost)

Output:

[' one two ', ' three four ', '\nfive six\n']


问:
Passing some id from Dropzone using Laravel
I'm having a Modal to upload images into the gallery like this:

```<code><div id="imagesModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
            <form name="imagesForm" id="addImages" class="form-horizontal dropzone" role="form" method="POST" action="{{ route('images.add') }}" enctype="multipart/form-data">
                {{ csrf_field() }}
                {{ method_field('POST') }}
            </form>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code>```

and here's my jquery script:

```<code>$( "#addImages" ).click(function(event) {
                event.preventDefault();
                save_method = 'add';
                $('input[name=_method]').val('POST');
                $('#imagesModal').modal("show");
                $('#imagesForm')[0].reset();
                $('.modal-title').text('Add Images')
            });

            Dropzone.options.addImages = {
                paramName: "images", // The name that will be used to transfer the file
                maxFilesize: 2, // MB
            };

and i already add the route and the function

   public function store(Request $request)
    {
        $gallery = Gallery::find($request->id);
        $path = 'public'.'/'.str_slug($gallery->name);

        foreach ($request->images as $file) {
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->size = $file->getClientSize();
            $image->save();

            // Or any custom name as the third argument
            Storage::putFileAs($path, $file, $file->getClientOriginalName());
        }

    }
</code>```

My problem is i don't know how i can pass the gallery id so i can access it into the function? I have some idea to put it on data-gallery-id in the button, but how can pass that data so it's going to be sent with the images?

答:
I don't think we can send along with images object. But you can do this way instead. You can create one input type hidden to store the image gallery id in your form ex:
After you submit the form you can get the $request->id in your controller.</p>

Body:
I'm having a Modal to upload images into the gallery like this:

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

            <form name="imagesForm" id="addImages" class="form-horizontal dropzone" role="form" method="POST" action="{{ route('images.add') }}" enctype="multipart/form-data">
                {{ csrf_field() }}
                {{ method_field('POST') }}
            </form>

and here's my jquery script:

$( "#addImages" ).click(function(event) {
                event.preventDefault();
                save_method = 'add';
                $('input[name=_method]').val('POST');
                $('#imagesModal').modal("show");
                $('#imagesForm')[0].reset();
                $('.modal-title').text('Add Images')
            });

            Dropzone.options.addImages = {
                paramName: "images", // The name that will be used to transfer the file
                maxFilesize: 2, // MB
            };

and i already add the route and the function

   public function store(Request $request)
    {
        $gallery = Gallery::find($request->id);
        $path = 'public'.'/'.str_slug($gallery->name);

        foreach ($request->images as $file) {
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->size = $file->getClientSize();
            $image->save();

            // Or any custom name as the third argument
            Storage::putFileAs($path, $file, $file->getClientOriginalName());
        }

    }

My problem is i don't know how i can pass the gallery id so i can access it into the function? I have some idea to put it on data-gallery-id in the button, but how can pass that data so it's going to be sent with the images?


答:
You can do something like this:</p>

```<code>string ans;
int number;

for (int a = 0; a < 5; a++){
    number = rand() % 9 + 1;
    ans += to_string(number);
}
cout << ans;
</code>```

Title: Storing multiple integers in a string

Body:
I am trying to store 5 integers into a string, but I am having trouble. Here is the code:

for (int a = 0; a < 5; a++)
        {
            string ans;
            int number;
            int num;
            number = rand() % 9 + 1;
            cout << number << " ";
            num = number;
            to_string(num);
            ans =+ num;
        }

Essentially, I would like "ans" to be something along the lines of "12345" but when I run it, it either doesn't show anything or shows 5 boxes with question marks inside of them. Any help?

Body:
You can do something like this:

string ans;
int number;

for (int a = 0; a < 5; a++){
    number = rand() % 9 + 1;
    ans += to_string(number);
}
cout << ans;