问:
Sudden ArgumentError: invalid byte sequence in UTF-8 while seeding
While working on my Rails app I was experimenting with some way to crop images, I went from Rails Casts #182 , back to what I previously had and then to this blog post, after finishing setting all up, I decided to restart my database and seed it, however I got ArgumentError: invalid byte sequence in UTF-8 when I tried to seed my db.

I've never encountered this error before and after some small research I found this is due to some characters not being able to be read by ruby, however, after skimming my code I've found no difference between what I had before I started with cropping images and after further examining I've yet to find the cause.

It also doesn't help that I've yet to learn how to read and trace rails/rake bugs, here is what I get:

```<code>rails aborted!
ArgumentError: invalid byte sequence in UTF-8
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `==='
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `blank?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:131:in `is_path?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:97:in `size'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:140:in `empty?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/uploader/cache.rb:120:in `cache!'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:44:in `block in cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `map'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mount.rb:300:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/orm/activerecord.rb:70:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `public_send'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `_assign_attribute'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/attribute_assignment.rb:26:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:33:in `assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/core.rb:319:in `initialize'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/persistence.rb:50:in `create!'
/home/ubuntu/workspace/db/seeds.rb:60:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `block in load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/engine.rb:549:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/tasks/database_tasks.rb:268:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/railties/databases.rake:196:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:14:in `block in run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:11:in `run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:51:in `run_command!'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
/home/ubuntu/workspace/bin/rails:9:in `require'
/home/ubuntu/workspace/bin/rails:9:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/command.rb:7:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client.rb:30:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/bin/spring:49:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `<top (required)>'
/home/ubuntu/workspace/bin/spring:15:in `require'
/home/ubuntu/workspace/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
</code>```

My main question is where exactly could this error be happening? so far I've learned through experience that it could be either the seeds.rb or the model( in this case event.rb) however I don't see anything different and I had them both working before, I was even able to upload images and seed them no problem until I implemented and removed the code from the Rails Cast and implemented the code in the blog post, any direction into the solution will be of great help.

Here is the seed from the model, it was working fine beforehand.

```<code>Event.create!(
    name: "  1",
    spanish_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    english_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    place_name: "mamita's",
    place_type: "beach club",
    address: "Calle 28 Norte Mza 10, Lote 8, Centro",
    county: 'meh',
    city: "Playa del Carmen",
    state: "Quintana Roo",
    postal_code: 77710,

    user_id: 1,
    main_image: File.open(File.join(Rails.root, 'test.jpg')),
    sub_images: [File.open(File.join(Rails.root, 'chinchi.jpg'))],

    eventdates_attributes:[{
      start_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      finish_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      start_hour: "08:00am",
      finish_hour: "11:00am",
    }],

    tickets_attributes:[{
      ticket_type: "Solo una vez",
      price: 100,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }, {
      ticket_type: "Otra vez",
      price: 150,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }]
)
</code>```

IMPORTANT EDIT: So I decided to just return to previous commits just to not deal with this problem anymore, and for some reason the error keeps popping up, which leads me to believe there is a problem with the platform I'm using, which is Cloud9, I've also read this isn't a problem that should be happening on Rails 5.0

答:
Not sure, It’s just an invalid byte sequence in your request URL, try this one:

add into your gemfile gem 'rack-utf8_sanitizer' or gem 'handle_invalid_percent_encoding_requests' or gem 'utf8-cleaner' after that run bundle install.

Body:
While working on my Rails app I was experimenting with some way to crop images, I went from Rails Casts #182 , back to what I previously had and then to this blog post, after finishing setting all up, I decided to restart my database and seed it, however I got ArgumentError: invalid byte sequence in UTF-8 when I tried to seed my db.

I've never encountered this error before and after some small research I found this is due to some characters not being able to be read by ruby, however, after skimming my code I've found no difference between what I had before I started with cropping images and after further examining I've yet to find the cause.

It also doesn't help that I've yet to learn how to read and trace rails/rake bugs, here is what I get:

rails aborted!
ArgumentError: invalid byte sequence in UTF-8
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `==='
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `blank?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:131:in `is_path?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:97:in `size'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:140:in `empty?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/uploader/cache.rb:120:in `cache!'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:44:in `block in cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `map'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mount.rb:300:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/orm/activerecord.rb:70:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `public_send'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `_assign_attribute'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/attribute_assignment.rb:26:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:33:in `assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/core.rb:319:in `initialize'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/persistence.rb:50:in `create!'
/home/ubuntu/workspace/db/seeds.rb:60:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `block in load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/engine.rb:549:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/tasks/database_tasks.rb:268:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/railties/databases.rake:196:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:14:in `block in run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:11:in `run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:51:in `run_command!'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
/home/ubuntu/workspace/bin/rails:9:in `require'
/home/ubuntu/workspace/bin/rails:9:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/command.rb:7:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client.rb:30:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/bin/spring:49:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `<top (required)>'
/home/ubuntu/workspace/bin/spring:15:in `require'
/home/ubuntu/workspace/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

My main question is where exactly could this error be happening? so far I've learned through experience that it could be either the seeds.rb or the model( in this case event.rb) however I don't see anything different and I had them both working before, I was even able to upload images and seed them no problem until I implemented and removed the code from the Rails Cast and implemented the code in the blog post, any direction into the solution will be of great help.

Here is the seed from the model, it was working fine beforehand.

Event.create!(
    name: "  1",
    spanish_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    english_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    place_name: "mamita's",
    place_type: "beach club",
    address: "Calle 28 Norte Mza 10, Lote 8, Centro",
    county: 'meh',
    city: "Playa del Carmen",
    state: "Quintana Roo",
    postal_code: 77710,

    user_id: 1,
    main_image: File.open(File.join(Rails.root, 'test.jpg')),
    sub_images: [File.open(File.join(Rails.root, 'chinchi.jpg'))],

    eventdates_attributes:[{
      start_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      finish_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      start_hour: "08:00am",
      finish_hour: "11:00am",
    }],

    tickets_attributes:[{
      ticket_type: "Solo una vez",
      price: 100,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }, {
      ticket_type: "Otra vez",
      price: 150,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }]
)

IMPORTANT EDIT: So I decided to just return to previous commits just to not deal with this problem anymore, and for some reason the error keeps popping up, which leads me to believe there is a problem with the platform I'm using, which is Cloud9, I've also read this isn't a problem that should be happening on Rails 5.0


来源: stackexchange

问:
Data type of time in Spring-Data-Rest
I want to store the time what data type should I used in spring framework ?
Database which I used is MySQL </p>

```<code>@Entity
public class ShopDetail {

@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;
    }
</code>```

答:
you can use date time format.

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/format/annotation/DateTimeFormat.html

Spring 3.2 Date time format

ContentLicense: CC BY-SA 3.0

Title: Data type of time in Spring-Data-Rest

Body:
I want to store the time what data type should I used in spring framework ?
Database which I used is MySQL

@Entity
public class ShopDetail {

@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;
    }


问:
Xcode 8 Table View Cells to Different Views
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

```<code>import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}
</code>```

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!

答:
Embedded your TableViewController in Navigation Controller ( Most probably , you already did ) .

Select Yellow marked TableViewController click Right Mouse hold and put it to a view controller , release and select Manual Segue -> Show

Now select segue and rename it with unique Identifier . For every view controller repeat steps 2 & 3  .

Update tableView didSelectRowAt delegate  function like below .

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
    performSegue(withIdentifier: orchard[indexPath.row], sender: self)
}

Body:
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!


问:
Android- How to implement Horizontal Step Progress Bar
I want to implement horizontal progress bar with steps like shown in following img.

I could not find such native component in Android. Can anyone guide me on how to do it ?

答:
I found a Vertical Steper that follows Google Material Design guidelines:

And also another well documented library Here

I hope it helps.


问:
How to remove an element found in an array and shift the array elements to the left?
```<code>int search(int a[]) {

   int i,V,index;
   printf("Enter the element (V),That you want to find:>");
   scanf("%d",&V);

   for (i=0;i<N;i++) {
       if(a[i]==V) {
           V=a[i];
           index=i;
       }
   }
   printf("%d is located in a[%d].",V,index
)
</code>```

答: Perhaps use a linked list, binary tree or other data structure that allows you to quickly search for and remove nodes containing the target data.</p>

ContentLicense: CC BY-SA 2.5


问:
Is it possible to git stash an interactive rebase in progress?
I am currently rebasing origin/master onto a branch that was created from origin/master a while ago and the developer that worked on the branch is not available right now.

I have resolved some conflicts on the first commits of the feature branch but come to a point where I must wait for the developer to know how to finalize the rebase.

Is there a way to keep the conflict resolution I already did (~30 minutes) so that I can move on to another task?

答: In future, you can use rerere, which will record your resolutions. This won't instantly get you back to 30 minutes into the rebase, but it should help a lot, basically you just confirm your resolutions up to the point where you stopped. I don't know why rerere doesn't come as standard with Git, it's so useful.</p>


问:
How to delete column name
I want to delete to just column name (x,y,z), and use only data.

```<code>In [68]: df
Out[68]:
   x  y  z
0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0
</code>```

I want to print result to same as below.

```<code>Out[68]:

0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0
</code>```

Is it possible? How can I do this?

答:
If all you need is to print out without the headers then you can use the to_string() and set header=False, e.g.:

```<code>>>> print(df.to_string(header=False))
0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to delete column name

Body:
I want to delete to just column name (x,y,z), and use only data.

In [68]: df
Out[68]:
   x  y  z
0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0

I want to print result to same as below.

Out[68]:

0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0

Is it possible? How can I do this?

Body:
If all you need is to print out without the headers then you can use the to_string() and set header=False, e.g.:

>>> print(df.to_string(header=False))
0  1  0  1
1  2  0  0
2  2  1  1
3  2  0  1
4  2  1  0


问:
Fabric JS - Split Multiple Lines IText
I am using Fabric JS for my project, I want to split multiple lines IText like image below:

split multiple lines on IText

Here is my code:

```<code>var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true
});

var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
  fontSize: 20,
  top: 80,
  left: 100,
  fontFamily: "Arial"
});

canvas.add(text);
canvas.renderAll();

$('#split').click(function() {

    var object = canvas.getActiveObject();

    if(!object) return false;

    if ((object.get('type') == 'i-text') && (object.getText().indexOf( "\n" ) > 0)) {

        var splitText = object.getText().split("\n");
        var group = new fabric.Group();
        var cloneObj = [];

        for(var i=0;i<=splitText.length-1;i++) {
            cloneObj[i] = fabric.util.object.clone(object);
            cloneObj[i].setText(splitText[i]);
            canvas.add(group);
            canvas.add(cloneObj[i]);
            group.addWithUpdate(cloneObj[i]);
            canvas.renderAll();
        }

        object.remove();
        canvas.setActiveGroup(group);
        group.setCoords();
        canvas.renderAll();

    }
});
</code>```

Here is the jsfiddle: https://jsfiddle.net/m74ruzwq/2/

Any help would be appreciated. Thanks in advance.

答:
Any help.

Here is the jsfiddle: http://jsfiddle.net/edvkemerovo/4ufjrrco/2/

1 button split to group. 2 button ungroup.

```<code>   var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true });

    var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
      fontSize: 20,
      top: 80,
      left: 100,
      fontFamily: "Arial"
    });

    canvas.add(text);
    canvas.renderAll();

    $('#split').click(function() {

            var object = canvas.getActiveObject();

        if(!object) return false;

            if ((object.get('type') == 'i-text') && (object.getText().indexOf( "\n" ) > 0)) {

                var splitText = object.getText().split("\n");
          var top = object.top
                var group = new fabric.Group();
                var cloneObj = [];
          canvas.add(group);
                for(var i=0;i<=splitText.length-1;i++) {
                    cloneObj[i] = fabric.util.object.clone(object);
                    cloneObj[i].setText(splitText[i]);
            cloneObj[i].setTop(top+cloneObj[i].height*i);

                //  canvas.add(cloneObj[i]);
                    group.addWithUpdate(cloneObj[i]);
                    canvas.renderAll();
                }

                object.remove();
        //  canvas.setActiveGroup(group);
                group.setCoords();
                canvas.renderAll();

            }
    });
        $('#ungroup').click(function() {
        var group = canvas.getActiveObject();
        for(var i=0;i<= group._objects.length-1;i++) {
        var cloneObj = fabric.util.object.clone(group._objects[i]);
       cloneObj.setTop(group.top+cloneObj.height*i);
        cloneObj.left = group.left;
       cloneObj.setCoords();
       canvas.add(cloneObj);
       }
            canvas.remove(group);
        canvas.renderAll();
            });
</code>```

Title: Fabric JS - Split Multiple Lines IText

Body:
I am using Fabric JS for my project, I want to split multiple lines IText like image below:

split multiple lines on IText

Here is my code:

var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true
});

var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
  fontSize: 20,
  top: 80,
  left: 100,
  fontFamily: "Arial"
});

canvas.add(text);
canvas.renderAll();

$('#split').click(function() {

    var object = canvas.getActiveObject();

    if(!object) return false;

    if ((object.get('type') == 'i-text') && (object.getText().indexOf( "\n" ) > 0)) {

        var splitText = object.getText().split("\n");
        var group = new fabric.Group();
        var cloneObj = [];

        for(var i=0;i<=splitText.length-1;i++) {
            cloneObj[i] = fabric.util.object.clone(object);
            cloneObj[i].setText(splitText[i]);
            canvas.add(group);
            canvas.add(cloneObj[i]);
            group.addWithUpdate(cloneObj[i]);
            canvas.renderAll();
        }

        object.remove();
        canvas.setActiveGroup(group);
        group.setCoords();
        canvas.renderAll();

    }
});

Here is the jsfiddle: https://jsfiddle.net/m74ruzwq/2/

Any help would be appreciated. Thanks in advance.

Body:
Any help.

Here is the jsfiddle: http://jsfiddle.net/edvkemerovo/4ufjrrco/2/

1 button split to group. 2 button ungroup.

   var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true });

    var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
      fontSize: 20,
      top: 80,
      left: 100,
      fontFamily: "Arial"
    });

    canvas.add(text);
    canvas.renderAll();

    $('#split').click(function() {

            var object = canvas.getActiveObject();

        if(!object) return false;

            if ((object.get('type') == 'i-text') && (object.getText().indexOf( "\n" ) > 0)) {

                var splitText = object.getText().split("\n");
          var top = object.top
                var group = new fabric.Group();
                var cloneObj = [];
          canvas.add(group);
                for(var i=0;i<=splitText.length-1;i++) {
                    cloneObj[i] = fabric.util.object.clone(object);
                    cloneObj[i].setText(splitText[i]);
            cloneObj[i].setTop(top+cloneObj[i].height*i);

                //  canvas.add(cloneObj[i]);
                    group.addWithUpdate(cloneObj[i]);
                    canvas.renderAll();
                }

                object.remove();
        //  canvas.setActiveGroup(group);
                group.setCoords();
                canvas.renderAll();

            }
    });
        $('#ungroup').click(function() {
        var group = canvas.getActiveObject();
        for(var i=0;i<= group._objects.length-1;i++) {
        var cloneObj = fabric.util.object.clone(group._objects[i]);
       cloneObj.setTop(group.top+cloneObj.height*i);
        cloneObj.left = group.left;
       cloneObj.setCoords();
       canvas.add(cloneObj);
       }
            canvas.remove(group);
        canvas.renderAll();
            });


问:
The best way to get a count of IEnumerable<T>
Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection?

Possible with LINQ or Lambda?

答:
The best solution -as I think is to do the following:

using System.Linq.Dynamic;

myEnumerable.AsQueryable().Count()

OwnerDisplayName: Sean Chambers

LastEditorDisplayName: Konrad Rudolph


问:
Wordpress: Some ressources won't be GZIP compressed
My .htaccess contains

```<code><IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/jquery
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml

# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
</code>```

and GTMetrix showed me that these ressources won't be compressed.

Is something missing in my .htaccess file?

Note:

-I'm not using any plugins to speed up my Wordpress page (even those installed ones are deactivated).

答:
Try this alternative, it works for me

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddType x-font/otf .otf
AddType x-font/ttf .ttf
AddType x-font/eot .eot
AddType x-font/woff .woff
AddType image/x-icon .ico
AddType image/png .png
AddType text/css .css

Body:
My .htaccess contains

<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/jquery
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml

# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>

and GTMetrix showed me that these ressources won't be compressed.

Is something missing in my .htaccess file?

Note:

-I'm not using any plugins to speed up my Wordpress page (even those installed ones are deactivated).


问:
type of object while implementing interface
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

```<code>public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}
</code>```

答:
Java hides the memory addresses of the objects created in Heap. Objects are accessed by the references. One object may have multiple references. Using = operator references are made to refer to an object and using . operator references can invoke a particular behavior of the object. References and objects are stored in different memory locations.

If there is an objext X of class C then as per the Java language specifications an X can have references whose type is C or any super class in higher hierarchy or any interface implemented by C or any of the super class in higher hierarchy or any interface extended by any of these interfaces.

```<code>class A implements IA{}
class B extends A implements IB{}
interface IC extends IA{}
interface IB extends ID{}
class E{}
class F extends B{}
</code>```

Now new B() can have references of type A,B,IA,IB,ID but can not have reference of type E,IC,F as these do not belong to the higher lever hierarchy.

Body:
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}

Body:
Java hides the memory addresses of the objects created in Heap. Objects are accessed by the references. One object may have multiple references. Using = operator references are made to refer to an object and using . operator references can invoke a particular behavior of the object. References and objects are stored in different memory locations.

If there is an objext X of class C then as per the Java language specifications an X can have references whose type is C or any super class in higher hierarchy or any interface implemented by C or any of the super class in higher hierarchy or any interface extended by any of these interfaces.

class A implements IA{}
class B extends A implements IB{}
interface IC extends IA{}
interface IB extends ID{}
class E{}
class F extends B{}

Now new B() can have references of type A,B,IA,IB,ID but can not have reference of type E,IC,F as these do not belong to the higher lever hierarchy.


问:
How can I make a combination array which contains maximum length?
I have these three arrays:

```<code>$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];
</code>```

And this is expected result:

```<code>/* Array
   (
       [0] => one
       [1] => two
       [3] => three
       [4] => four
       [5] => five
       [6] => six
       [7] => seven
   )
</code>```

Here is my solution which doesn't work as expected:

```<code>print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
   (
       [0] => one
       [1] => two
       [2] => three
       [3] => seven
   )
</code>```

How can I do that?

答:
```<code><?php
    $arr1 = ['one', 'two', 'three'];
    $arr2 = ['three', 'four'];
    $arr3 = ['two', 'five', 'six', 'seven'];
    $merge_arr = array_merge($arr1,$arr2,$arr3);
    $unique_arr = array_unique($merge_arr);
    echo '```';
        print_r($unique_arr);
    echo '```';
?>
</code>```

Output

```<code>Array
(
    [0] => one
    [1] => two
    [2] => three
    [4] => four
    [6] => five
    [7] => six
    [8] => seven
)
</code>```

Body:
I have these three arrays:

$arr1 = ['one', 'two', 'three'];
$arr2 = ['three', 'four'];
$arr3 = ['two', 'five', 'six', 'seven'];

And this is expected result:

/* Array
   (
       [0] => one
       [1] => two
       [3] => three
       [4] => four
       [5] => five
       [6] => six
       [7] => seven
   )

Here is my solution which doesn't work as expected:

print_r( array_unique( $arr1 + $arr2 + $arr3) );
/* Array
   (
       [0] => one
       [1] => two
       [2] => three
       [3] => seven
   )

How can I do that?

Body:
<?php
    $arr1 = ['one', 'two', 'three'];
    $arr2 = ['three', 'four'];
    $arr3 = ['two', 'five', 'six', 'seven'];
    $merge_arr = array_merge($arr1,$arr2,$arr3);
    $unique_arr = array_unique($merge_arr);
    echo '<pre>';
        print_r($unique_arr);
    echo '</pre>';
?>

Output

Array
(
    [0] => one
    [1] => two
    [2] => three
    [4] => four
    [6] => five
    [7] => six
    [8] => seven
)


问:
Why can't I return only in a nested body of my Method and not be forced to return in the scope of the main method?
Why is it that if you declare a return type on a method, that you have to specify a return in the scope of that method? Meaning, if I have a If/Switch in my method I can't specify the return there "ALONE" and not in the main method body? Is the only way around this is to assign the value returned by the nested procedure to a variable and return the variable in the main body of the method?

Example:

```<code>public Int GetNum()
{
   var a = 1;
   switch(a)
   {
      case 1:
        return 1 + 5;
      default:
        return a;
   }
 return a;   //Why must I specify this return if it is going to hit my switch statement
             //and return some int.
}
</code>```

答:
If you have a default, that's not necessary.

If you don't have a default, you need an outer return in case none of the cases execute.

Body:
Why is it that if you declare a return type on a method, that you have to specify a return in the scope of that method? Meaning, if I have a If/Switch in my method I can't specify the return there "ALONE" and not in the main method body? Is the only way around this is to assign the value returned by the nested procedure to a variable and return the variable in the main body of the method?

Example:

public Int GetNum()
{
   var a = 1;
   switch(a)
   {
      case 1:
        return 1 + 5;
      default:
        return a;
   }
 return a;   //Why must I specify this return if it is going to hit my switch statement
             //and return some int.
}


问:
Zero margin between labels in bootstrap modal
I've using bootstrap labels in web page but in normal page its looking good but in modal there is no margin b/w two labels:

$('.task').dblclick(function (e) {
$('#Modal_Task_View').modal({keyboard: true, show: true});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Common styles for all types */
.task {
  padding: 10px 15px;
  margin: 10px 0;
  border: 1px solid #eee;
  border-left-width: 10px;
  border-radius: 3px;
}
.task h4 {
  margin-top: 0;
  margin-bottom: 5px;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Title 2
                                (First Category)

                        Assigned to :

                Gobind Samrow(admindddd)

                Chris Walker(CW)

                Due Date: 26-Jun-2017

                Days Left: 0

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Task 2 Wishlist

                DueNormal
                Due Date : 08-Jul-2017

                         Category : Second Category

                        Description :
                        Description Description Description

                        Assigned To :
                        StandardAsh Wilde(ACW)admin admin(admin)

Linked TasksTitle 4Title 3

Documents

```

答:
This because of no line change or spacebar in modal have a look these two example

No Space/Line Change Example

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Gobind Samrow(admindddd)Chris Walker(CW)```
</div>
</div>
</p>

<p><strong>Line Change Example</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<span>
    <label class="label label-info" data-type="1" data-id="28">Gobind Samrow(admindddd)</label>
    <label class="label label-info" data-type="1" data-id="22">Chris Walker(CW)</label>
</span></code>```

Body:
I've using bootstrap labels in web page but in normal page its looking good but in modal there is no margin b/w two labels:

$('.task').dblclick(function (e) {
$('#Modal_Task_View').modal({keyboard: true, show: true});
});

/* Common styles for all types */
.task {
  padding: 10px 15px;
  margin: 10px 0;
  border: 1px solid #eee;
  border-left-width: 10px;
  border-radius: 3px;
}
.task h4 {
  margin-top: 0;
  margin-bottom: 5px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Title 2
                                (First Category)

                        Assigned to :

                Gobind Samrow(admindddd)

                Chris Walker(CW)

                Due Date: 26-Jun-2017

                Days Left: 0

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Task 2 Wishlist

                DueNormal
                Due Date : 08-Jul-2017

                         Category : Second Category

                        Description :
                        Description Description Description

                        Assigned To :
                        StandardAsh Wilde(ACW)admin admin(admin)

Linked TasksTitle 4Title 3

Documents

Body:
This because of no line change or spacebar in modal have a look these two example

No Space/Line Change Example

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<span><label class="label label-info" data-type="1" data-id="28">Gobind Samrow(admindddd)</label><label class="label label-info" data-type="1" data-id="22">Chris Walker(CW)</label></span>

Line Change Example

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<span>
    <label class="label label-info" data-type="1" data-id="28">Gobind Samrow(admindddd)</label>
    <label class="label label-info" data-type="1" data-id="22">Chris Walker(CW)</label>
</span>


问:
Parsing HTML into NSAttributedText - how to set font?
I am trying to get a snippet of text that is formatted in html to display nicely on an iPhone in a UITableViewCell.

So far I have this:

```<code>NSError* error;
NSString* source = @"<strong>Nice</strong> try, Phil";
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                     NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                              documentAttributes:nil error:&error];
</code>```

This kind of works. I get some text that has 'Nice' in bold! But... it also sets the font to be Times Roman! This is not the font face I want.
I am thinking I need to set something in the documentAttributes, but, I can't find any examples anywhere.

答:
Swift 4+ update of UILabel extension

```<code>extension UILabel {
    func setHTMLFromString(text: String) {
        let modifiedFont = NSString(format:"<span style=\"font-family: \(self.font!.fontName); font-size: \(self.font!.pointSize)\">%@</span>" as NSString, text)

        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: String.Encoding.unicode.rawValue, allowLossyConversion: true)!,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}
</code>```

iOS 9+

```<code>extension UILabel {
    func setHTMLFromString(htmlText: String) {
        let modifiedFont = NSString(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: \(self.font!.pointSize)\">%@</span>" as NSString, htmlText) as String

        //process collection values
        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}
</code>```

Body:
I am trying to get a snippet of text that is formatted in html to display nicely on an iPhone in a UITableViewCell.

So far I have this:

NSError* error;
NSString* source = @"Nice try, Phil";
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                     NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                              documentAttributes:nil error:&error];

This kind of works. I get some text that has 'Nice' in bold! But... it also sets the font to be Times Roman! This is not the font face I want.
I am thinking I need to set something in the documentAttributes, but, I can't find any examples anywhere.

Body:
Swift 4+ update of UILabel extension

extension UILabel {
    func setHTMLFromString(text: String) {
        let modifiedFont = NSString(format:"<span style=\"font-family: \(self.font!.fontName); font-size: \(self.font!.pointSize)\">%@</span>" as NSString, text)

        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: String.Encoding.unicode.rawValue, allowLossyConversion: true)!,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}

iOS 9+

extension UILabel {
    func setHTMLFromString(htmlText: String) {
        let modifiedFont = NSString(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: \(self.font!.pointSize)\">%@</span>" as NSString, htmlText) as String

        //process collection values
        let attrStr = try! NSAttributedString(
            data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
            options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue],
            documentAttributes: nil)

        self.attributedText = attrStr
    }
}


问:
Throw exception from within a future
I need to throw an exception in my program, but the exception happens within a future, so it is thrown in a different thread. How to make this example work?

```<code>object TestFutures extends App {

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map {
    seq => seq.map {  i =>
        println("i="+i)
        if (i == 1)
              throw new Exception("This is an exception")

    }
  }

  Thread.sleep(5000)
}
</code>```

This is the program output, but I need it to throw the exception:

```<code>i=0
i=1
</code>```

答:
How to make this example work?

You can use for to make it work as

```<code>val f0 = Future { 0 }
val f1 = Future { 1 }
val fx = Seq(f0,f1)

for(seq <- fx){
  for(i <- seq) {
    println("i="+i)
    if (i == 1) {
      throw new Exception("This is an exception")
    }
  }
}
Thread.sleep(5000)
</code>```

Title: Throw exception from within a future

Body:
I need to throw an exception in my program, but the exception happens within a future, so it is thrown in a different thread. How to make this example work?

object TestFutures extends App {

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map {
    seq => seq.map {  i =>
        println("i="+i)
        if (i == 1)
              throw new Exception("This is an exception")

    }
  }

  Thread.sleep(5000)
}

This is the program output, but I need it to throw the exception:

i=0
i=1

Body:
How to make this example work?

You can use for to make it work as

val f0 = Future { 0 }
val f1 = Future { 1 }
val fx = Seq(f0,f1)

for(seq <- fx){
  for(i <- seq) {
    println("i="+i)
    if (i == 1) {
      throw new Exception("This is an exception")
    }
  }
}
Thread.sleep(5000)


问:
In classification, how do you validate the model in case of imbalanced data set?
I’m kind of a beginner in machine learning and trying to solve a classification problem. I’m working on a very unbalanced (sequential) data set (only 2% positives out of 20k records) and I'm using LSTM/GRUs to model in python using tensorflow.

This is what I do:
Load the data.
Split the data set into 3 data sets :
A for Training (70%)
B for Validating (15%)
C for Testing (15%);
For each data set (A, B, C), do an over-sampling on positive class in order to increase the percentage of positives from 2% to 30%. This gives me 3 new datasets which are more balanced: A’, B’, C’

Then I train my model with the data set A’ using GRU.

My Objective: Get highest F score on my test set C (Are there any better metrics? From what I've seen, F score depends on data distribution i.e. how skewed the data is. If my actual negatives to positives ratio increases then precision  decreases (due to increase in False negatives) though recall more or less remains the same; and so my overall F score goes down)

My questions are:

Can I use cross entropy as my cost function while training ? (I am not altering the cost function to be more sensitive to false positives since I have already over sampled my positives )

Which data set do I have to use for validation ? B or B’ ? and what metric should I use to plot the validation learning curve to know the point where my model is over fitting? (Currently I am using accuracy on both A’ (train) and B’ (validation) to see if there is any over fitting. But it seems accuracy on B’ and f score on B doesn't correlate much. Because ultimately I want good f score on C which means I need the model which gives good f score on B)

Thanks in advance for your time!
Regards.

答:
(The following is more a long comment than an complete answer - I need to think about this. I hope I'll find the time to update it this evening / tomorrow)

Which set should be the test set?

We are using a test set to estimate the real score (error / accuracy / F1-score / recall / precision / ...), hence the score we would get if we tested the model on all possible samples (that would be an extraordinary huge amount of samples; e.g. if you received 32x32 px grayscale images it would be 256^1024 \approx  10^2466).

Hence you take C for testing, not C'.

Which set should be the validation set?

We are using a validation set to not overfit on the test set. Usually for early stopping. If the score is the optimization objective, it should be B (not B'). If the score is something different, you might want to think about how both go hand in hand (e.g. when the optimization objective gets better, does the score also become better?). If they do not go hand in hand in many cases, you should adjust the optimization objective.

You have the F1 score and are thinking about using cross entropy as the optimization objective. Cross entropy ignores the class, hence you balance the classes.

edit: Thinking about it, I would take F1 score on B as a stopping criterion. Other choices might be valid, too, but this seems to make most sense as the F1 score should be maximized

Which set should be used the training set?

If you take A you will have the problem that your network learns to always predict the more common class. Hence you have to take A'.


问:
Visual Studio - Xamarin - Show "Document Outline"
I'm starting out with Xamarin and am finding Visual Studio to have many pitfalls :(

I clicked the "X" button on the left/right hand side tabs and they've vanished ... now I can't find how to recover them!

How can I show the "Solution", "Document Outline", "Unit Tests", "Toolbox" & "Properties" tabs in the following situation (as I'm about to reinstall the software :/)

答: Please, look at the image below.

Body: Please, look at the image below.


问:
Delete only first appearance of element into list?
How to delete only first appearance of element into list (elisp) ?</p>

答:
You can use this elisp (which requires cl):

```<code>(defun remove-first (elt seq)
  (let ((remove-first t))
    (remove-if (lambda (e) (when (and remove-first (equal elt e))
                             (setq remove-first nil)
                             t))
               seq)))
</code>```

Note: this makes a copy of the original list.  For one using side-effects, try this:

```<code>(defun remove-first* (elt seq)
  (if (equal elt (car seq))
      (cdr seq)
    (while (cdr seq)
      (if (equal elt (cadr seq))
          (progn (setcdr seq (cddr seq))
                 (setq seq nil))
        (setq seq (cdr seq))))
    seq))
</code>```

Note: when the first element is the one removed, just the cdr is returned, so as always with this type of operation, invoke it like so:

```<code>(setq mylist (remove-first* 3 mylist))
</code>```

Body:
You can use this elisp (which requires cl):

(defun remove-first (elt seq)
  (let ((remove-first t))
    (remove-if (lambda (e) (when (and remove-first (equal elt e))
                             (setq remove-first nil)
                             t))
               seq)))

Note: this makes a copy of the original list.  For one using side-effects, try this:

(defun remove-first* (elt seq)
  (if (equal elt (car seq))
      (cdr seq)
    (while (cdr seq)
      (if (equal elt (cadr seq))
          (progn (setcdr seq (cddr seq))
                 (setq seq nil))
        (setq seq (cdr seq))))
    seq))

Note: when the first element is the one removed, just the cdr is returned, so as always with this type of operation, invoke it like so:

(setq mylist (remove-first* 3 mylist))


问:
Difference between now and birthdate in years, months, days, mintues
```<code>import datetime
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
#This returns a timedelta object -> datetime.timedelta(7629, 36148, 156646)
</code>```

Now i want to convert precisely the timedelta object in years, months, days and seconds..
I know i can do like difference.days // 365 to get years and so on..
Is there any other way or methods to convert this timedelta objects in
Year, months, days and minutes precisely and easily?

答:
You could use this function:

```<code>import datetime
import calendar

def difference(start, end):
    years = end.year - start.year
    months = end.month - start.month
    days = end.day - start.day
    hours = end.hour - start.hour
    minutes = end.minute - start.minute
    seconds = end.second - start.second
    if seconds < 0:
        minutes -= 1
        seconds += 60
    if minutes < 0:
        hours -= 1
        minutes += 60
    if hours < 0:
        days -= 1
        hours += 24
    if days < 0:
        months -= 1
        days += calendar.monthrange(start.year, start.month)[1]
    if months < 0:
        years -= 1
        months += 12
    return {
        'years': years,
        'months': months,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    }

birthday = datetime.datetime(1996,8,30)
diff = difference(birthday, datetime.datetime.now())
print(diff)
</code>```

This counts the years (including leap years) as they occur between the two dates.

The difference in days is either the net difference of the day numbers, or -- if the current date has a smaller day number than the birth date -- then the number of days remaining in the month of birth are added to the current day number. This can be a bit arbitrary. Suppose tomorrow is my birthday (and the birthday is not on the first of the month), then the output will have 11 for the months as expected, but either 27, 28, 29 or 30 for the days component, depending how many days the month of birth has...

Body:
import datetime
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
#This returns a timedelta object -> datetime.timedelta(7629, 36148, 156646)

Now i want to convert precisely the timedelta object in years, months, days and seconds..
I know i can do like difference.days // 365 to get years and so on..
Is there any other way or methods to convert this timedelta objects in
Year, months, days and minutes precisely and easily?

Body:
You could use this function:

import datetime
import calendar

def difference(start, end):
    years = end.year - start.year
    months = end.month - start.month
    days = end.day - start.day
    hours = end.hour - start.hour
    minutes = end.minute - start.minute
    seconds = end.second - start.second
    if seconds < 0:
        minutes -= 1
        seconds += 60
    if minutes < 0:
        hours -= 1
        minutes += 60
    if hours < 0:
        days -= 1
        hours += 24
    if days < 0:
        months -= 1
        days += calendar.monthrange(start.year, start.month)[1]
    if months < 0:
        years -= 1
        months += 12
    return {
        'years': years,
        'months': months,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    }

birthday = datetime.datetime(1996,8,30)
diff = difference(birthday, datetime.datetime.now())
print(diff)

This counts the years (including leap years) as they occur between the two dates.

The difference in days is either the net difference of the day numbers, or -- if the current date has a smaller day number than the birth date -- then the number of days remaining in the month of birth are added to the current day number. This can be a bit arbitrary. Suppose tomorrow is my birthday (and the birthday is not on the first of the month), then the output will have 11 for the months as expected, but either 27, 28, 29 or 30 for the days component, depending how many days the month of birth has...


问:
Create-react-app doesn't allow import component.js from node_modules?
I received error when try to import { PrimaryButton } from 'my-npm-modules/src/button' ( which is a flowtype src jsx file with extension .js)?

Is it because the create-react-app have config to NOT do flowtype processing for files in node_modules?

```<code>Module parse failed: /Users/me/live-demo/node_modules/my-npm-modules/src/button.js Unexpected token (2:35)
You may need an appropriate loader to handle this file type.
| //@flow
| import React from 'react';
| export function PrimaryButton(props: {
|     text: string;
|     onClick: ()=>void
</code>```

When I put the button.js inside the live-demo project, it works fine.

答:
It seems it did exclude the node_modules folder for performance reason.

So I endup compile the flow-typed jsx --> normal js files, and provided js.flow at the same output folder for sake of consumer flowtype support.

Body:
I received error when try to import { PrimaryButton } from 'my-npm-modules/src/button' ( which is a flowtype src jsx file with extension .js)?

Is it because the create-react-app have config to NOT do flowtype processing for files in node_modules?

Module parse failed: /Users/me/live-demo/node_modules/my-npm-modules/src/button.js Unexpected token (2:35)
You may need an appropriate loader to handle this file type.
| //@flow
| import React from 'react';
| export function PrimaryButton(props: {
|     text: string;
|     onClick: ()=>void

When I put the button.js inside the live-demo project, it works fine.


问:
Limit length of several text fields
I have several text fields in one view controller and I'm using the following function to limit the number of characters:

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    return textView.text.characters.count + (text.characters.count - range.length) <= 300
}
</code>```

How can I change the number of maximum number of characters for a different text field? I need a lower limit for another text field.

答:
For TextView you need to use following TextView delegate method

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
     if textView == yourTextViewName
     {
         let str = (NSString(string: textView.text!)).replacingCharacters(in: range, with: text)
         if str.characters.count <= 300 {
             return true
         }
         textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
         return false
     }
     return true
}
</code>```

For TextField you have to use following delegate method

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    if textField == yourTextFieldName {
        let str = (NSString(string: textField.text!)).replacingCharacters(in: range, with: string)
        if str.characters.count <= 300 {
            return true
        }
        textField.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
        return false
    }
    return true
}
</code>```

I hope this help you.

Title: Limit length of several text fields

Body:
I have several text fields in one view controller and I'm using the following function to limit the number of characters:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    return textView.text.characters.count + (text.characters.count - range.length) <= 300
}

How can I change the number of maximum number of characters for a different text field? I need a lower limit for another text field.

Body:
For TextView you need to use following TextView delegate method

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
     if textView == yourTextViewName
     {
         let str = (NSString(string: textView.text!)).replacingCharacters(in: range, with: text)
         if str.characters.count <= 300 {
             return true
         }
         textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
         return false
     }
     return true
}

For TextField you have to use following delegate method

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    if textField == yourTextFieldName {
        let str = (NSString(string: textField.text!)).replacingCharacters(in: range, with: string)
        if str.characters.count <= 300 {
            return true
        }
        textField.text = str.substring(to: str.index(str.startIndex, offsetBy: 300))
        return false
    }
    return true
}

I hope this help you.


问:
Default values and initialization in Java
Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.

```<code>public class Main {
    public static void main(String[] args) {
        int a;
        System.out.println(a);
    }
}
</code>```

The line System.out.println(a); will be an error pointing at the variable a that says variable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.

```<code>public class Main {
    static int a;
    public static void main(String[] args) {
        System.out.println(a);
    }
}
</code>```

What could possibly go wrong with the first code? Do class variables behave different from local variables?

答:
Local variables do not get default values. Their initial values are undefined without assigning values by some means. Before you can use local variables they must be initialized.

There is a big difference when you declare a variable at class level (as a member, i.e., as a field) and at the method level.

If you declare a field at the class level they get default values according to their type. If you declare a variable at the method level or as a block (means any code inside {}) do not get any values and remain undefined until somehow they get some starting values, i.e., some values assigned to them.

Body:
Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.

public class Main {
    public static void main(String[] args) {
        int a;
        System.out.println(a);
    }
}

The line System.out.println(a); will be an error pointing at the variable a that says variable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.

public class Main {
    static int a;
    public static void main(String[] args) {
        System.out.println(a);
    }
}

What could possibly go wrong with the first code? Do class variables behave different from local variables?


问:
Add Custom User-Meta to the Users Admin page in WordPress
I have created a special form within my site that allows my users to enter a key.  I am using add_user_meta() to add the meta data into the database.  I want to be able to see this key when I click on users in the admin center.

How would I go about adding to this column?

Below is the meta data info im using

```<code>add_user_meta($userId,'code','12345');
</code>```

We just want to be able to add it to the view on users.php in the table displaying username email and role.

I have used code like this to display the user id but I can not figure out how to display their meta.

```<code>add_filter('manage_users_columns', 'pippin_add_user_id_column');
function pippin_add_user_id_column($columns) {
    $columns['user_id'] = 'User ID';
    return $columns;
}

add_action('manage_users_custom_column',  'pippin_show_user_id_column_content', 10, 3);
function pippin_show_user_id_column_content($value, $column_name, $user_id) {
    $user = get_userdata( $user_id );
    if ( 'user_id' == $column_name )
        return $user_id;
    return $value;
}
</code>```

答:
To add custom user_meta fields to users.php you need to do the following:</p>

```<code>function yoursite_manage_users_columns( $columns ) {

    // $columns is a key/value array of column slugs and names
    $columns[ 'custom_field' ] = 'Subscription';

    return $columns;
}

add_filter( 'manage_users_columns', 'yoursite_manage_users_columns', 10, 1 );

function yoursite_manage_users_custom_column( $output, $column_key, $user_id ) {

    switch ( $column_key ) {
        case 'custom_field':
            $value = get_user_meta( $user_id, 'custom_field', true );

            return $value;
            break;
        default: break;
    }

    // if no column slug found, return default output value
    return $output;
}

add_filter( 'manage_users_custom_column', 'yoursite_manage_users_custom_column', 10, 3 );
</code>```

Body:
I have created a special form within my site that allows my users to enter a key.  I am using add_user_meta() to add the meta data into the database.  I want to be able to see this key when I click on users in the admin center.

How would I go about adding to this column?

Below is the meta data info im using

add_user_meta($userId,'code','12345');

We just want to be able to add it to the view on users.php in the table displaying username email and role.

I have used code like this to display the user id but I can not figure out how to display their meta.

add_filter('manage_users_columns', 'pippin_add_user_id_column');
function pippin_add_user_id_column($columns) {
    $columns['user_id'] = 'User ID';
    return $columns;
}

add_action('manage_users_custom_column',  'pippin_show_user_id_column_content', 10, 3);
function pippin_show_user_id_column_content($value, $column_name, $user_id) {
    $user = get_userdata( $user_id );
    if ( 'user_id' == $column_name )
        return $user_id;
    return $value;
}

Body:
To add custom user_meta fields to users.php you need to do the following:

function yoursite_manage_users_columns( $columns ) {

    // $columns is a key/value array of column slugs and names
    $columns[ 'custom_field' ] = 'Subscription';

    return $columns;
}

add_filter( 'manage_users_columns', 'yoursite_manage_users_columns', 10, 1 );

function yoursite_manage_users_custom_column( $output, $column_key, $user_id ) {

    switch ( $column_key ) {
        case 'custom_field':
            $value = get_user_meta( $user_id, 'custom_field', true );

            return $value;
            break;
        default: break;
    }

    // if no column slug found, return default output value
    return $output;
}

add_filter( 'manage_users_custom_column', 'yoursite_manage_users_custom_column', 10, 3 );


问:
Difference between classes in Java vs JavaScript?
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

```<code>const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();
</code>```

The MyClass it's calling has this code:

```<code>class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;
</code>```

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?

答:
To indicate that you're referring to a property of the object named myString instead of a variable with the same name, your console.log() invocation should read:

```<code>console.log(this.myString);
</code>```

Body:
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();

The MyClass it's calling has this code:

class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?

Body:
To indicate that you're referring to a property of the object named myString instead of a variable with the same name, your console.log() invocation should read:

console.log(this.myString);


问:
Name clash from implementing interface
I have spent a few hours reading Java documentation/Stackoverflow answers on generics and type erasure but I still don't understand the topic fully.
The problem is implementing the following simple interface:

```<code>public interface Stack {
void push(Object element); }
</code>```

I have implemented this in a simple generic class:

```<code>public class NodeStack<T> implements Stack {
private Node<T> top;
private int size;

public void push(T value) {
    if(this.size == 0) {
        this.top = new Node<>(value, null);
    } else {
        this.top = new Node<>(value, this.top);
    }
    this.size++;}
}
</code>```

When I attempt to compile this I get the compiler error messages:

```<code>NodeStack.java:10: error: NodeStack is not abstract and does not override abstract method push(Object) in Stack
public class NodeStack<T> implements Stack {
   ^
NodeStack.java:63: error: name clash: push(T) in NodeStack and push(Object) in Stack have the same erasure, yet neither overrides the other

    public void push(T value) {
                ^
where T is a type-variable:
    T extends Object declared in class NodeStack
2 errors
</code>```

I think this problem occurs because of type erasure - the push method in the class and the push method in the interface have the same signature after type erasure. What I don't understand is why this would be a problem. The push method implementation should have the same signature as the interface method, right? What am I missing here? Any help is greatly appreciated.

答:
In your interface: void push(Object element);, parameter of type Object but when you implementing the interface you have changed the type of the parameter. It don't matter subtype of Object. Because of you didnot implement the abstract method in the NodeStack, compiler says:

```<code>NodeStack is not abstract and does not override abstract method push(Object) in Stack
</code>```

When overriding a method you should always remember:

name of the method and parameter list cannot be changed and you can change access modifier.

As a solution, make the interface as generic and change type of the parameter Object to T. Then you can implement that generic interface.

Title: Name clash from implementing interface

Body:
I have spent a few hours reading Java documentation/Stackoverflow answers on generics and type erasure but I still don't understand the topic fully.
The problem is implementing the following simple interface:

public interface Stack {
void push(Object element); }

I have implemented this in a simple generic class:

public class NodeStack<T> implements Stack {
private Node<T> top;
private int size;

public void push(T value) {
    if(this.size == 0) {
        this.top = new Node<>(value, null);
    } else {
        this.top = new Node<>(value, this.top);
    }
    this.size++;}
}

When I attempt to compile this I get the compiler error messages:

NodeStack.java:10: error: NodeStack is not abstract and does not override abstract method push(Object) in Stack
public class NodeStack<T> implements Stack {
   ^
NodeStack.java:63: error: name clash: push(T) in NodeStack and push(Object) in Stack have the same erasure, yet neither overrides the other

    public void push(T value) {
                ^
where T is a type-variable:
    T extends Object declared in class NodeStack
2 errors

I think this problem occurs because of type erasure - the push method in the class and the push method in the interface have the same signature after type erasure. What I don't understand is why this would be a problem. The push method implementation should have the same signature as the interface method, right? What am I missing here? Any help is greatly appreciated.

Body:
In your interface: void push(Object element);, parameter of type Object but when you implementing the interface you have changed the type of the parameter. It don't matter subtype of Object. Because of you didnot implement the abstract method in the NodeStack, compiler says:

NodeStack is not abstract and does not override abstract method push(Object) in Stack

When overriding a method you should always remember:

name of the method and parameter list cannot be changed and you can change access modifier.

As a solution, make the interface as generic and change type of the parameter Object to T. Then you can implement that generic interface.


问:
How to check if the button is clickable using selenium webdriver
I am trying to find if the button element is clickable which I am not able to validate successfully using selenium webdriver.

Here is my code to validate if the element is clickable

```<code>    boolean installAFile;

    String classValues = driver.findElement(by.XPATH("//button[contains(., 'Install a new file')]")).getAttribute("class");
    installAFIle = classValues.contains("iconbutton-button--clickable");

    return installAFIle;
</code>```

Here is the HTML

```<code><div>
<!-- react-text: 406 -->
test message 1
<!-- /react-text -->
<div class="iconbutton">
<button class="iconbutton-button iconbutton-button--clickable" type="button"
tabindex="0">
<div class="iconbutton-button-label">Install a new file</div>
</button>
</div>
<!-- react-text: 410 -->
under File > Install.
<!-- /react-text -->
</div>
</code>```

I keep on getting following validation message:
no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(., 'Install a new file')]"}

答:
Just write the below method and call it whenever you want to check whether element is clickable or not. Pass the required arguments also.</p>

```<code>public static boolean isClickable(WebElement el, WebDriver driver)
    {
        try{
            WebDriverWait wait = new WebDriverWait(driver, 6);
            wait.until(ExpectedConditions.elementToBeClickable(el));
            return true;
        }
        catch (Exception e){
            return false;
        }
    }
</code>```

Body:
I am trying to find if the button element is clickable which I am not able to validate successfully using selenium webdriver.

Here is my code to validate if the element is clickable

    boolean installAFile;

    String classValues = driver.findElement(by.XPATH("//button[contains(., 'Install a new file')]")).getAttribute("class");
    installAFIle = classValues.contains("iconbutton-button--clickable");

    return installAFIle;

Here is the HTML

test message 1

<button class="iconbutton-button iconbutton-button--clickable" type="button"
tabindex="0">

Install a new file

</button>

under File > Install.

I keep on getting following validation message:
no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(., 'Install a new file')]"}

Body:
Just write the below method and call it whenever you want to check whether element is clickable or not. Pass the required arguments also.

public static boolean isClickable(WebElement el, WebDriver driver)
    {
        try{
            WebDriverWait wait = new WebDriverWait(driver, 6);
            wait.until(ExpectedConditions.elementToBeClickable(el));
            return true;
        }
        catch (Exception e){
            return false;
        }
    }


问:
sharepoint breadcrum trail editing on the fly
I have been searching for hours now and have found some code that claims to be able to do what i want however...it doesn't.

I am currently trying to remove Pages and .aspx off the end of my page name in the breadcrumb trail in sharepoint. Currently it look like....
mysite > myarea > pages >mypage.aspx

I have tried changing the SiteMapProvider and this takes away the pages link as well as the current page. It then looked like..
mysite > myarea.

I would like to have
mysite > myarea >mypage
I have tried using this snippet of code...I do not claim to own or to have developed this code.

```<code>var breadCrumbs = document.getElementById('ctl00_PlaceHolderTitleBreadcrumb_ContentMap')
if (breadCrumbs != null) {
    if (breadCrumbs.childNodes.length >= 3) {
        if (breadCrumbs.childNodes[2].innerHTML.indexOf('Pages') > 0) {
            breadCrumbs.childNodes[1].innerHTML = "";
            breadCrumbs.childNodes[2].innerHTML = "";
        }
    }
}
</code>```

I put some document.writes in to see where the code was getting to and the breadCrums variable seems to be null therefore the code never gets to the juicy part :P

Any ideas hints tips would be hugely appreciated

Truez

答:
I have run your code on a SharePoint site and was able to get the breadCrumbs element just fine.  Have you verified that that is the correct ID of your breadcrumbs object.  The ID you use is the default, but you should check.  Just view source on the page and do a quick Ctrl-F and search for "Breadcrumb".

Too see if it is just a matter of placement, do this: On a target SharePoint page using IE, open the Web Developer tool (Tools > Developer Tools).  Switch to the Script tab and press the Multi Line Mode button at the bottom of the script pane.  Paste this code:

```<code>var breadCrumbs = document.getElementById('ctl00_PlaceHolderTitleBreadcrumb_ContentMap')
if (breadCrumbs != null) {
    if (breadCrumbs.childNodes.length >= 3) {
        if (breadCrumbs.childNodes[2].innerHTML.indexOf('Pages') > 0) {
            breadCrumbs.childNodes[1].innerHTML = "";
            breadCrumbs.childNodes[2].innerHTML = "";
        } else {
            alert('Pages node NOT found!');
        }
    } else {
        alert('breadCrumbs only has ' + breadCrumbs.childNodes.length + ' children!');
    }
} else {
    alert('breadCrumbs NOT found!');
}
</code>```

Then press the Run Script button.  This code is just yours with some alerts added to help you see if/where it fails.  If you get no alerts and the breadcrumbs element changes as you expect then yes it is placement.  Otherwise, it depends on which alert you get.  Let me know the results and I can help you correct the issue.

Body:
I have been searching for hours now and have found some code that claims to be able to do what i want however...it doesn't.

I am currently trying to remove Pages and .aspx off the end of my page name in the breadcrumb trail in sharepoint. Currently it look like....
mysite > myarea > pages >mypage.aspx

I have tried changing the SiteMapProvider and this takes away the pages link as well as the current page. It then looked like..
mysite > myarea.

I would like to have
mysite > myarea >mypage
I have tried using this snippet of code...I do not claim to own or to have developed this code.

var breadCrumbs = document.getElementById('ctl00_PlaceHolderTitleBreadcrumb_ContentMap')
if (breadCrumbs != null) {
    if (breadCrumbs.childNodes.length >= 3) {
        if (breadCrumbs.childNodes[2].innerHTML.indexOf('Pages') > 0) {
            breadCrumbs.childNodes[1].innerHTML = "";
            breadCrumbs.childNodes[2].innerHTML = "";
        }
    }
}

I put some document.writes in to see where the code was getting to and the breadCrums variable seems to be null therefore the code never gets to the juicy part :P

Any ideas hints tips would be hugely appreciated

Truez

Body:
I have run your code on a SharePoint site and was able to get the breadCrumbs element just fine.  Have you verified that that is the correct ID of your breadcrumbs object.  The ID you use is the default, but you should check.  Just view source on the page and do a quick Ctrl-F and search for "Breadcrumb".

Too see if it is just a matter of placement, do this: On a target SharePoint page using IE, open the Web Developer tool (Tools > Developer Tools).  Switch to the Script tab and press the Multi Line Mode button at the bottom of the script pane.  Paste this code:

var breadCrumbs = document.getElementById('ctl00_PlaceHolderTitleBreadcrumb_ContentMap')
if (breadCrumbs != null) {
    if (breadCrumbs.childNodes.length >= 3) {
        if (breadCrumbs.childNodes[2].innerHTML.indexOf('Pages') > 0) {
            breadCrumbs.childNodes[1].innerHTML = "";
            breadCrumbs.childNodes[2].innerHTML = "";
        } else {
            alert('Pages node NOT found!');
        }
    } else {
        alert('breadCrumbs only has ' + breadCrumbs.childNodes.length + ' children!');
    }
} else {
    alert('breadCrumbs NOT found!');
}

Then press the Run Script button.  This code is just yours with some alerts added to help you see if/where it fails.  If you get no alerts and the breadcrumbs element changes as you expect then yes it is placement.  Otherwise, it depends on which alert you get.  Let me know the results and I can help you correct the issue.


问:
proc rank vs proc means to remove the top and bottom 0.1%
I would like to remove some outlier in the top and bottom 0.1%. PROC MEANS has the p99 option which only helps to remove the top 1%, not 0.1%. Is there another way to do so? I thought of PROC RANK but not sure if it would give the same result.
my code is:

```<code>    proc means data=input noprint; by date; output out=trunc(drop=_FREQ_ _TYPE_) p99(var1)=p99_var1 p99(var2)=p99_var2; run;
data input; merge input trunc; by date;
    if var1 < p99_var1 and var2<p99_var2;run;

    versus

    proc rank data=input out=input percent;
        by date;
         var var1 var2;
         ranks percentile1 percentile2;
    run;
data input; set input;
where 0.001<percentile1<0.999 and 0.001<percentile2<0.999;run
</code>```

I am aware that in the first method I use 99% (because I don't know how to do 99.9% with this method) but I use 99.9% in the second method. If I use 99% for the second method, which one would be a better way to do? and would the 2 yield the same result?

答:
Using the ties treatment and fractions options of proc rank you should have the flexibility you need for this problem.

Check the SAS documentation here.

Body:
I would like to remove some outlier in the top and bottom 0.1%. PROC MEANS has the p99 option which only helps to remove the top 1%, not 0.1%. Is there another way to do so? I thought of PROC RANK but not sure if it would give the same result.
my code is:

    proc means data=input noprint; by date; output out=trunc(drop=_FREQ_ _TYPE_) p99(var1)=p99_var1 p99(var2)=p99_var2; run;
data input; merge input trunc; by date;
    if var1 < p99_var1 and var2<p99_var2;run;

    versus

    proc rank data=input out=input percent;
        by date;
         var var1 var2;
         ranks percentile1 percentile2;
    run;
data input; set input;
where 0.001<percentile1<0.999 and 0.001<percentile2<0.999;run

I am aware that in the first method I use 99% (because I don't know how to do 99.9% with this method) but I use 99.9% in the second method. If I use 99% for the second method, which one would be a better way to do? and would the 2 yield the same result?


问:
Optional Group python Rgx
```<code>import re
string = 'Alabama[edit]'
a = re.search(r'(\w+)(?:\(([\w+\s*]+)\))(\[.*\])',string).group(2)
</code>```

I have made the () in the optional group, but the result still returned None.
what I want to achieve is that there are two different types of string:

1.Alabama[edit]
2.Alabama (some text)[edit]

I want to abstract either none , if there is no parenthesis or the string in the
parenthesis.

And also I am not sure why this doesn't work for the optional Group I mean if there is on parenthesis , this expression should be ignored and capture the rest group which are captured right?

```<code>(?:\(([\w+\s*]+)\))
</code>```

thanks!
Erik

答:
This seems to work:

```<code>a = re.search('(\w+)(\([\w+\s*]+\))?(\[.*\])',string).groups()
print(a) #('Alabama', None, '[edit]')
</code>```

In your original expression you didn't use the optional indicator. To make the group optional you put the ? at the end, after the closing ). The ?: notation you used means the following group will be ignored in the result, but will be always taken into consideration for matching. It basically says: "Match this group, but i don't want to know anything about it in the result"

I think what you wanted after all is this:

a = re.search('(\w+)(?:\([\w+\s*]+\))?(\[.*\])',string).groups()

so:

```<code>import re
s1 = 'Alabama[edit]'
s2 = 'Alabama(test)[edit]'
print(re.search(r'(\w+)(?:\(([\w+\s*]+)\))?(\[.*\])',s1).groups())
#('Alabama', None, '[edit]')
print(re.search(r'(\w+)(?:\(([\w+\s*]+)\))?(\[.*\])',s2).groups())
#('Alabama', 'test', '[edit]')
</code>```

Title: Optional Group python Rgx

Body:
import re
string = 'Alabama[edit]'
a = re.search(r'(\w+)(?:\(([\w+\s*]+)\))(\[.*\])',string).group(2)

I have made the () in the optional group, but the result still returned None.
what I want to achieve is that there are two different types of string:

1.Alabama[edit]
2.Alabama (some text)[edit]

I want to abstract either none , if there is no parenthesis or the string in the
parenthesis.

And also I am not sure why this doesn't work for the optional Group I mean if there is on parenthesis , this expression should be ignored and capture the rest group which are captured right?

(?:\(([\w+\s*]+)\))

thanks!
Erik

Body:
This seems to work:

a = re.search('(\w+)(\([\w+\s*]+\))?(\[.*\])',string).groups()
print(a) #('Alabama', None, '[edit]')

In your original expression you didn't use the optional indicator. To make the group optional you put the ? at the end, after the closing ). The ?: notation you used means the following group will be ignored in the result, but will be always taken into consideration for matching. It basically says: "Match this group, but i don't want to know anything about it in the result"

I think what you wanted after all is this:

a = re.search('(\w+)(?:\([\w+\s*]+\))?(\[.*\])',string).groups()

so:

import re
s1 = 'Alabama[edit]'
s2 = 'Alabama(test)[edit]'
print(re.search(r'(\w+)(?:\(([\w+\s*]+)\))?(\[.*\])',s1).groups())
#('Alabama', None, '[edit]')
print(re.search(r'(\w+)(?:\(([\w+\s*]+)\))?(\[.*\])',s2).groups())
#('Alabama', 'test', '[edit]')


问:
Replace single zeros of a tab-separated-values file
How do I replace single zeros (0) with string NA in a tab-separated-values file?

Suppose I have the table:

```<code>0\t0.15\t0t\8.05\t0\t0\t0.15\7.0306\n
5\t0.18\t0\8.05\t0\t0\t0.5t\50\n
1\t15\t0205\t0\t0.16\t200t\40.90\n
</code>```

I would like to get:

```<code>NA\t0.15\NAt\8.05\tNA\tNA\t0.15t\7.0306\n
5\t0.18\tNA\8.05\tNA\tNA\t0.5t\50\n
1\t15\t0205\tNA\t0.16\t200t\40.90\n
</code>```

That is, I would like to match the null measures of the data frame.

答:
With GNU sed:

```<code>sed -E ':a;s/(\t)*\b0\b(\t)/\1NA\2/g;ta;' file
</code>```

Using backreference, this replace 0 eventually preceded of followed by a tab(\t) with NA and captured tab.

Body:
How do I replace single zeros (0) with string NA in a tab-separated-values file?

Suppose I have the table:

0\t0.15\t0t\8.05\t0\t0\t0.15\7.0306\n
5\t0.18\t0\8.05\t0\t0\t0.5t\50\n
1\t15\t0205\t0\t0.16\t200t\40.90\n

I would like to get:

NA\t0.15\NAt\8.05\tNA\tNA\t0.15t\7.0306\n
5\t0.18\tNA\8.05\tNA\tNA\t0.5t\50\n
1\t15\t0205\tNA\t0.16\t200t\40.90\n

That is, I would like to match the null measures of the data frame.

Body:
With GNU sed:

sed -E ':a;s/(\t)*\b0\b(\t)/\1NA\2/g;ta;' file

Using backreference, this replace 0 eventually preceded of followed by a tab(\t) with NA and captured tab.


问:
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
I am working on the snippet

```<code>top[0].data[128,0:128] = (fc1[self.keep1.tolist()])[self.keep2[128].tolist()]
</code>```

keep1 has the data

```<code>[
  0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, ...... 114.0, 115.0, 116.0, 117.0, 118.0, 119.0
]
</code>```

keep2 has the data

```<code>[
   125.  800.  255.  119.  801.  804.  114.  368.  636.  308.  805.  213.
   ......218.   373.
]
</code>```

I got a problem saying "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

I tried  self.keep2[128].tolist().astype(int), but it does say tolist() has no method astype(int)

how could I solve it?

答:
Assuming that top[0].data, fc1, self.keep1 and self.keep2 are all numpy arrays you are making your solution too complicated, when you turn your variables into lists. It is sufficient to do

```<code>top[0].data[128,0:128] = (fc1[self.keep1.astype(int)])[self.keep2[128].astype(int)]
</code>```

if the dimensions are correct.

You should also ask yourself why keep1 and keep2 are floats and not ints to begin with. Are they the result of some float calculation? And in that case, can you be sure they do not have any fractional part?

Body:
I am working on the snippet

top[0].data[128,0:128] = (fc1[self.keep1.tolist()])[self.keep2[128].tolist()]

keep1 has the data

[
  0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, ...... 114.0, 115.0, 116.0, 117.0, 118.0, 119.0
]

keep2 has the data

[
   125.  800.  255.  119.  801.  804.  114.  368.  636.  308.  805.  213.
   ......218.   373.
]

I got a problem saying "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

I tried  self.keep2[128].tolist().astype(int), but it does say tolist() has no method astype(int)

how could I solve it?

Body:
Assuming that top[0].data, fc1, self.keep1 and self.keep2 are all numpy arrays you are making your solution too complicated, when you turn your variables into lists. It is sufficient to do

top[0].data[128,0:128] = (fc1[self.keep1.astype(int)])[self.keep2[128].astype(int)]

if the dimensions are correct.

You should also ask yourself why keep1 and keep2 are floats and not ints to begin with. Are they the result of some float calculation? And in that case, can you be sure they do not have any fractional part?


问:
Adobe Flex control missing vertical scroll bar
I have a canvas containing a datagrid.  I set horizontal and vertical scroll to 'off' for the canvas, and set both to 'auto' for the DG.  This works until I have a larger number of columns in the DG (>=16), then the vertical scroll bar doesn't appear.  Anyone seen this and, better yet, have an answer?</p>

答: Found a simple solution, if not an answer.  The outer container was specified with fixed height and width, and the inner DG was set to 100% height and width.  Setting the DG height and width to fixed values a bit smaller than the outer container did the trick.  Still, it seems "100%" should work.</p>


问:
Why getting Double.isNan() value as False in below scenario?
Can anyone explain why the flag value is returning False?   </p>

```<code>double a = 1.0;
double b = 0.0;
double c = a / b;
boolean flag = Double.isNaN(c);
System.out.println(flag); // False?
System.out.println(c); // Infinity
</code>```

答:
That's what the IEEE-754 standard says. When you divide a non-zero floating point number by zero, it does not return a number, but infinity.

Take a look at this: http://grouper.ieee.org/groups/754/faq.html#exceptions

Body:
Can anyone explain why the flag value is returning False?

double a = 1.0;
double b = 0.0;
double c = a / b;
boolean flag = Double.isNaN(c);
System.out.println(flag); // False?
System.out.println(c); // Infinity