问:
expected struct `std::string::String`, found struct `std::str::Split`
I am making a program which calculates the difference between number of days in date, input by the user. So far I am able to make the program work with string literal but not with the string object.

```<code>use std::io;

fn main() {
    let mut date_1 = "22/8/2019".split("/");
    let mut date_2 = "30/8/2019".split("/");
    let vec_1: Vec<&str> = date_1.collect();
    let vec_2: Vec<&str> = date_2.collect();
    println!("{:#?}", vec_1);
    println!("{:#?}", vec_2);
    let my_int_2 = vec_2[0].parse::<i32>().unwrap();
    let my_int_1 = vec_1[0].parse::<i32>().unwrap();
    let result = my_int_2 - my_int_1;
    println!("The difference between two dates is: {}", result);
}
</code>```

Output:

```<code>[
    "22",
    "8",
    "2019",
]
[
    "30",
    "8",
    "2019",
]
The difference between two dates is: 8
</code>```

I want ask the date from user:

```<code>use std::io;

fn main() {
    let mut date_1 = String::new();
    println!("Enter a date in (dd/mm/yy) format: ");
    io::stdin()
        .read_line(&mut date_1)
        .ok()
        .expect("Couldn't read line");

    let mut date_2 = String::new();
    println!("Enter a date in (dd/mm/yy) format: ");
    io::stdin()
        .read_line(&mut date_2)
        .ok()
        .expect("Couldn't read line");
    date_1 = date_1.split("/");
    date_2 = date_2.split("/");
    let vec_1: Vec<&str> = date_1.collect();
    let vec_2: Vec<&str> = date_2.collect();
    println!("{:#?}", vec_1);
    println!("{:#?}", vec_2);
    let my_int_2 = vec_2[0].parse::<i32>().unwrap();
    let my_int_1 = vec_1[0].parse::<i32>().unwrap();
    let result = my_int_2 - my_int_1;
    println!("The difference between two dates is: {}", result);
}
</code>```

Output:

```<code>   Compiling twentythree v0.1.0 (C:\Users\Muhammad.3992348\Desktop\rust\hackathon\twentythree)
error[E0308]: mismatched types
  --> src\main.rs:15:14
   |
15 |     date_1 = date_1.split("/");
   |              ^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found struct `std::str::Split`
   |
   = note: expected type `std::string::String`
              found type `std::str::Split<'_, &str>`

error[E0308]: mismatched types
  --> src\main.rs:16:14
   |
16 |     date_2 = date_2.split("/");
   |              ^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found struct `std::str::Split`
   |
   = note: expected type `std::string::String`
              found type `std::str::Split<'_, &str>`

error[E0599]: no method named `collect` found for type `std::string::String` in the current scope
  --> src\main.rs:19:35
   |
19 |     let vec_1: Vec<&str> = date_1.collect();
   |                                   ^^^^^^^
   |
   = note: the method `collect` exists but the following trait bounds were not satisfied:
           `&mut std::string::String : std::iter::Iterator`
           `&mut str : std::iter::Iterator`

error[E0599]: no method named `collect` found for type `std::string::String` in the current scope
  --> src\main.rs:20:35
   |
20 |     let vec_2: Vec<&str> = date_2.collect();
   |                                   ^^^^^^^
   |
   = note: the method `collect` exists but the following trait bounds were not satisfied:
           `&mut std::string::String : std::iter::Iterator`
           `&mut str : std::iter::Iterator`

error: aborting due to 4 previous errors

Some errors occurred: E0308, E0599.
For more information about an error, try `rustc --explain E0308`.
error: Could not compile `twentythree`.

To learn more, run the command again with --verbose.
</code>```

How to convert string object into string literal or any other war around, which runs the program.

答:
The problem is this:

```<code>let mut date_1 = String::new(); /* type: std::string::String */
// ...
date_1 = date_1.split("/"); /* type: std::str::Split<'_, &str> */
</code>```

You've declared a variable with one type (String) but you're trying to assign it with a different type (std::str::Split).

One "Rust-y" way of solving this is typically to redeclare a variable with the same name:

```<code>let date_1 = String::new(); /* type: std::string::String */
// ...
let date_1 = date_1.split("/"); /* type: std::str::Split<'_, &str> */
</code>```

The second date_1 is a different variable (hence it can have a different type), but it has the same name as the former variable, so it "shadows" the former variable (meaning you cannot refer to it by name anymore).

Body:
I am making a program which calculates the difference between number of days in date, input by the user. So far I am able to make the program work with string literal but not with the string object.

use std::io;

fn main() {
    let mut date_1 = "22/8/2019".split("/");
    let mut date_2 = "30/8/2019".split("/");
    let vec_1: Vec<&str> = date_1.collect();
    let vec_2: Vec<&str> = date_2.collect();
    println!("{:#?}", vec_1);
    println!("{:#?}", vec_2);
    let my_int_2 = vec_2[0].parse::<i32>().unwrap();
    let my_int_1 = vec_1[0].parse::<i32>().unwrap();
    let result = my_int_2 - my_int_1;
    println!("The difference between two dates is: {}", result);
}

Output:

[
    "22",
    "8",
    "2019",
]
[
    "30",
    "8",
    "2019",
]
The difference between two dates is: 8

I want ask the date from user:

use std::io;

fn main() {
    let mut date_1 = String::new();
    println!("Enter a date in (dd/mm/yy) format: ");
    io::stdin()
        .read_line(&mut date_1)
        .ok()
        .expect("Couldn't read line");

    let mut date_2 = String::new();
    println!("Enter a date in (dd/mm/yy) format: ");
    io::stdin()
        .read_line(&mut date_2)
        .ok()
        .expect("Couldn't read line");
    date_1 = date_1.split("/");
    date_2 = date_2.split("/");
    let vec_1: Vec<&str> = date_1.collect();
    let vec_2: Vec<&str> = date_2.collect();
    println!("{:#?}", vec_1);
    println!("{:#?}", vec_2);
    let my_int_2 = vec_2[0].parse::<i32>().unwrap();
    let my_int_1 = vec_1[0].parse::<i32>().unwrap();
    let result = my_int_2 - my_int_1;
    println!("The difference between two dates is: {}", result);
}

Output:

   Compiling twentythree v0.1.0 (C:\Users\Muhammad.3992348\Desktop\rust\hackathon\twentythree)
error[E0308]: mismatched types
  --> src\main.rs:15:14
   |
15 |     date_1 = date_1.split("/");
   |              ^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found struct `std::str::Split`
   |
   = note: expected type `std::string::String`
              found type `std::str::Split<'_, &str>`

error[E0308]: mismatched types
  --> src\main.rs:16:14
   |
16 |     date_2 = date_2.split("/");
   |              ^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found struct `std::str::Split`
   |
   = note: expected type `std::string::String`
              found type `std::str::Split<'_, &str>`

error[E0599]: no method named `collect` found for type `std::string::String` in the current scope
  --> src\main.rs:19:35
   |
19 |     let vec_1: Vec<&str> = date_1.collect();
   |                                   ^^^^^^^
   |
   = note: the method `collect` exists but the following trait bounds were not satisfied:
           `&mut std::string::String : std::iter::Iterator`
           `&mut str : std::iter::Iterator`

error[E0599]: no method named `collect` found for type `std::string::String` in the current scope
  --> src\main.rs:20:35
   |
20 |     let vec_2: Vec<&str> = date_2.collect();
   |                                   ^^^^^^^
   |
   = note: the method `collect` exists but the following trait bounds were not satisfied:
           `&mut std::string::String : std::iter::Iterator`
           `&mut str : std::iter::Iterator`

error: aborting due to 4 previous errors

Some errors occurred: E0308, E0599.
For more information about an error, try `rustc --explain E0308`.
error: Could not compile `twentythree`.

To learn more, run the command again with --verbose.

How to convert string object into string literal or any other war around, which runs the program.

Body:
The problem is this:

let mut date_1 = String::new(); /* type: std::string::String */
// ...
date_1 = date_1.split("/"); /* type: std::str::Split<'_, &str> */

You've declared a variable with one type (String) but you're trying to assign it with a different type (std::str::Split).

One "Rust-y" way of solving this is typically to redeclare a variable with the same name:

let date_1 = String::new(); /* type: std::string::String */
// ...
let date_1 = date_1.split("/"); /* type: std::str::Split<'_, &str> */

The second date_1 is a different variable (hence it can have a different type), but it has the same name as the former variable, so it "shadows" the former variable (meaning you cannot refer to it by name anymore).


来源: stackexchange

问:
EF Core In-Memmory Array mapping
I have a string array column in database

```<code>ALTER TABLE sample ADD languages VARCHAR[] NULL;
</code>```

which is mapped to model:

```<code>public string[] languages { get; set; }
</code>```

Using EF Core with PostgreSQL (Npgsql.EntityFrameworkCore.PostgreSQL 2.2.0) works out of the box.

However, when I want to test DbContext using In-Memmory (Microsoft.EntityFrameworkCore.InMemory 2.2.4) I got this error:

System.InvalidOperationException: The property 'sample.languages' could not be mapped, because it is of type 'string[]' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

So, adding this to model builder configuration solves the In-Memmory error:

```<code> builder.Property(p => p.languages)
                    .HasConversion(
                        v => string.Join("'", v),
                        v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
</code>```

But raises new one (Npgsql):

Can't cast database type character varying[] to String
     at Npgsql.NpgsqlDefaultDataReader.GetFieldValue[T](Int32 column)

Do you have any hints please?

答:
Not many databases support array type columns out of the box. Actually PostgreSQL might be the only one from the currently supported databases which does that. According to the original exception, apparently in-memory database also doesn't support it (currently).

EF Core builds a separate model for each database type. Each database provider exposes an extension method of DatabaseFacade like IsSqlServer(), IsNpgsql(), IsInMemory() etc. which can be used inside OnModelCreating to conditionally configure different mappings for a specific database type(s) if needed.

The intended usage is like this:

```<code>modelBuilder.Entity<Sample>(builder =>
{
    if (!Database.IsNpgsql()) // <--
    {
         builder.Property(p => p.languages)
             .HasConversion(
                 v => string.Join("'", v),
                 v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
    }
});
</code>```

If you are using separate classes implementing IEntityTypeConfiguration<TEntity> for configuring the model, then you should pass the Database to their constructor and store in a class member, because the EntityTypeBuilder<TEntity> passed to the Configure method does not provide such information.

ContentLicense: CC BY-SA 4.0

Title: EF Core In-Memmory Array mapping

Body:
I have a string array column in database

ALTER TABLE sample ADD languages VARCHAR[] NULL;

which is mapped to model:

public string[] languages { get; set; }

Using EF Core with PostgreSQL (Npgsql.EntityFrameworkCore.PostgreSQL 2.2.0) works out of the box.

However, when I want to test DbContext using In-Memmory (Microsoft.EntityFrameworkCore.InMemory 2.2.4) I got this error:

System.InvalidOperationException: The property 'sample.languages' could not be mapped, because it is of type 'string[]' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

So, adding this to model builder configuration solves the In-Memmory error:

 builder.Property(p => p.languages)
                    .HasConversion(
                        v => string.Join("'", v),
                        v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));

But raises new one (Npgsql):

Can't cast database type character varying[] to String
     at Npgsql.NpgsqlDefaultDataReader.GetFieldValue[T](Int32 column)

Do you have any hints please?

Body:
Not many databases support array type columns out of the box. Actually PostgreSQL might be the only one from the currently supported databases which does that. According to the original exception, apparently in-memory database also doesn't support it (currently).

EF Core builds a separate model for each database type. Each database provider exposes an extension method of DatabaseFacade like IsSqlServer(), IsNpgsql(), IsInMemory() etc. which can be used inside OnModelCreating to conditionally configure different mappings for a specific database type(s) if needed.

The intended usage is like this:

modelBuilder.Entity<Sample>(builder =>
{
    if (!Database.IsNpgsql()) // <--
    {
         builder.Property(p => p.languages)
             .HasConversion(
                 v => string.Join("'", v),
                 v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
    }
});

If you are using separate classes implementing IEntityTypeConfiguration<TEntity> for configuring the model, then you should pass the Database to their constructor and store in a class member, because the EntityTypeBuilder<TEntity> passed to the Configure method does not provide such information.


问:
When app is closed how can i use local notification from sqlite data in flutter
Flutter Issue for background processing

How to show local notification from sqlite while app is closed in flutter?

答:
Try flutter_local_notifications, code snippet from the sample example app.

```<code>  Future<void> _showNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
        0, 'plain title', 'plain body', platformChannelSpecifics,
        payload: 'item x');
  }
</code>```

It also has the option to schedule an Notification, and route based on the Notification clicked.

Body:
Try flutter_local_notifications, code snippet from the sample example app.

  Future<void> _showNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
        0, 'plain title', 'plain body', platformChannelSpecifics,
        payload: 'item x');
  }

It also has the option to schedule an Notification, and route based on the Notification clicked.


问:
Sort ObservableCollection - what is the best approach?
I have a ObservableCollection , where MyData is a class with 4 properties i.e. int id, string name, bool IsSelected, string IsVisible.

This ObservableCollection is binded to a combobox with checkboxes(Cities data for example). Now, when the user checks the checkboxes then next time when he opens the drop down - all selections should come on top in ascending order by name.

I have also implemented auto complete when the user types in 3 chars in the combobox, the drop down will open showing all the selections first, then then all the items starting from the 3 chars type in by the user.

I have researched and implemented the following code and it is working fine, but i want to know whether this is the best approach or can i implement this in a better manner, code is :

```<code>        IEnumerable<MyData> sort;
        ObservableCollection<MyData> tempSortedCities = new ObservableCollection<MyData>();
        sort = City.OrderByDescending(item => item.IsSelected).ThenBy(item => item.Name.ToUpper()) ;
       // City is my observablecollection<MyData> property in my Model binded to combobox in UI
        foreach (var item in sort)
            tempSortedCities.Add(item);

        City.Clear(); // City is my observablecollection<MyData> property in my Model
        City = tempSortedCities;
        tempSortedCities = null;
        sort = null;
</code>```

Thanks in advance for your time !

答:
ICollectionView seems to be a perfect fit for this. It was designed specifically for sorting, filtering and grouping of a collection without modifying the original collection.

You can get an instance of ICollectionView for your collection using the following code:

```<code>var sortedCities  = CollectionViewSource.GetDefaultView(City);
</code>```

Then you can setup sorting by adding instances of SortDescription type to the ICollectionView.SortDescriptions collection:

```<code>sortedCities.SortDescriptions.Add(new SortDescription("IsSelected", ListSortDirection.Descending));
sortedCities.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
</code>```

Then you can bind your ComboBox directly to the collection view (instead of City collection) and it will display already sorted data.

ContentLicense: CC BY-SA 3.0

Body:
I have a ObservableCollection , where MyData is a class with 4 properties i.e. int id, string name, bool IsSelected, string IsVisible.

This ObservableCollection is binded to a combobox with checkboxes(Cities data for example). Now, when the user checks the checkboxes then next time when he opens the drop down - all selections should come on top in ascending order by name.

I have also implemented auto complete when the user types in 3 chars in the combobox, the drop down will open showing all the selections first, then then all the items starting from the 3 chars type in by the user.

I have researched and implemented the following code and it is working fine, but i want to know whether this is the best approach or can i implement this in a better manner, code is :

        IEnumerable<MyData> sort;
        ObservableCollection<MyData> tempSortedCities = new ObservableCollection<MyData>();
        sort = City.OrderByDescending(item => item.IsSelected).ThenBy(item => item.Name.ToUpper()) ;
       // City is my observablecollection<MyData> property in my Model binded to combobox in UI
        foreach (var item in sort)
            tempSortedCities.Add(item);

        City.Clear(); // City is my observablecollection<MyData> property in my Model
        City = tempSortedCities;
        tempSortedCities = null;
        sort = null;

Thanks in advance for your time !

Body:
ICollectionView seems to be a perfect fit for this. It was designed specifically for sorting, filtering and grouping of a collection without modifying the original collection.

You can get an instance of ICollectionView for your collection using the following code:

var sortedCities  = CollectionViewSource.GetDefaultView(City);

Then you can setup sorting by adding instances of SortDescription type to the ICollectionView.SortDescriptions collection:

sortedCities.SortDescriptions.Add(new SortDescription("IsSelected", ListSortDirection.Descending));
sortedCities.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

Then you can bind your ComboBox directly to the collection view (instead of City collection) and it will display already sorted data.


问:
Sparx EA Heatmap: Combine none or multiple results from a selects subquery into a single comma-separated value
I'm using Sparx EA 14.x with the file based repository, and moving into SQL server based soon. Currently creating some base template level model, to be used later with real customer data with SQL server based repository.
I have created Tagged Values (type=RefGUIDList) for e.g. adding relation into existing Bus.Processes in my data elemets. The list of existing business processes can be selected and their .ea_guid is stored in the tagged value as value.

I have created an HeatMap chart, with attached sql.

The sql works fine if the tagged value has only one business process selected, the problem is that if I add more processes there is no results.

```<code> SELECT (SELECT t_object.Name FROM t_object
         WHERE t_object.ea_guid = tv.Value) AS Series,
        t_object.Alias AS GroupName, Packages.Name
 FROM t_object,
      t_package RootPackage,
      t_package Packages,
      t_objectproperties tv
 WHERE RootPackage.Name = 'Data elements' AND
       Packages.Parent_ID = RootPackage.Package_ID AND
       t_object.Package_ID = Packages.Package_ID AND
       t_object.Object_ID = tv.Object_ID AND
       tv.Property = 'APM:Prosesses'
</code>```

One solution, that I have been looking, would be to concatenate the listed Bus.processes names and show the result.

I'm aware that the SQL server dialect is different than the current Access based repository.

答:
The problem was that the Sparx t_objectproperties.ea_guid was stored in several times into t_objectproperties.Value and I did need the corresponding t_object.Name as comma concatenated.

In my case worked a solution, where I 1st moved the repository into SQL server based repository and did create a function like below:

```<code>CREATE FUNCTION fnSplitString
(
    @string NVARCHAR(1000),
    @delimiter CHAR(1)
 )
 RETURNS VARCHAR(1000) AS
 BEGIN
    DECLARE @csvObjectname VARCHAR(1000)
    DECLARE @start INT, @end INT
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
    WHILE @start < LEN(@string) + 1 BEGIN
      IF @end = 0
        SET @end = LEN(@string) + 1
      SELECT @csvObjectname = COALESCE(@csvObjectname + ', ', '') +
            COALESCE(t_Object.Name,'')
      FROM t_Object
        WHERE t_Object.ea_guid = SUBSTRING(@string, @start, @end - @start)
      SET @start = @end + 1
      SET @end = CHARINDEX(@delimiter, @string, @start)

  END
  RETURN @csvObjectname
END
</code>```

Body:
I'm using Sparx EA 14.x with the file based repository, and moving into SQL server based soon. Currently creating some base template level model, to be used later with real customer data with SQL server based repository.
I have created Tagged Values (type=RefGUIDList) for e.g. adding relation into existing Bus.Processes in my data elemets. The list of existing business processes can be selected and their .ea_guid is stored in the tagged value as value.

I have created an HeatMap chart, with attached sql.

The sql works fine if the tagged value has only one business process selected, the problem is that if I add more processes there is no results.

 SELECT (SELECT t_object.Name FROM t_object
         WHERE t_object.ea_guid = tv.Value) AS Series,
        t_object.Alias AS GroupName, Packages.Name
 FROM t_object,
      t_package RootPackage,
      t_package Packages,
      t_objectproperties tv
 WHERE RootPackage.Name = 'Data elements' AND
       Packages.Parent_ID = RootPackage.Package_ID AND
       t_object.Package_ID = Packages.Package_ID AND
       t_object.Object_ID = tv.Object_ID AND
       tv.Property = 'APM:Prosesses'

One solution, that I have been looking, would be to concatenate the listed Bus.processes names and show the result.

I'm aware that the SQL server dialect is different than the current Access based repository.

Body:
The problem was that the Sparx t_objectproperties.ea_guid was stored in several times into t_objectproperties.Value and I did need the corresponding t_object.Name as comma concatenated.

In my case worked a solution, where I 1st moved the repository into SQL server based repository and did create a function like below:

CREATE FUNCTION fnSplitString
(
    @string NVARCHAR(1000),
    @delimiter CHAR(1)
 )
 RETURNS VARCHAR(1000) AS
 BEGIN
    DECLARE @csvObjectname VARCHAR(1000)
    DECLARE @start INT, @end INT
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
    WHILE @start < LEN(@string) + 1 BEGIN
      IF @end = 0
        SET @end = LEN(@string) + 1
      SELECT @csvObjectname = COALESCE(@csvObjectname + ', ', '') +
            COALESCE(t_Object.Name,'')
      FROM t_Object
        WHERE t_Object.ea_guid = SUBSTRING(@string, @start, @end - @start)
      SET @start = @end + 1
      SET @end = CHARINDEX(@delimiter, @string, @start)

  END
  RETURN @csvObjectname
END


问:
how to turn a list of strings in a list of objects?
I have a list of strings from an external text file. Each string is like this: name job location. What is the fastest way to turn each string into an object, creating a list of objects?

The objects are like this:

class Person:
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location
```

答:
You will need to open your file, read line by line, split the line on the spaces (since you don't want to add commas) and create the object:</p>

```<code>p = []

with open('file', 'r') as f:
    for line in f:
        values = line.split(' ')
        p.append(people(values[0], values[1], values[2]))
</code>```

Body:
You will need to open your file, read line by line, split the line on the spaces (since you don't want to add commas) and create the object:

p = []

with open('file', 'r') as f:
    for line in f:
        values = line.split(' ')
        p.append(people(values[0], values[1], values[2]))


问:
Flutter: How can I receive local notifications even if my app is closed?
I created a Flutter app that receive signals every minute, and I display local notifications when I receive a new signal. The notifications are well displayed when the app is opened but when the app is closed, I receive nothing. I tried to add

```<code>    <receiver android:name=".notification.NotificationReceiver">
        <intent-filter>
            <action android:name="io.flutter.app.notification.RECEIVE"/>
            <action android:name="io.flutter.app.notification.DELETE" />
            <action android:name="io.flutter.app.notification.OPEN" />
        </intent-filter>
    </receiver>
</code>```

in my AndroidManifest.xml as shown in this issue for Android but it's not working.

There is a way to do that with Flutter?

答:
If its Local notification then, try flutter_local_notifications, code snippet from the sample example app.

```<code>  Future<void> _showNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
        0, 'plain title', 'plain body', platformChannelSpecifics,
        payload: 'item x');
  }
</code>```

It also has the option to schedule an Notification, and route based on the Notification clicked.

Body:
I created a Flutter app that receive signals every minute, and I display local notifications when I receive a new signal. The notifications are well displayed when the app is opened but when the app is closed, I receive nothing. I tried to add

    <receiver android:name=".notification.NotificationReceiver">
        <intent-filter>
            <action android:name="io.flutter.app.notification.RECEIVE"/>
            <action android:name="io.flutter.app.notification.DELETE" />
            <action android:name="io.flutter.app.notification.OPEN" />
        </intent-filter>
    </receiver>

in my AndroidManifest.xml as shown in this issue for Android but it's not working.

There is a way to do that with Flutter?

Body:
If its Local notification then, try flutter_local_notifications, code snippet from the sample example app.

  Future<void> _showNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
        0, 'plain title', 'plain body', platformChannelSpecifics,
        payload: 'item x');
  }

It also has the option to schedule an Notification, and route based on the Notification clicked.


问:
How to create a Controller to simulate the Springboard feature of the iPhone within your own application
I am trying to design a feature in my application for the iPhone that simulates the Springboard feature (Main menu of the iPhone that allows you to view more apps), or the way Weather application works that allows you to flip between views.

Does anyone have any samples of this how I would go about doing this.  It's seems very trivial but I am wondering if I am missing something that is already available either as an Apple example or someone who did a tutorial on this.

The image below show how the user would use it.
alt text http://www.agilitesoftware.com/SpringboardExample.png

As they slide their finger to the right (or left) the other image would begin to show up. And it would animate smoothly.  The faster you swiped your finger the faster it would move to the next view.

Update: The other feature is that it should mimic the same feel when you slide your hand across the display that is snaps to the current view into place.  It should not keep sliding across if there is more than 1 view to the direction you swiping your finger.

I've seen other applications use this so that is why I am asking.

答:
There is a sample app (with code) with exactly this functionality on the iPhone developer site on Apple.com (I believe it's called "PageControl".) - I'd suggest checking it out.

d.

OwnerDisplayName: Niels Hansen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Dunk


问:
using exec to execute a system command in a new process
I am trying to spawn a process that executes a system command, while my own program still proceeds and two processes will run in parallel. I am working on linux.

I looked up online and sounds like I should use exec() family. But it doesn't work quite as what I expected. For example, in the following code, I only see "before" being printed, ,but not "done".

I am curious if I am issing anything?

```<code>#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
   cout << "done" << endl;
}
</code>```

[UPDATE]

Thank you for your guys comments. Now my program looks like this. Everything works fine except at the end, I have to press enter to finish the program. I am not sure why I have to press the last enter?

```<code>#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   int pid = fork();
   cout << pid << endl;
   if (pid==0) {
      execl("/bin/ls", "ls", "-r", "-t", "-l", (char *) 0);
   }
   cout << "done" << endl;
}
</code>```

答:
The Exec family of functions replaces the current process with the new executable.

To do what you need, use one of the fork() functions and have the child process exec the new image.

[response to update]

It is doing exactly what you told it:  You don't have to press "enter" to finish the program:  It has already exited.  The shell has already given a prompt:

```<code>[wally@zenetfedora ~]$ ./z
before
22397
done
[wally@zenetfedora ~]$ 0               << here is the prompt (as well as the pid)
total 5102364
drwxr-xr-x.  2 wally wally       4096 2011-01-31 16:22 Templates
...
</code>```

The output from ls takes awhile so it buries the prompt.  If you want output to appear in a more logical order, add sleep(1) (or maybe longer) before the "done".

Body:
I am trying to spawn a process that executes a system command, while my own program still proceeds and two processes will run in parallel. I am working on linux.

I looked up online and sounds like I should use exec() family. But it doesn't work quite as what I expected. For example, in the following code, I only see "before" being printed, ,but not "done".

I am curious if I am issing anything?

#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
   cout << "done" << endl;
}

[UPDATE]

Thank you for your guys comments. Now my program looks like this. Everything works fine except at the end, I have to press enter to finish the program. I am not sure why I have to press the last enter?

#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   int pid = fork();
   cout << pid << endl;
   if (pid==0) {
      execl("/bin/ls", "ls", "-r", "-t", "-l", (char *) 0);
   }
   cout << "done" << endl;
}

Body:
The Exec family of functions replaces the current process with the new executable.

To do what you need, use one of the fork() functions and have the child process exec the new image.

[response to update]

It is doing exactly what you told it:  You don't have to press "enter" to finish the program:  It has already exited.  The shell has already given a prompt:

[wally@zenetfedora ~]$ ./z
before
22397
done
[wally@zenetfedora ~]$ 0               << here is the prompt (as well as the pid)
total 5102364
drwxr-xr-x.  2 wally wally       4096 2011-01-31 16:22 Templates
...

The output from ls takes awhile so it buries the prompt.  If you want output to appear in a more logical order, add sleep(1) (or maybe longer) before the "done".


问:
Reading and printing values from tcx files in Python
I am writing Python code to read a TCX file that downloads from my Polar Heart Rate monitor. I have tried using the xml.dom library and what I am getting appears to be some sort of class or memory location.

The data I am looking at has heart rates (and other information) for each second in an exercise file.

Here is a part of the data file:

```<code><Trackpoint>
    <Time>2019-05-24T12:12:10.000Z</Time>
    <Position><LatitudeDegrees>37.09307833</LatitudeDegrees
    <LongitudeDegrees>-84.60697</LongitudeDegrees></Position>
    <DistanceMeters>0.10000000149011612</DistanceMeters>
    <HeartRateBpm><Value>73</Value></HeartRateBpm>
    <Cadence>0</Cadence><SensorState>Present</SensorState>
</Trackpoint>
<Trackpoint>
    <Time>2019-05-24T12:12:11.000Z</Time>
    <Position><LatitudeDegrees>37.09307667</LatitudeDegrees>
    <LongitudeDegrees>-84.60697667</LongitudeDegrees></Position>
    <HeartRateBpm><Value>73</Value></HeartRateBpm>
    <Cadence>0</Cadence><SensorState>Present</SensorState>
</Trackpoint>
<Trackpoint>
    <Time>2019-05-24T12:12:12.000Z</Time>
    <Position><LatitudeDegrees>37.09307167</LatitudeDegrees>
    <LongitudeDegrees>-84.60698167</LongitudeDegrees></Position>
    <DistanceMeters>0.800000011920929</DistanceMeters>
    <HeartRateBpm><Value>73</Value></HeartRateBpm>
    <Cadence>0</Cadence><SensorState>Present</SensorState>
</Trackpoint>
</code>```

Here is the code I am using:

```<code>from xml.dom import minidom
from datetime import *

xmldoc = minidom.parse("testfile.tcx")
print(xmldoc)

tcd = xmldoc.getElementsByTagName("TrainingCenterDatabase")[0]

activitiesElement = tcd.getElementsByTagName("Activities")[0]

activities = activitiesElement.getElementsByTagName("Activity")

for activity in activities:
    sport = activity.attributes["Sport"]
    sportName = sport.value

    idElement = activity.getElementsByTagName("Id")[0]
    timeOfDay = idElement.firstChild.data
    year = int(timeOfDay[0:4])
    month = int(timeOfDay[5:7])
    day = int(timeOfDay[8:10])
    date = datetime(year,month,day)
    #print(sportName, month, day, year)
    print(sportName, date)

trackPoints = tcd.getElementsByTagName("Time")
heartRate = tcd.getElementsByTagName("Value")

print(type(trackPoints))
print(type(heartRate))

i=0

while i <= 10:
    print(trackPoints[i], heartRate[i])
    i += 1
</code>```

This is the output I am getting from this program:

```<code>C:\Python\Heart Rate Data>python "c:/Python/Heart Rate
Data/readfiletest4.py"
<xml.dom.minidom.Document object at 0x00000217F5A86948>
Running 2019-05-24 00:00:00
<class 'xml.dom.minicompat.NodeList'>
<class 'xml.dom.minicompat.NodeList'>
<DOM Element: Time at 0x217f5a92048> <DOM Element: Value at 0x217f5a4daf8>
<DOM Element: Time at 0x217f5a92638> <DOM Element: Value at 0x217f5a4dc28>
<DOM Element: Time at 0x217f5a92b90> <DOM Element: Value at 0x217f5a923d8>
<DOM Element: Time at 0x217f5aae210> <DOM Element: Value at 0x217f5a92930>
<DOM Element: Time at 0x217f5aae768> <DOM Element: Value at 0x217f5a92f20>
<DOM Element: Time at 0x217f5aaed58> <DOM Element: Value at 0x217f5aae508>
<DOM Element: Time at 0x217f5aaf3d8> <DOM Element: Value at 0x217f5aaeaf8>
<DOM Element: Time at 0x217f5aaf9c8> <DOM Element: Value at 0x217f5aaf178>
<DOM Element: Time at 0x217f5ab0048> <DOM Element: Value at 0x217f5aaf768>
<DOM Element: Time at 0x217f5ab0638> <DOM Element: Value at 0x217f5aafd58>
<DOM Element: Time at 0x217f5ab0c28> <DOM Element: Value at 0x217f5ab03d8>
</code>```

I am hoping to get some sort of array that has various elements from the TCX file so that I can ultimately do some graphing, etc.

答:
In order to get the text of the XML element you need to use the 'text' property of the element.

(You can have a look at this code https://github.com/vkurup/python-tcxparser)

```<code>while i <= 10:
    print(trackPoints[i].text, heartRate[i].text)
    i += 1
</code>```

A complete working example (based on sample XML) below:

```<code>import xml.etree.ElementTree as ET
import re

with open('1.tcx') as xml_file:
    xml_str = xml_file.read()
    xml_str = re.sub(' xmlns="[^"]+"', '', xml_str.decode('utf-8'), count=1)
    root = ET.fromstring(xml_str)
    activities = root.findall('.//Activity')
    for activity in activities:
        print('-- {} --'.format(activity.attrib['Sport']))
        tracking_points = activity.findall('.//Trackpoint')
        for tracking_point in list(tracking_points):
            children = list(tracking_point)
            print('Time: {}, HR Value: {}'.format(children[0].text,
                                                  list(children[4])[0].text))
</code>```

1.tcx

```<code><?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation
="http://www.garmin.com/xmlschemas/ActivityExtension/v2 http://www.garmin.com/xmlschemas/ActivityExtensionv2.xsd http://www.garmin.com/xmlschemas/TrainingCenterDat
abase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">

  <Activities>
    <Activity Sport="Biking">
      <Id>2010-06-26T10:06:11Z</Id>
      <Lap StartTime="2010-06-26T10:06:11Z">
        <TotalTimeSeconds>906.1800000</TotalTimeSeconds>
        <DistanceMeters>9762.4433594</DistanceMeters>
        <MaximumSpeed>15.2404995</MaximumSpeed>
        <Calories>493</Calories>
        <AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
          <Value>179</Value>
        </AverageHeartRateBpm>
        <MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
          <Value>194</Value>
        </MaximumHeartRateBpm>
        <Intensity>Active</Intensity>
        <Cadence>84</Cadence>
        <TriggerMethod>Location</TriggerMethod>
        <Track>
          <Trackpoint>
            <Time>2010-06-26T10:06:11Z</Time>
            <Position>
              <LatitudeDegrees>40.7780135</LatitudeDegrees>
              <LongitudeDegrees>-73.9665795</LongitudeDegrees>
            </Position>
            <AltitudeMeters>36.1867676</AltitudeMeters>
            <DistanceMeters>0.0629519</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>148</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:12Z</Time>
            <Position>
              <LatitudeDegrees>40.7780136</LatitudeDegrees>
              <LongitudeDegrees>-73.9665778</LongitudeDegrees>
            </Position>
            <AltitudeMeters>35.2254639</AltitudeMeters>
            <DistanceMeters>0.1698548</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>148</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:17Z</Time>
            <Position>
              <LatitudeDegrees>40.7780147</LatitudeDegrees>
              <LongitudeDegrees>-73.9665789</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.2641602</AltitudeMeters>
            <DistanceMeters>0.5907414</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>152</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:24Z</Time>
            <Position>
              <LatitudeDegrees>40.7780246</LatitudeDegrees>
              <LongitudeDegrees>-73.9665919</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.7448730</AltitudeMeters>
            <DistanceMeters>1.9415363</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>147</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:25Z</Time>
            <Position>
              <LatitudeDegrees>40.7780338</LatitudeDegrees>
              <LongitudeDegrees>-73.9665851</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.7448730</AltitudeMeters>
            <DistanceMeters>1.9993043</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>147</Value>
            </HeartRateBpm>
            <SensorState>Present</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:28Z</Time>
            <Position>
              <LatitudeDegrees>40.7780800</LatitudeDegrees>
              <LongitudeDegrees>-73.9665492</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.2641602</AltitudeMeters>
            <DistanceMeters>7.9581327</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>148</Value>
            </HeartRateBpm>
            <Cadence>1</Cadence>
            <SensorState>Present</SensorState>
            <Extensions>
              <TPX xmlns="http://www.garmin.com/xmlschemas/ActivityExtension/v2" CadenceSensor="Bike"/>
            </Extensions>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:30Z</Time>
            <Position>
              <LatitudeDegrees>40.7781448</LatitudeDegrees>
              <LongitudeDegrees>-73.9665005</LongitudeDegrees>
            </Position>
            <AltitudeMeters>32.8222656</AltitudeMeters>
            <DistanceMeters>15.3775177</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>151</Value>
            </HeartRateBpm>
            <Cadence>42</Cadence>
            <SensorState>Present</SensorState>
            <Extensions>
              <TPX xmlns="http://www.garmin.com/xmlschemas/ActivityExtension/v2" CadenceSensor="Bike"/>
            </Extensions>
          </Trackpoint>
        </Track>
      </Lap>
    </Activity>
  </Activities>

</TrainingCenterDatabase>
</code>```

output

```<code>-- Biking --
Time: 2010-06-26T10:06:11Z, HR Value: 148
Time: 2010-06-26T10:06:12Z, HR Value: 148
Time: 2010-06-26T10:06:17Z, HR Value: 152
Time: 2010-06-26T10:06:24Z, HR Value: 147
Time: 2010-06-26T10:06:25Z, HR Value: 147
Time: 2010-06-26T10:06:28Z, HR Value: 148
Time: 2010-06-26T10:06:30Z, HR Value: 151
</code>```

Body:
I am writing Python code to read a TCX file that downloads from my Polar Heart Rate monitor. I have tried using the xml.dom library and what I am getting appears to be some sort of class or memory location.

The data I am looking at has heart rates (and other information) for each second in an exercise file.

Here is a part of the data file:

<Trackpoint>
    <Time>2019-05-24T12:12:10.000Z</Time>
    <Position><LatitudeDegrees>37.09307833</LatitudeDegrees
    <LongitudeDegrees>-84.60697</LongitudeDegrees></Position>
    <DistanceMeters>0.10000000149011612</DistanceMeters>
    <HeartRateBpm><Value>73</Value></HeartRateBpm>
    <Cadence>0</Cadence><SensorState>Present</SensorState>
</Trackpoint>
<Trackpoint>
    <Time>2019-05-24T12:12:11.000Z</Time>
    <Position><LatitudeDegrees>37.09307667</LatitudeDegrees>
    <LongitudeDegrees>-84.60697667</LongitudeDegrees></Position>
    <HeartRateBpm><Value>73</Value></HeartRateBpm>
    <Cadence>0</Cadence><SensorState>Present</SensorState>
</Trackpoint>
<Trackpoint>
    <Time>2019-05-24T12:12:12.000Z</Time>
    <Position><LatitudeDegrees>37.09307167</LatitudeDegrees>
    <LongitudeDegrees>-84.60698167</LongitudeDegrees></Position>
    <DistanceMeters>0.800000011920929</DistanceMeters>
    <HeartRateBpm><Value>73</Value></HeartRateBpm>
    <Cadence>0</Cadence><SensorState>Present</SensorState>
</Trackpoint>

Here is the code I am using:

from xml.dom import minidom
from datetime import *

xmldoc = minidom.parse("testfile.tcx")
print(xmldoc)

tcd = xmldoc.getElementsByTagName("TrainingCenterDatabase")[0]

activitiesElement = tcd.getElementsByTagName("Activities")[0]

activities = activitiesElement.getElementsByTagName("Activity")

for activity in activities:
    sport = activity.attributes["Sport"]
    sportName = sport.value

    idElement = activity.getElementsByTagName("Id")[0]
    timeOfDay = idElement.firstChild.data
    year = int(timeOfDay[0:4])
    month = int(timeOfDay[5:7])
    day = int(timeOfDay[8:10])
    date = datetime(year,month,day)
    #print(sportName, month, day, year)
    print(sportName, date)

trackPoints = tcd.getElementsByTagName("Time")
heartRate = tcd.getElementsByTagName("Value")

print(type(trackPoints))
print(type(heartRate))

i=0

while i <= 10:
    print(trackPoints[i], heartRate[i])
    i += 1

This is the output I am getting from this program:

C:\Python\Heart Rate Data>python "c:/Python/Heart Rate
Data/readfiletest4.py"
<xml.dom.minidom.Document object at 0x00000217F5A86948>
Running 2019-05-24 00:00:00
<class 'xml.dom.minicompat.NodeList'>
<class 'xml.dom.minicompat.NodeList'>
<DOM Element: Time at 0x217f5a92048> <DOM Element: Value at 0x217f5a4daf8>
<DOM Element: Time at 0x217f5a92638> <DOM Element: Value at 0x217f5a4dc28>
<DOM Element: Time at 0x217f5a92b90> <DOM Element: Value at 0x217f5a923d8>
<DOM Element: Time at 0x217f5aae210> <DOM Element: Value at 0x217f5a92930>
<DOM Element: Time at 0x217f5aae768> <DOM Element: Value at 0x217f5a92f20>
<DOM Element: Time at 0x217f5aaed58> <DOM Element: Value at 0x217f5aae508>
<DOM Element: Time at 0x217f5aaf3d8> <DOM Element: Value at 0x217f5aaeaf8>
<DOM Element: Time at 0x217f5aaf9c8> <DOM Element: Value at 0x217f5aaf178>
<DOM Element: Time at 0x217f5ab0048> <DOM Element: Value at 0x217f5aaf768>
<DOM Element: Time at 0x217f5ab0638> <DOM Element: Value at 0x217f5aafd58>
<DOM Element: Time at 0x217f5ab0c28> <DOM Element: Value at 0x217f5ab03d8>

I am hoping to get some sort of array that has various elements from the TCX file so that I can ultimately do some graphing, etc.

Body:
In order to get the text of the XML element you need to use the 'text' property of the element.

(You can have a look at this code https://github.com/vkurup/python-tcxparser)

while i <= 10:
    print(trackPoints[i].text, heartRate[i].text)
    i += 1

A complete working example (based on sample XML) below:

import xml.etree.ElementTree as ET
import re

with open('1.tcx') as xml_file:
    xml_str = xml_file.read()
    xml_str = re.sub(' xmlns="[^"]+"', '', xml_str.decode('utf-8'), count=1)
    root = ET.fromstring(xml_str)
    activities = root.findall('.//Activity')
    for activity in activities:
        print('-- {} --'.format(activity.attrib['Sport']))
        tracking_points = activity.findall('.//Trackpoint')
        for tracking_point in list(tracking_points):
            children = list(tracking_point)
            print('Time: {}, HR Value: {}'.format(children[0].text,
                                                  list(children[4])[0].text))

1.tcx

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation
="http://www.garmin.com/xmlschemas/ActivityExtension/v2 http://www.garmin.com/xmlschemas/ActivityExtensionv2.xsd http://www.garmin.com/xmlschemas/TrainingCenterDat
abase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">

  <Activities>
    <Activity Sport="Biking">
      <Id>2010-06-26T10:06:11Z</Id>
      <Lap StartTime="2010-06-26T10:06:11Z">
        <TotalTimeSeconds>906.1800000</TotalTimeSeconds>
        <DistanceMeters>9762.4433594</DistanceMeters>
        <MaximumSpeed>15.2404995</MaximumSpeed>
        <Calories>493</Calories>
        <AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
          <Value>179</Value>
        </AverageHeartRateBpm>
        <MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
          <Value>194</Value>
        </MaximumHeartRateBpm>
        <Intensity>Active</Intensity>
        <Cadence>84</Cadence>
        <TriggerMethod>Location</TriggerMethod>
        <Track>
          <Trackpoint>
            <Time>2010-06-26T10:06:11Z</Time>
            <Position>
              <LatitudeDegrees>40.7780135</LatitudeDegrees>
              <LongitudeDegrees>-73.9665795</LongitudeDegrees>
            </Position>
            <AltitudeMeters>36.1867676</AltitudeMeters>
            <DistanceMeters>0.0629519</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>148</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:12Z</Time>
            <Position>
              <LatitudeDegrees>40.7780136</LatitudeDegrees>
              <LongitudeDegrees>-73.9665778</LongitudeDegrees>
            </Position>
            <AltitudeMeters>35.2254639</AltitudeMeters>
            <DistanceMeters>0.1698548</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>148</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:17Z</Time>
            <Position>
              <LatitudeDegrees>40.7780147</LatitudeDegrees>
              <LongitudeDegrees>-73.9665789</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.2641602</AltitudeMeters>
            <DistanceMeters>0.5907414</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>152</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:24Z</Time>
            <Position>
              <LatitudeDegrees>40.7780246</LatitudeDegrees>
              <LongitudeDegrees>-73.9665919</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.7448730</AltitudeMeters>
            <DistanceMeters>1.9415363</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>147</Value>
            </HeartRateBpm>
            <SensorState>Absent</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:25Z</Time>
            <Position>
              <LatitudeDegrees>40.7780338</LatitudeDegrees>
              <LongitudeDegrees>-73.9665851</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.7448730</AltitudeMeters>
            <DistanceMeters>1.9993043</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>147</Value>
            </HeartRateBpm>
            <SensorState>Present</SensorState>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:28Z</Time>
            <Position>
              <LatitudeDegrees>40.7780800</LatitudeDegrees>
              <LongitudeDegrees>-73.9665492</LongitudeDegrees>
            </Position>
            <AltitudeMeters>34.2641602</AltitudeMeters>
            <DistanceMeters>7.9581327</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>148</Value>
            </HeartRateBpm>
            <Cadence>1</Cadence>
            <SensorState>Present</SensorState>
            <Extensions>
              <TPX xmlns="http://www.garmin.com/xmlschemas/ActivityExtension/v2" CadenceSensor="Bike"/>
            </Extensions>
          </Trackpoint>
          <Trackpoint>
            <Time>2010-06-26T10:06:30Z</Time>
            <Position>
              <LatitudeDegrees>40.7781448</LatitudeDegrees>
              <LongitudeDegrees>-73.9665005</LongitudeDegrees>
            </Position>
            <AltitudeMeters>32.8222656</AltitudeMeters>
            <DistanceMeters>15.3775177</DistanceMeters>
            <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
              <Value>151</Value>
            </HeartRateBpm>
            <Cadence>42</Cadence>
            <SensorState>Present</SensorState>
            <Extensions>
              <TPX xmlns="http://www.garmin.com/xmlschemas/ActivityExtension/v2" CadenceSensor="Bike"/>
            </Extensions>
          </Trackpoint>
        </Track>
      </Lap>
    </Activity>
  </Activities>

</TrainingCenterDatabase>

output

-- Biking --
Time: 2010-06-26T10:06:11Z, HR Value: 148
Time: 2010-06-26T10:06:12Z, HR Value: 148
Time: 2010-06-26T10:06:17Z, HR Value: 152
Time: 2010-06-26T10:06:24Z, HR Value: 147
Time: 2010-06-26T10:06:25Z, HR Value: 147
Time: 2010-06-26T10:06:28Z, HR Value: 148
Time: 2010-06-26T10:06:30Z, HR Value: 151


问:
right to left scrollbar at the bottom of the table html
In the following fiddle I create a table where I need it to be right to left.
Everything is fine except that the scrollbar at the bottom  of the table initially is in the left of the page and so the user can not see the first column.

FiddleDemo

How can I set the initial position of the scrollbar to be in the right and I can see the first column.

The following is the code in the fiddle link.

HTML

```<code><table>
    <tr>
        <th>RTL Header 1</th>
        <th>RTL Header 2</th>
        <th>RTL Header 3</th>
        <th>RTL Header 4</th>
        <th>RTL Header 5</th>
        <th>RTL Header 6</th>
        <th>RTL Header 7</th>
        <th>RTL Header 8</th>
        <th>RTL Header 9</th>
        <th>RTL Header 10</th>
        <th>RTL Header 11</th>
        <th>RTL Header 12</th>
        <th>RTL Header 13</th>
        <th>RTL Header 14</th>
    </tr>
    <tr>
        <td>RTL Content 1</td>
        <td>RTL Content 2</td>
        <td>RTL Content 3</td>
        <td>RTL Content 4</td>
        <td>RTL Content 5</td>
        <td>RTL Content 6</td>
        <td>RTL Content 7</td>
        <td>RTL Content 8</td>
        <td>RTL Content 9</td>
        <td>RTL Content 10</td>
        <td>RTL Content 11</td>
        <td>RTL Content 12</td>
        <td>RTL Content 13</td>
        <td>RTL Content 14</td>
    </tr>
</table>
</code>```

CSS

```<code>table {
  direction: rtl;
  font-family: Vazir;
  border-collapse: collapse;
  width: 100%;
}

th {
  direction: rtl;
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
}
td{
    direction: rtl;
    width: 100%;
    border: 1px solid #848080;
    text-align: center;
    padding: 8px;
    white-space: nowrap;
}
td:last-child{
    width:100%;
}
th:last-child{
    width:100%;
}
tr:nth-child(even) {
  background-color: #dddddd;
}
</code>```

答:
Use the scrollIntoView method on the last cell of the table as

```<code>document.getElementById("last").scrollIntoView();
</code>```

Where last is the id given to your last table cell as

```<code><th id="last">RTL Header 1</th>
</code>```

Body:
In the following fiddle I create a table where I need it to be right to left.
Everything is fine except that the scrollbar at the bottom  of the table initially is in the left of the page and so the user can not see the first column.

FiddleDemo

How can I set the initial position of the scrollbar to be in the right and I can see the first column.

The following is the code in the fiddle link.

HTML

        RTL Header 1
        RTL Header 2
        RTL Header 3
        RTL Header 4
        RTL Header 5
        RTL Header 6
        RTL Header 7
        RTL Header 8
        RTL Header 9
        RTL Header 10
        RTL Header 11
        RTL Header 12
        RTL Header 13
        RTL Header 14

        RTL Content 1
        RTL Content 2
        RTL Content 3
        RTL Content 4
        RTL Content 5
        RTL Content 6
        RTL Content 7
        RTL Content 8
        RTL Content 9
        RTL Content 10
        RTL Content 11
        RTL Content 12
        RTL Content 13
        RTL Content 14

CSS

table {
  direction: rtl;
  font-family: Vazir;
  border-collapse: collapse;
  width: 100%;
}

th {
  direction: rtl;
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
}
td{
    direction: rtl;
    width: 100%;
    border: 1px solid #848080;
    text-align: center;
    padding: 8px;
    white-space: nowrap;
}
td:last-child{
    width:100%;
}
th:last-child{
    width:100%;
}
tr:nth-child(even) {
  background-color: #dddddd;
}

Body:
Use the scrollIntoView method on the last cell of the table as

document.getElementById("last").scrollIntoView();

Where last is the id given to your last table cell as

<th id="last">RTL Header 1</th>


问:
C++ unordered_map self defined hash function collision
Below code is for counting number of lines in a plane for different slope value. It is recommended to use a pair of x-axis and y-axis positions to denote the slope of line, b/c directly calculating the division y / x will have float precision issue. All x and y positions are integers.

Although Method I is working in test code, there are still something unclear to me:

1) For method I, pair {5, 3} and {3, 5} will have the same hash value (x ^ y), but these two lines have different slope! Why does not it cause the problem of considering both lines the same slope? Or the hash function value only determines the slot to be hashed, while comparing the equivalence of actual pair value determines whether to count them as equal?

2) Since the pair {5, 3} and {3, 5} will be hashed into the same slot, and there are lots of other similar collisions like {a, b} and {b, a}. Why does the collision hash table still produces correct final result?

3) XOR for negative integers is fine, right? Is there a better hash function we usually use here to avoid high collision?

```<code>struct hashfunc
{
    //Method I:
    size_t operator() (const pair<int,int>& l) const
    { return l.first ^ l.second; }

    //Method II is WRONG: can NOT left shift negative int!!
    size_t operator() (const pair<int, int>& l) const {
         return l.first << 32 | l.second;
    }
};

unordered_map< pair< int,int >, int, hashfunc> lines;
</code>```

答:
Complete absence of collisions is not achievable in any function whose output is smaller than the combined inputs. Correctness does not depend on lack of collisions, only perfomance does. You should get the correct results even with a hash function that returns zero all the time (try it).

the hash function value only determines the slot to be hashed, while
  comparing the equivalence of actual pair value determines whether to
  count them as equal?

Correct.

The usual method is to mash the numbers together in an unpredictable way, like

```<code>choose distinct primes a,b,c
hash(x,y) = (a*x + b*y) % c
</code>```

see e.g. https://en.wikipedia.org/wiki/Universal_hashing#Hashing_integers

Body:
Below code is for counting number of lines in a plane for different slope value. It is recommended to use a pair of x-axis and y-axis positions to denote the slope of line, b/c directly calculating the division y / x will have float precision issue. All x and y positions are integers.

Although Method I is working in test code, there are still something unclear to me:

1) For method I, pair {5, 3} and {3, 5} will have the same hash value (x ^ y), but these two lines have different slope! Why does not it cause the problem of considering both lines the same slope? Or the hash function value only determines the slot to be hashed, while comparing the equivalence of actual pair value determines whether to count them as equal?

2) Since the pair {5, 3} and {3, 5} will be hashed into the same slot, and there are lots of other similar collisions like {a, b} and {b, a}. Why does the collision hash table still produces correct final result?

3) XOR for negative integers is fine, right? Is there a better hash function we usually use here to avoid high collision?

struct hashfunc
{
    //Method I:
    size_t operator() (const pair<int,int>& l) const
    { return l.first ^ l.second; }

    //Method II is WRONG: can NOT left shift negative int!!
    size_t operator() (const pair<int, int>& l) const {
         return l.first << 32 | l.second;
    }
};

unordered_map< pair< int,int >, int, hashfunc> lines;

Body:
Complete absence of collisions is not achievable in any function whose output is smaller than the combined inputs. Correctness does not depend on lack of collisions, only perfomance does. You should get the correct results even with a hash function that returns zero all the time (try it).

the hash function value only determines the slot to be hashed, while
  comparing the equivalence of actual pair value determines whether to
  count them as equal?

Correct.

The usual method is to mash the numbers together in an unpredictable way, like

choose distinct primes a,b,c
hash(x,y) = (a*x + b*y) % c

see e.g. https://en.wikipedia.org/wiki/Universal_hashing#Hashing_integers


问:
RecyclerView does not update after removing an item
I have a RecyclerView horizontal image slider at the bottom of a fragment. The top of the fragment shows some details. Once the user clicks on the images at the bottom, the idea is to remove that image from the image slider and display its information in the fragment. Now the information shows up but the image does not gets removed from the RecyclerView. Here is what I have coded in the Onclick of the outermost layout. I have tried all the related answers that I could find but nothing worked. They all are in the code. Please let me know what am I doing wrong or what is missing.

```<code>holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (isFiltering) {
                mItemList.clear();
                mItemList.addAll(mOriginalItemList);
                mItemList.remove(position);// At this point mItemList holds the correct. That is all the images but not the one that was clicked.

                notifyItemRemoved(position); //solution 1
                notifyItemRangeRemoved(position, getItemCount()); // solution 2
                notifyItemRangeRemoved(0, getItemCount()); // solution 3
                notifyDataSetChanged();//solution 4
            }
        }
    });
</code>```

Full Code of the adapter

```<code>public class ImageGallery16X9Adapter<T extends GalleryItem> extends RecyclerView.Adapter<ImageGallery16X9Adapter.GalleryItemViewHolder> {

public enum GalleryMode {
    All_SAME,
    FIRST_DIFFERENT
}

private Context mContext;
private BasePresenter mPresenter;
private List<T> mItemList;
private List<T> mOriginalItemList;
private GalleryItem mFirstItem;
private GalleryMode mGalleryMode;
private int deviceWidth, itemWidth, marginSingle, marginDouble;
private boolean isFiltering;

public ImageGallery16X9Adapter(Context context, BasePresenter presenter, GalleryMode galleryMode, List<T> itemList, GalleryItem firstItem, boolean isFiltering) {
    mContext = context;
    mPresenter = presenter;
    mGalleryMode = galleryMode;
    mItemList = new ArrayList<>(itemList);
    mOriginalItemList = new ArrayList<>(itemList);
    mFirstItem = firstItem;
    deviceWidth = CommonUtils.getDeviceWidth((Activity) mContext);
    itemWidth = (int) (deviceWidth * 0.9);
    marginDouble = (int) (deviceWidth * 0.05);
    marginSingle = (int) (deviceWidth * 0.025);
    this.isFiltering = isFiltering;
}

@Override
public GalleryItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new GalleryItemViewHolder(LayoutInflater.from(parent.getContext()).
            inflate(R.layout.row_image_gallery_16x9_item, parent, false));
}

@Override
public void onBindViewHolder(GalleryItemViewHolder holder, final int position) {
    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemRowRelativeLayout.getLayoutParams();
    RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) holder.itemImageView.getLayoutParams();
    layoutParams.width = itemWidth;
    rlParams.height = (int) (layoutParams.width * Constant.HEIGHT_FACTOR_16X9);

    if (position == 0) {
        layoutParams.leftMargin = marginDouble;
        layoutParams.rightMargin = 0;
        if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) {
            holder.itemTitle.setVisibility(View.VISIBLE);
            holder.itemTitle.setText(mFirstItem.getItemTitle());
            if (mFirstItem.getItemImage() != null) {
                Picasso.with(MyApplication.getAppContext()).load(mFirstItem.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView);
            } else {
                Picasso.with(MyApplication.getAppContext()).load(R.drawable.error_image).placeholder(R.drawable.error_image).error(R.drawable.error_image).fit().into(holder.itemImageView);
            }
            holder.itemDescription.setText(mFirstItem.getItemDescription());
        }
    } else {
        if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) {
            if (position == mItemList.size()) {
                layoutParams.rightMargin = marginDouble;
            } else {
                layoutParams.rightMargin = 0;
            }
        } else {
            if (position == mItemList.size() - 1) {
                layoutParams.rightMargin = marginDouble;
            } else {
                layoutParams.rightMargin = 0;
            }
        }
        layoutParams.leftMargin = marginSingle;
    }

    int itemPosition = position;
    if (mGalleryMode == GalleryMode.FIRST_DIFFERENT && position > 0) {
        itemPosition = position - 1;
        T item = mItemList.get(itemPosition);
        holder.itemTitle.setVisibility(View.GONE);
        holder.itemDescription.setText(item.getItemDescription());
        Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView);

    } else if (mGalleryMode == GalleryMode.All_SAME) {
        T item = mItemList.get(itemPosition);
        holder.itemTitle.setVisibility(View.GONE);
        holder.itemDescription.setText(item.getItemDescription());
        Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView);
    }

    holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) {
                if (position == 0) {
                    mPresenter.onItemClicked(mFirstItem);
                } else {
                    mPresenter.onItemClicked(mItemList.get(position - 1));
                }
            } else {
                mPresenter.onItemClicked(mItemList.get(position));
                if (isFiltering) {
                    mItemList.clear();
                    mItemList.addAll(mOriginalItemList);
                    mItemList.remove(position);

                    notifyItemRemoved(position); //solution 1
                    notifyItemRangeRemoved(position, getItemCount()); // solution 2
                    notifyItemRangeRemoved(0, getItemCount()); // solution 3
                    notifyDataSetChanged();//solution 4
                }
            }
        }
    });
}

@Override
public int getItemCount() {
    if (mGalleryMode == GalleryMode.FIRST_DIFFERENT)
        return mItemList.size() + 1;
    else
        return mItemList.size();
}

static class GalleryItemViewHolder extends RecyclerView.ViewHolder {
    private final TextView itemDescription, itemTitle;
    private final ImageView itemImageView, itemFavoriteImageView;
    private final RelativeLayout itemRowRelativeLayout;

    public GalleryItemViewHolder(View itemView) {
        super(itemView);
        itemRowRelativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl_gallery_item_row);
        itemImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item);
        itemFavoriteImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item_favorite);
        itemTitle = (TextView) itemView.findViewById(R.id.txt_gallery_item_name);
        itemDescription = (TextView) itemView.findViewById(R.id.txt_gallery_item_description);
    }
}
</code>```

}

答:
Declare a method in your custom RecylerView.Adapter like below:

```<code>public void deleteData(int position) {
    recordingItems.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, recordingItems.size());
}
</code>```

and from MainActivity call:

```<code>adapter.deleteData(position);
</code>```

Body:
I have a RecyclerView horizontal image slider at the bottom of a fragment. The top of the fragment shows some details. Once the user clicks on the images at the bottom, the idea is to remove that image from the image slider and display its information in the fragment. Now the information shows up but the image does not gets removed from the RecyclerView. Here is what I have coded in the Onclick of the outermost layout. I have tried all the related answers that I could find but nothing worked. They all are in the code. Please let me know what am I doing wrong or what is missing.

holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (isFiltering) {
                mItemList.clear();
                mItemList.addAll(mOriginalItemList);
                mItemList.remove(position);// At this point mItemList holds the correct. That is all the images but not the one that was clicked.

                notifyItemRemoved(position); //solution 1
                notifyItemRangeRemoved(position, getItemCount()); // solution 2
                notifyItemRangeRemoved(0, getItemCount()); // solution 3
                notifyDataSetChanged();//solution 4
            }
        }
    });

Full Code of the adapter

public class ImageGallery16X9Adapter<T extends GalleryItem> extends RecyclerView.Adapter<ImageGallery16X9Adapter.GalleryItemViewHolder> {

public enum GalleryMode {
    All_SAME,
    FIRST_DIFFERENT
}

private Context mContext;
private BasePresenter mPresenter;
private List<T> mItemList;
private List<T> mOriginalItemList;
private GalleryItem mFirstItem;
private GalleryMode mGalleryMode;
private int deviceWidth, itemWidth, marginSingle, marginDouble;
private boolean isFiltering;

public ImageGallery16X9Adapter(Context context, BasePresenter presenter, GalleryMode galleryMode, List<T> itemList, GalleryItem firstItem, boolean isFiltering) {
    mContext = context;
    mPresenter = presenter;
    mGalleryMode = galleryMode;
    mItemList = new ArrayList<>(itemList);
    mOriginalItemList = new ArrayList<>(itemList);
    mFirstItem = firstItem;
    deviceWidth = CommonUtils.getDeviceWidth((Activity) mContext);
    itemWidth = (int) (deviceWidth * 0.9);
    marginDouble = (int) (deviceWidth * 0.05);
    marginSingle = (int) (deviceWidth * 0.025);
    this.isFiltering = isFiltering;
}

@Override
public GalleryItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new GalleryItemViewHolder(LayoutInflater.from(parent.getContext()).
            inflate(R.layout.row_image_gallery_16x9_item, parent, false));
}

@Override
public void onBindViewHolder(GalleryItemViewHolder holder, final int position) {
    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemRowRelativeLayout.getLayoutParams();
    RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) holder.itemImageView.getLayoutParams();
    layoutParams.width = itemWidth;
    rlParams.height = (int) (layoutParams.width * Constant.HEIGHT_FACTOR_16X9);

    if (position == 0) {
        layoutParams.leftMargin = marginDouble;
        layoutParams.rightMargin = 0;
        if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) {
            holder.itemTitle.setVisibility(View.VISIBLE);
            holder.itemTitle.setText(mFirstItem.getItemTitle());
            if (mFirstItem.getItemImage() != null) {
                Picasso.with(MyApplication.getAppContext()).load(mFirstItem.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView);
            } else {
                Picasso.with(MyApplication.getAppContext()).load(R.drawable.error_image).placeholder(R.drawable.error_image).error(R.drawable.error_image).fit().into(holder.itemImageView);
            }
            holder.itemDescription.setText(mFirstItem.getItemDescription());
        }
    } else {
        if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) {
            if (position == mItemList.size()) {
                layoutParams.rightMargin = marginDouble;
            } else {
                layoutParams.rightMargin = 0;
            }
        } else {
            if (position == mItemList.size() - 1) {
                layoutParams.rightMargin = marginDouble;
            } else {
                layoutParams.rightMargin = 0;
            }
        }
        layoutParams.leftMargin = marginSingle;
    }

    int itemPosition = position;
    if (mGalleryMode == GalleryMode.FIRST_DIFFERENT && position > 0) {
        itemPosition = position - 1;
        T item = mItemList.get(itemPosition);
        holder.itemTitle.setVisibility(View.GONE);
        holder.itemDescription.setText(item.getItemDescription());
        Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView);

    } else if (mGalleryMode == GalleryMode.All_SAME) {
        T item = mItemList.get(itemPosition);
        holder.itemTitle.setVisibility(View.GONE);
        holder.itemDescription.setText(item.getItemDescription());
        Picasso.with(mContext).load(item.getItemImage()).fit().placeholder(R.drawable.error_image).error(R.drawable.error_image).into(holder.itemImageView);
    }

    holder.itemRowRelativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mGalleryMode == GalleryMode.FIRST_DIFFERENT) {
                if (position == 0) {
                    mPresenter.onItemClicked(mFirstItem);
                } else {
                    mPresenter.onItemClicked(mItemList.get(position - 1));
                }
            } else {
                mPresenter.onItemClicked(mItemList.get(position));
                if (isFiltering) {
                    mItemList.clear();
                    mItemList.addAll(mOriginalItemList);
                    mItemList.remove(position);

                    notifyItemRemoved(position); //solution 1
                    notifyItemRangeRemoved(position, getItemCount()); // solution 2
                    notifyItemRangeRemoved(0, getItemCount()); // solution 3
                    notifyDataSetChanged();//solution 4
                }
            }
        }
    });
}

@Override
public int getItemCount() {
    if (mGalleryMode == GalleryMode.FIRST_DIFFERENT)
        return mItemList.size() + 1;
    else
        return mItemList.size();
}

static class GalleryItemViewHolder extends RecyclerView.ViewHolder {
    private final TextView itemDescription, itemTitle;
    private final ImageView itemImageView, itemFavoriteImageView;
    private final RelativeLayout itemRowRelativeLayout;

    public GalleryItemViewHolder(View itemView) {
        super(itemView);
        itemRowRelativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl_gallery_item_row);
        itemImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item);
        itemFavoriteImageView = (ImageView) itemView.findViewById(R.id.img_gallery_item_favorite);
        itemTitle = (TextView) itemView.findViewById(R.id.txt_gallery_item_name);
        itemDescription = (TextView) itemView.findViewById(R.id.txt_gallery_item_description);
    }
}

}

Body:
Declare a method in your custom RecylerView.Adapter like below:

public void deleteData(int position) {
    recordingItems.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, recordingItems.size());
}

and from MainActivity call:

adapter.deleteData(position);


问:
().jexcel not a function
I would like to ask why the console always prompt that "TypeError: $(...).jexcel is not a function" when i try to convert the data of the table in jexcel plugin into JSON.
Here's my code:

```<code>  <a class="btn btn-info" id="showWidth" >Import Excel</a>
    <a class="btn btn-success" id="uploadOTexc">Upload OT's</a>
    <br>
    <br>
    <div class="widget widget-table action-table">
        <div class="widget-header">
            <i class="icon-th-list"></i>
            <h3>OT's</h3>
        </div>
        <div class="widget-content" id="totalwidth">

            <div id="xcls" class="table table-striped table-border">
            </div>
        </div>
        @*<textarea id='txt' style='width:400px;height:120px'></textarea>*@
    </div>
    <script type="text/javascript">
        var dynWidth = 227.2
        var data = [];
        for (var i = 0; i < 15; i++)
        {
            data.push({
                id: '',
                date: '',
                start: '',
                end: '',
                reason: '',
            })
        }

        $('#xcls').jexcel({
            data: data,
            colHeaders: ['EMPLOYEE ID', 'DATE APPLY', 'START TIME', 'END TIME', 'REASON'],
            colWidths: [195, dynWidth, dynWidth, dynWidth, dynWidth],
            //minDimensions:[10,5],
            columns: [
                { type: 'text' },
                 { type: 'text' },
                { type: 'text' },
                { type: 'text' },
                { type: 'text' },
            ]
        });

        $('#uploadOTexc').on('click', function ()
        {
            var data = $('#xcls').jexcel("getData");
        });
    </script>
</code>```

by the way I use a jexcel plugin from bossanova.
Thanks,

答: The javascript file is not loaded when you execute the script.</p>

Title: ().jexcel not a function

Body:
I would like to ask why the console always prompt that "TypeError: $(...).jexcel is not a function" when i try to convert the data of the table in jexcel plugin into JSON.
Here's my code:

  Import Excel
    Upload OT's

OT's

        @*<textarea id='txt' style='width:400px;height:120px'></textarea>*@

by the way I use a jexcel plugin from bossanova.
Thanks,


问:
Trying to parse logfile based on start and end time
I am trying to parse large zipped logfile and would like to collect all matching parameters within a certain time range:

Wed Nov  3 09:27:20 2010 : remote IP address 209.151.64.18
Wed Nov  3 11:57:22 2010 : secondary DNS address 204.117.214.10

I am able to grep other parameter using the line below:
gzcat  jfk-gw10-asr1.20100408.log.gz | egrep gabriel|98.126.209.144\|13.244.137.58\|16.151.65.121

I have been unable to parse for the start time and/or end time.
Any assistance is greatly appreciated.

答:
Assuming that the log file is chronologically sorted you could do e.g.:

```<code>gzcat jfk-gw10-asr1.20100408.log.gz | sed -n '/Nov 3 09:/,/Nov 3 11:/p'
</code>```

to get log entries between 09:00:00 and 11:59:59 on Nov, 3rd.

Body:
Assuming that the log file is chronologically sorted you could do e.g.:

gzcat jfk-gw10-asr1.20100408.log.gz | sed -n '/Nov 3 09:/,/Nov 3 11:/p'

to get log entries between 09:00:00 and 11:59:59 on Nov, 3rd.


问:
React app does not start server with npm start
I created a new react app using CRA. As soon as I started the development server, it throws the error and exits.

```<code>Starting the development server...

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: spawn cmd ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! cart-redux@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cart-redux@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logg
ing output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HP\AppData\Roaming\npm-cache\_logs\2019-05-26T09_32_50_014Z
-debug.log
</code>```

The react-scripts version 3.0.1 is avoiding to 'npm start'. I tried downgrading to version 2.1.8, it works fine. But I don't want to downgrade the version everytime to make my app work.
I tried following the similar case, but it didn't help.
Any one else facing the issue, please help to resolve it.

答:
if you tried this and it didn't work for you then this maybe a react-scripts issue so to fix it try this:

```<code>remove node_modules and lock files
edit package.json so the version of react-scripts is "2.1.8"
npm install
npm start
</code>```

LTK how that goes

Body:
I created a new react app using CRA. As soon as I started the development server, it throws the error and exits.

Starting the development server...

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: spawn cmd ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! cart-redux@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cart-redux@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logg
ing output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HP\AppData\Roaming\npm-cache\_logs\2019-05-26T09_32_50_014Z
-debug.log

The react-scripts version 3.0.1 is avoiding to 'npm start'. I tried downgrading to version 2.1.8, it works fine. But I don't want to downgrade the version everytime to make my app work.
I tried following the similar case, but it didn't help.
Any one else facing the issue, please help to resolve it.

Body:
if you tried this and it didn't work for you then this maybe a react-scripts issue so to fix it try this:

remove node_modules and lock files
edit package.json so the version of react-scripts is "2.1.8"
npm install
npm start

LTK how that goes


问:
PWA with ionic and capacitor, native plugin complains cordova not available, on browser and device
I am developing a PWA with ionic 4.12 and Capacitor, I  would like to use the native plugin ImagePicker; I followed this guide https://ionicframework.com/docs/native/image-picker, when I run imagePicker.getPicture, get this error "cordova not available" both on browser and on the device, I do not know how to make working the plugin, thanks in advance.</p>

答:
Cordova plugins are not supported on PWAs yet

https://github.com/ionic-team/capacitor/issues/769


问:
Keras: How to use a generator with variable input sizes
I have a large dataset and heavy augmentions, thus I rely onthe keras.utils.Sequence generator and let Keras do the multiprocessing. So, using the simple model.fit(...) command is no option for me, when it comes to having a variable input size. Furthermore, due to my specific problem it is not a good idea to resize or pad the images.

Also chosing a batch-size of 1 is not very handy, because of BatchNormalization Layers.

I have variable image sizes, and created a toy example of my problem:

```<code>from keras.applications.vgg16 import VGG16 as model
from keras.utils import Sequence
import numpy as np
from keras.layers import Input, Flatten, Dense, GlobalAveragePooling2D
from keras.models import Model

CLASSES = 10
class ExampleGenerator(Sequence):

    def __init__(self,dataset_length=100,batch_size=8):
        self.dataset_length = dataset_length
        self.batch_size = batch_size

    def __len__(self):
        return int(np.ceil(self.dataset_length / float(self.batch_size)))

    def __getitem__(self,idx):

        # create random targets
        Y_batch = np.random.randint(0,2,size=(self.batch_size,CLASSES))
        X = []

        for i in range(self.batch_size):

            # create a random image with a random size

            width = np.random.randint(64,256)
            height = np.random.randint(64,256)
            img = np.random.rand(width,height,3)
            X.append(img)

        X_batch = np.array(X)
        return X_batch,Y_batch

gen = ExampleGenerator()
input_tensor = Input(shape=(None, None, 3))

base_model = model(input_tensor=input_tensor,weights=None, include_top=False)

output = base_model.output

x = GlobalAveragePooling2D()(output)
x = Dense(512)(x)
predictions = Dense(CLASSES)(x)

model = Model(inputs=base_model.input, outputs=predictions)

model.compile(optimizer='adam', loss='categorical_crossentropy')

model.fit_generator(gen)
</code>```

Note that this example is only for the purpose of recreating my problem.

The followng error message will be prompted if the script is executed:

ValueError: Error when checking input: expected input_2 to have 4
  dimensions, but got array with shape (8, 1)

which of course is due to the numpy arry returned by __getitem__ with only the batch_size as a fixed size.

When the list X is not convert to a numpy array different error occurs:

ValueError: Error when checking model input: the list of Numpy arrays
  that you are passing to your model is not the size the model expected.
  Expected to see 1 array(s), but instead got the following list of 8
  arrays:

So, how can I have a variable input size with a keras generator?

Thank you for your help

答: You cannot use a batch_size greater than 1 for variable size images. If you're using variable size images and you want to send in a batch size greater than one then you should fix the dimensions for the input of the model and add some padding to reach that fixed size in you generator. </p>

Body:
I have a large dataset and heavy augmentions, thus I rely onthe keras.utils.Sequence generator and let Keras do the multiprocessing. So, using the simple model.fit(...) command is no option for me, when it comes to having a variable input size. Furthermore, due to my specific problem it is not a good idea to resize or pad the images.

Also chosing a batch-size of 1 is not very handy, because of BatchNormalization Layers.

I have variable image sizes, and created a toy example of my problem:

from keras.applications.vgg16 import VGG16 as model
from keras.utils import Sequence
import numpy as np
from keras.layers import Input, Flatten, Dense, GlobalAveragePooling2D
from keras.models import Model

CLASSES = 10
class ExampleGenerator(Sequence):

    def __init__(self,dataset_length=100,batch_size=8):
        self.dataset_length = dataset_length
        self.batch_size = batch_size

    def __len__(self):
        return int(np.ceil(self.dataset_length / float(self.batch_size)))

    def __getitem__(self,idx):

        # create random targets
        Y_batch = np.random.randint(0,2,size=(self.batch_size,CLASSES))
        X = []

        for i in range(self.batch_size):

            # create a random image with a random size

            width = np.random.randint(64,256)
            height = np.random.randint(64,256)
            img = np.random.rand(width,height,3)
            X.append(img)

        X_batch = np.array(X)
        return X_batch,Y_batch

gen = ExampleGenerator()
input_tensor = Input(shape=(None, None, 3))

base_model = model(input_tensor=input_tensor,weights=None, include_top=False)

output = base_model.output

x = GlobalAveragePooling2D()(output)
x = Dense(512)(x)
predictions = Dense(CLASSES)(x)

model = Model(inputs=base_model.input, outputs=predictions)

model.compile(optimizer='adam', loss='categorical_crossentropy')

model.fit_generator(gen)

Note that this example is only for the purpose of recreating my problem.

The followng error message will be prompted if the script is executed:

ValueError: Error when checking input: expected input_2 to have 4
  dimensions, but got array with shape (8, 1)

which of course is due to the numpy arry returned by __getitem__ with only the batch_size as a fixed size.

When the list X is not convert to a numpy array different error occurs:

ValueError: Error when checking model input: the list of Numpy arrays
  that you are passing to your model is not the size the model expected.
  Expected to see 1 array(s), but instead got the following list of 8
  arrays:

So, how can I have a variable input size with a keras generator?

Thank you for your help


问:
I write a code for a saving dataframe, but it works incorrectly
Group observations into a table by type (mode) and save the result dataframes, with every type in separate CSV file (there are four types: beach, boat, charter, pier), which should produce a total of four different csv files.

```<code>for value in set(df['mode']):
    df[df['mode'] == value].to_csv('df_beach_'+str(value)+'.csv', index = False)
</code>```

I understand that in the end something should turn out like this:

```<code>mode
beach 35.213412
boat 41.2341
charter 75.213412
pier 30.02384
name: price, dtype: float64
</code>```

答:
Generate a list of df['mode'] only unique values:

```<code>l = list(set(df['mode'].tolist()))
</code>```

Then run:

```<code>for value in l:
    df.loc[df['mode'] == value].to_csv('df_beach_'+str(value)+'.csv', index = False)
</code>```

or

```<code>for value in l:
    df1 = df.loc[df['mode']==value]
    df1.to_csv('df_beach_'+str(value)+'.csv', index = False)
</code>```

Should give the required csv's.

Body:
Group observations into a table by type (mode) and save the result dataframes, with every type in separate CSV file (there are four types: beach, boat, charter, pier), which should produce a total of four different csv files.

for value in set(df['mode']):
    df[df['mode'] == value].to_csv('df_beach_'+str(value)+'.csv', index = False)

I understand that in the end something should turn out like this:

mode
beach 35.213412
boat 41.2341
charter 75.213412
pier 30.02384
name: price, dtype: float64

Body:
Generate a list of df['mode'] only unique values:

l = list(set(df['mode'].tolist()))

Then run:

for value in l:
    df.loc[df['mode'] == value].to_csv('df_beach_'+str(value)+'.csv', index = False)

or

for value in l:
    df1 = df.loc[df['mode']==value]
    df1.to_csv('df_beach_'+str(value)+'.csv', index = False)

Should give the required csv's.


问:
Why does Java allow only a single method X when implementing 2 interfaces that both declare X but which differ in their throws clauses?
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

```<code>import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}
</code>```

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.

答:
By using generic names you have effectively tried to combine two unrelated methods.  One method performs IO operations, the other does not appear to or must handle those errors it self.  You have to decide which one it is and what the method should really be doing.

One hint you have confusion is that you have two interfaces, but you don't use them anywhere. i.e. you could delete them and your main() would compile just fine.

Body:
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.