问:
Use Dagger2 Android Injection Support without specifying the class name
Is there a way in Dagger2 or in Dagger2 Android Injection support to inject the member instances without specifying the class names of the fragments.

I have a modular project where

The following line is asking to provide a binder Factory for the injectable class.

```<code>    @Override
    public void onAttach(Context context) {
      AndroidSupportInjection.inject(this);
      super.onAttach(context);
    }
</code>```

But my intention is to provide the injecting members through different modules in the project, where the I wouldn't need to specify the class name of the Fragment at all.

Is this possible in Dagger2 injection or not?

答:
Is there a way in Dagger2 or in Dagger2 Android Injection support to inject the member instances without specifying the class names of the fragments.

tl;dr No. You always need a component that contains a .inject(FragmentInQuestion fragment) method for every Fragment you want to inject.

Dagger uses annotation processing at compile time to resolve all of your .inject(SomeFragment fragment) methods where it looks up fields annotated with @Inject and creates code to inject them.

It needs the actual class name, since it will only generate code for the class used with its fields.

```<code>class Fragment {
  // no @Inject annotated fields, part of framework!
}

class SomeFragment extens Fragment {
  @Inject SomeDependency dep;
}
class OtherFragment extens Fragment {
  @Inject OtherDependency dep;
}
</code>```

Declaring one generic component that injects all your fragments is impossible.

.inject(Fragment fragment) would not inject any properties, since Fragment does not contain any @Inject annotated fields. So neither of the dep fields in the above sample would be provided and they both would be null.

You could create a BaseFragment that contains common objects and write an injection for it, but again, any annotated fields of its children would not be supplied.

You could try some other workarounds, but in the end it would always mean that you'd be injecting or be working with a base type. While this might be feasible in some situations, I don't think it would work on more than some special edge cases.

The Android Injection part of Dagger 2 takes this approach and creates a generic interface that your components have to implement along with a Builder to bind the type in question.

```<code>interface AndroidInjector<T> {
  inject(T instance)
}
</code>```

By implementing this interface AndroidInjection can then look up (and create) the correct component and inject your Fragment. For the reasons mentioned above this will always be the actual class of your Fragment, and not some base type.

So by using the Android Injection part you won't be able to use some common base class, and even without it you'd have a hard time.

If you're looking for a way to move out the call of AndroidInjection.inject(this) to somewhere else you should look at the Google Android Architecture Components sample project where they use FragmentLifecycleCallbacks to inject the fragments globally at the right time.

Body:
Is there a way in Dagger2 or in Dagger2 Android Injection support to inject the member instances without specifying the class names of the fragments.

I have a modular project where

The following line is asking to provide a binder Factory for the injectable class.

    @Override
    public void onAttach(Context context) {
      AndroidSupportInjection.inject(this);
      super.onAttach(context);
    }

But my intention is to provide the injecting members through different modules in the project, where the I wouldn't need to specify the class name of the Fragment at all.

Is this possible in Dagger2 injection or not?

Body:
Is there a way in Dagger2 or in Dagger2 Android Injection support to inject the member instances without specifying the class names of the fragments.

tl;dr No. You always need a component that contains a .inject(FragmentInQuestion fragment) method for every Fragment you want to inject.

Dagger uses annotation processing at compile time to resolve all of your .inject(SomeFragment fragment) methods where it looks up fields annotated with @Inject and creates code to inject them.

It needs the actual class name, since it will only generate code for the class used with its fields.

class Fragment {
  // no @Inject annotated fields, part of framework!
}

class SomeFragment extens Fragment {
  @Inject SomeDependency dep;
}
class OtherFragment extens Fragment {
  @Inject OtherDependency dep;
}

Declaring one generic component that injects all your fragments is impossible.

.inject(Fragment fragment) would not inject any properties, since Fragment does not contain any @Inject annotated fields. So neither of the dep fields in the above sample would be provided and they both would be null.

You could create a BaseFragment that contains common objects and write an injection for it, but again, any annotated fields of its children would not be supplied.

You could try some other workarounds, but in the end it would always mean that you'd be injecting or be working with a base type. While this might be feasible in some situations, I don't think it would work on more than some special edge cases.

The Android Injection part of Dagger 2 takes this approach and creates a generic interface that your components have to implement along with a Builder to bind the type in question.

interface AndroidInjector<T> {
  inject(T instance)
}

By implementing this interface AndroidInjection can then look up (and create) the correct component and inject your Fragment. For the reasons mentioned above this will always be the actual class of your Fragment, and not some base type.

So by using the Android Injection part you won't be able to use some common base class, and even without it you'd have a hard time.

If you're looking for a way to move out the call of AndroidInjection.inject(this) to somewhere else you should look at the Google Android Architecture Components sample project where they use FragmentLifecycleCallbacks to inject the fragments globally at the right time.


来源: stackexchange

问:
ionic 3 image slider stops autoplay after manual sliding
Ionic 3 image slider autoplay works well, but when I slide the image manually the autoplay stops working. Below is my ionic 3 code. I am really stuck here..

```<code>    slideData = [{ image: "../../assets/img1.jpg" },{ image: "../../assets/img2.jpg" },{ image: "../../assets/img3.jpg" }]
</code>```

html code is as below

```<code>  <ion-slides  class="slide-css" autoplay="100" loop="true" speed="100" pager="true" autoplayDisableOnInteraction = "false">
  <ion-slide *ngFor="let slide of slideData">
  <img src="{{slide.image}}" />
  </ion-slide>
  </ion-slides>
</code>```

答:
Update:

You need to use it like this:

```<code>import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, Slides } from 'ionic-angular';

@ViewChild(Slides) slides: Slides;

constructor(private navCtrl: NavController, private navParams: NavParams) {
  }

  ionViewDidEnter() {
    this.slides.autoplayDisableOnInteraction = false;
  }
</code>```

Note: You need to remove autoplayDisableOnInteraction = "false" on html page.

Old Answer:

You can use autoplayDisableOnInteraction = "false" as shown below.

```<code>    <ion-slides  class="slide-css" autoplay="100" loop="true" speed="100"
                 pager="true" autoplayDisableOnInteraction = "false">

    </ion-slides>
</code>```

See how it implements on Ionic

Swiper API

disableOnInteraction  boolean true    Set to false and autoplay will not
  be disabled after user interactions (swipes), it will be restarted
  every time after interaction

ContentLicense: CC BY-SA 3.0

Body:
Ionic 3 image slider autoplay works well, but when I slide the image manually the autoplay stops working. Below is my ionic 3 code. I am really stuck here..

    slideData = [{ image: "../../assets/img1.jpg" },{ image: "../../assets/img2.jpg" },{ image: "../../assets/img3.jpg" }]

html code is as below

  <ion-slides  class="slide-css" autoplay="100" loop="true" speed="100" pager="true" autoplayDisableOnInteraction = "false">
  <ion-slide *ngFor="let slide of slideData">

  </ion-slide>
  </ion-slides>

Body:
Update:

You need to use it like this:

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, Slides } from 'ionic-angular';

@ViewChild(Slides) slides: Slides;

constructor(private navCtrl: NavController, private navParams: NavParams) {
  }

  ionViewDidEnter() {
    this.slides.autoplayDisableOnInteraction = false;
  }

Note: You need to remove autoplayDisableOnInteraction = "false" on html page.

Old Answer:

You can use autoplayDisableOnInteraction = "false" as shown below.

    <ion-slides  class="slide-css" autoplay="100" loop="true" speed="100"
                 pager="true" autoplayDisableOnInteraction = "false">

    </ion-slides>

See how it implements on Ionic

Swiper API

disableOnInteraction  boolean true    Set to false and autoplay will not
  be disabled after user interactions (swipes), it will be restarted
  every time after interaction


问:
Laravel and Remote Database Dropping
I have a Larvel 4.2 app running (Digital Ocean) and a remote database on Google Cloud SQL. (I know being on the same network would be better, but this is just the way it is for now) The database is mapped fine but about 1 in 20 page loads the app server doesn't connect to the database. Is there a way to "keep the connection alive" between the two, or maybe I'm missing something? Any help is always greatly appreciated. Thanks, folks! </p>

```<code>    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'xx.xxx.xx.xxx',
        'database'  => 'mydb',
        'username'  => 'user',
        'password'  => 'mypassword',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
</code>```

答:
What would be more helpful to find the solution, is to understand why the 1/20 loads fail? Does it display an error (e.g. too many connections or connection timeout)?

You can keep the connection alive by using persistent connections but without understanding the problem, it may perhaps aggravate it further (so use with caution).

Here's how to implement Peristent Connections:
In your database.php file, add the following line to your mysql connection:

'options' => [\PDO::ATTR_PERSISTENT => true]

For more info, check out this Laracasts response

Title: Laravel and Remote Database Dropping

Body:
I have a Larvel 4.2 app running (Digital Ocean) and a remote database on Google Cloud SQL. (I know being on the same network would be better, but this is just the way it is for now) The database is mapped fine but about 1 in 20 page loads the app server doesn't connect to the database. Is there a way to "keep the connection alive" between the two, or maybe I'm missing something? Any help is always greatly appreciated. Thanks, folks!

    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'xx.xxx.xx.xxx',
        'database'  => 'mydb',
        'username'  => 'user',
        'password'  => 'mypassword',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),


问:
Displaying notification messages in angular2 app failes
I want to implement notification messages for my simple angular 2 app. I decided to use ng2-toasty. My simple angular 2 app is based on ng2-admin theme.

I installed package
npm install ng2-toasty --save

Import and register ToastyModule in the AppModule

```<code>import { ToastyModule } from 'ng2-toasty';
...
 imports: [
    ToastyModule.forRoot(),
]
</code>```

3. Inside Component I import again Toast service and injected inside constructor

```<code>import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';
constructor(private toastyService: ToastyService) { }
...
// This error is raised on purpose inside some method
this.toastyService.error({
      title: 'Error',
      msg: 'An unexpected error occured!',
      theme: 'default',
      showClose: true,
      timeout: 2000
});
</code>```

Inside app.component.html
I added on top of the file

```<code><ng2-toasty [position="'top-right'"]></ng2-toasty>
</code>```

I don't get any errors inside console but still notification message is not shown.
  I've found several examples where I need to update systemjs.config.js or webpack.config.vendor.js files but inside this template I cannot find one. What I'm missing here?

答:
Usually when you are trying to import a new module to your app, you just declare it in your app module (or any other module you wish to use it) and then use it.

In your case, ng toasty runs as a service as well, so you will need to import it as a provider too. In your app module providers[] array, add:

```<code>providers: [ToastyService] // add ToastyService
</code>```

Body:
I want to implement notification messages for my simple angular 2 app. I decided to use ng2-toasty. My simple angular 2 app is based on ng2-admin theme.

I installed package
npm install ng2-toasty --save

Import and register ToastyModule in the AppModule

import { ToastyModule } from 'ng2-toasty';
...
 imports: [
    ToastyModule.forRoot(),
]

3. Inside Component I import again Toast service and injected inside constructor

import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';
constructor(private toastyService: ToastyService) { }
...
// This error is raised on purpose inside some method
this.toastyService.error({
      title: 'Error',
      msg: 'An unexpected error occured!',
      theme: 'default',
      showClose: true,
      timeout: 2000
});

Inside app.component.html
I added on top of the file

<ng2-toasty [position="'top-right'"]></ng2-toasty>

I don't get any errors inside console but still notification message is not shown.
  I've found several examples where I need to update systemjs.config.js or webpack.config.vendor.js files but inside this template I cannot find one. What I'm missing here?

Body:
Usually when you are trying to import a new module to your app, you just declare it in your app module (or any other module you wish to use it) and then use it.

In your case, ng toasty runs as a service as well, so you will need to import it as a provider too. In your app module providers[] array, add:

providers: [ToastyService] // add ToastyService


问:
Xamarin uitest fails to interact with accessibility label for IOS 11.0
Accessibility label of UIView is set to Eg "BackButton"
 [UIAccessibilityBackButtonElement] label: "BackButton"
Xamarin uitest for IOS 11.0 fails to interact with the label
app.Flash("BackButton")                                                     Flashing query for Marked("BackButton") gave 0 results.                         [                                                                                ]
I have tried waitForElement, Query methods, etc.Nothing seems to work.
Would be great if someone can help me.</p>

答:
It's weird but marked does not match labels. Here is the description per the method documentation.

Matches common values. For Android: An element with the given value as either id, contentDescription or text. For iOS: An element with the given value as either accessibilityLabel or accessibilityIdentifier.

You can find more info via the documentation here,
https://developer.xamarin.com/api/member/Xamarin.UITest.Queries.AppQuery.Marked/

Here is a post giving more info:
https://forums.xamarin.com/discussion/99701/not-able-to-query-label-text-with-property-label


问:
PHP Session string limit
Is there a length limit to a string that can be placed into $_SESSION with PHP?

Thanks

答:
The size of string is limited by the amount of memory available on the server. Whether that string can be successfully stored in a session would depend on the session storage mechanism in use.

If you're using the out-of-the-box file based session storage, then the it's likely you can write a file which is larger than the amount of available memory. If however you were using, say, memcache, then you might be more limited.

However, practically speaking, if you're storing so much in a session you have ask this question, you're probably abusing sessions!

Sessions should contain only that which you really want to have readily available for virtually every PHP request your application handles - typical examples would be a user name, user id or privilege level. When your app needs something bigger occasionally, it can go and grab it from another storage system.

ContentLicense: CC BY-SA 2.5

Title: PHP Session string limit


问:
Spring amqp is not raising timeout exception when the connection is blocked by RabbitMQ
When RabbitMQ disk usage or memory usage reaches the higher threshold RabbitMQ will block connection

In the spring amqp whenever rabbitMQ blocks the connection there is no error message about the connection failure

is there is any way to set timeout for a publish in spring amqp?

Thanks in advance

答:
Blocking connection listener is not enabled in Spring amqp by default, we need to add Blocked connection listener to the rabbitmq connection factory bean for getting blocked connection notification.

Following code will works :

```<code>connectionFactory.addConnectionListener(new ConnectionListener() {

    @Override
    public void onCreate(Connection connection) {
        Channel channel = connection.createChannel(false);
        channel.getConnection().addBlockedListener(new BlockedListener() {
            @Override
            public void handleUnblocked() throws IOException {

            }

            @Override
            public void handleBlocked(String reason) throws IOException {

            }
        });

        try {
            channel.close();
        }
        catch (IOException e) {

        }
    }

    @Override
    public void onClose(Connection connection) {

    }

});
</code>```

Reference

https://www.rabbitmq.com/connection-blocked.html

Spring AMQP: Register BlockedListener to Connection

Body:
Blocking connection listener is not enabled in Spring amqp by default, we need to add Blocked connection listener to the rabbitmq connection factory bean for getting blocked connection notification.

Following code will works :

connectionFactory.addConnectionListener(new ConnectionListener() {

    @Override
    public void onCreate(Connection connection) {
        Channel channel = connection.createChannel(false);
        channel.getConnection().addBlockedListener(new BlockedListener() {
            @Override
            public void handleUnblocked() throws IOException {

            }

            @Override
            public void handleBlocked(String reason) throws IOException {

            }
        });

        try {
            channel.close();
        }
        catch (IOException e) {

        }
    }

    @Override
    public void onClose(Connection connection) {

    }

});

Reference

https://www.rabbitmq.com/connection-blocked.html

Spring AMQP: Register BlockedListener to Connection

ContentLicense: CC BY-SA 4.0


问:
How import a function from another view with Django?
I have this folder hierarchy:

```<code>|---- saga
    |---- core
         |---- views.py
    |---- study_time
         |---- views.py
</code>```

On my study_time/views.py, I have this functions:

```<code>def study_time(request):
    def tasks_subjects(week_day, key):
        #Code here
        return __tasks

    def day_studies(week_day):
        __tasks_subjects = tasks_subjects(week_day, 0)
        #Code here
        return __studies

    return render(request, 'study_time.html', context)
</code>```

On my core/views.py, I need the day_studies() function, so I'm importing like this:

```<code>from saga.study_time.views import day_studies
    def home(request):
        day_progress = day_studies(datetime.date.today().isoweekday())
</code>```

But I'm getting the error:

ImportError: cannot import name 'day_studies'

How can I make this importation? I don't want to reply all code.

答:
The inner function is not accessible,because it is local code for that function only. It is not generic for all in the views.py . So make a distinction on this.

Go through this for better understanding!!
https://realpython.com/blog/python/inner-functions-what-are-they-good-for/

Happy coding!!

Body:
I have this folder hierarchy:

|---- saga
    |---- core
         |---- views.py
    |---- study_time
         |---- views.py

On my study_time/views.py, I have this functions:

def study_time(request):
    def tasks_subjects(week_day, key):
        #Code here
        return __tasks

    def day_studies(week_day):
        __tasks_subjects = tasks_subjects(week_day, 0)
        #Code here
        return __studies

    return render(request, 'study_time.html', context)

On my core/views.py, I need the day_studies() function, so I'm importing like this:

from saga.study_time.views import day_studies
    def home(request):
        day_progress = day_studies(datetime.date.today().isoweekday())

But I'm getting the error:

ImportError: cannot import name 'day_studies'

How can I make this importation? I don't want to reply all code.


问:
Erlang create directory
I need create subdirectory in specific directory.

In erlang docs i find only file:make_dir/1 which create dir in the project source dir. How can i create directory in other dir?

I find solution. Maybe it will be interesting somebody:

```<code>filelib:ensure_dir("/this/path/will/soon/exist/").
</code>```

Thank you.

答:
You can ensure that a directory exists (and create it if it doesn't, which is what you're looking for) using filelib:ensure_dir.

Example:

```<code>filelib:ensure_dir("/this/path/will/soon/exist/")
</code>```

References:

filelib:ensure_dir documentation

Title: Erlang create directory

Body:
I need create subdirectory in specific directory.

In erlang docs i find only file:make_dir/1 which create dir in the project source dir. How can i create directory in other dir?

I find solution. Maybe it will be interesting somebody:

filelib:ensure_dir("/this/path/will/soon/exist/").

Thank you.

Body:
You can ensure that a directory exists (and create it if it doesn't, which is what you're looking for) using filelib:ensure_dir.

Example:

filelib:ensure_dir("/this/path/will/soon/exist/")

References:

filelib:ensure_dir documentation


问:
Using read.csv for rowSums with blanks in R
I'm working in R with data imported from a csv file and I'm trying to take a rowSum of a subset of my data. The data can either be 0, 1, or blank. I'd like to take a sum of all the 1s across all these rows (and ideally find a count of how many non-blank columns there are in each row, but that's my next problem). I am trying the following code:

```<code>df1 <- read.csv("/Users/ardyn/test.csv", header = T, na.strings = "")

rowSums(df1[,36:135])
</code>```

Which gives me the following error:

"Error in rowSums(df1[, 36:135]) : 'x' must be numeric".

When I check, the columns I'm trying to sum across are factors with 3 levels (".","0","1").

How do I import the data or change my rowSums command so that when I take a sum across a subset of variables it just counts the 1s?

答:
Only numbers and NA can be handled by rowSums(). If it works, try setting na.strings=".".

Else we can substitute all . with NA after reading the csv.

```<code>df1 <- read.csv("/Users/ardyn/test.csv", header = TRUE,
  na.strings = ".", stringsAsFactors=FALSE)

rowSums(df1[,36:135], na.rm=TRUE)
</code>```

Example of changing . to NA post fact:

```<code>dtf <- as.data.frame(matrix(sample(c(".", "0", "1"), 20, replace=TRUE), 4))

sapply(dtf, function(x) as.numeric(gsub("\\.", "NA", x)))

#      V1 V2 V3 V4 V5
# [1,]  1  0  0  0  1
# [2,]  1  1  0  0  0
# [3,]  1  1 NA  1 NA
# [4,] NA NA  1  0  0
</code>```

Body:
I'm working in R with data imported from a csv file and I'm trying to take a rowSum of a subset of my data. The data can either be 0, 1, or blank. I'd like to take a sum of all the 1s across all these rows (and ideally find a count of how many non-blank columns there are in each row, but that's my next problem). I am trying the following code:

df1 <- read.csv("/Users/ardyn/test.csv", header = T, na.strings = "")

rowSums(df1[,36:135])

Which gives me the following error:

"Error in rowSums(df1[, 36:135]) : 'x' must be numeric".

When I check, the columns I'm trying to sum across are factors with 3 levels (".","0","1").

How do I import the data or change my rowSums command so that when I take a sum across a subset of variables it just counts the 1s?

Body:
Only numbers and NA can be handled by rowSums(). If it works, try setting na.strings=".".

Else we can substitute all . with NA after reading the csv.

df1 <- read.csv("/Users/ardyn/test.csv", header = TRUE,
  na.strings = ".", stringsAsFactors=FALSE)

rowSums(df1[,36:135], na.rm=TRUE)

Example of changing . to NA post fact:

dtf <- as.data.frame(matrix(sample(c(".", "0", "1"), 20, replace=TRUE), 4))

sapply(dtf, function(x) as.numeric(gsub("\\.", "NA", x)))

#      V1 V2 V3 V4 V5
# [1,]  1  0  0  0  1
# [2,]  1  1  0  0  0
# [3,]  1  1 NA  1 NA
# [4,] NA NA  1  0  0


问:
Is there a way to execute this code using a For Loop, just curious?
This code removes the space between names and inserts a comma. I am curious to know if there is a way to execute the same code using a For Loop in replace of "Split". I remember doing something similar but not enough to actually do it.

function cutName (name) {
    return name.split(' ');
}

alert(cutName("Amjad Ali"));```

答:
function cutName(name){
  var result = "";
  for(const char of name) result += char === " " ? "," : char;
  return result;
}

console.log(cutName("Jonas W"));```

You may use a for loop to iterate over every character.

Body:
function cutName(name){
  var result = "";
  for(const char of name) result += char === " " ? "," : char;
  return result;
}

console.log(cutName("Jonas W"));

You may use a for loop to iterate over every character.


问:
Angular4 -Building dynamic forms from RestAPI Jsondata for fields
I am building a form builder application using following the Tutorial https://toddmotto.com/angular-dynamic-components-forms

I was able to build using that example & add it to my project. The data for the form comes from httpClient. Once I brought in the observable, then the data passing to the child components got out of sync.

I tried to pass the observable to the child similar to the template below

```<code><div>
<dynamic-form
[fieldCfg]="fieldConfig|async"
#form="dynamicForm"
(submit)="submit($event)">
</dynamic-form>
{{ form.valid }}
{{ form.value | json }}
</div>
</code>```

where fieldConfig is an observable. When I pass it to my child component & subscribe it on ngOnChanges, I get the error cannot subscribe to this.fieldConfig. I am relatively new to angular, and I would like to know the best approach to tackle this scenario.

答: If you use the async pipe it automatically subscribes for you. So now in the field fieldCfg you don't have an Observable<T> but the T so it's the result of the Observable

Body:
I am building a form builder application using following the Tutorial https://toddmotto.com/angular-dynamic-components-forms

I was able to build using that example & add it to my project. The data for the form comes from httpClient. Once I brought in the observable, then the data passing to the child components got out of sync.

I tried to pass the observable to the child similar to the template below

<dynamic-form
[fieldCfg]="fieldConfig|async"
#form="dynamicForm"
(submit)="submit($event)">
</dynamic-form>
{{ form.valid }}
{{ form.value | json }}

where fieldConfig is an observable. When I pass it to my child component & subscribe it on ngOnChanges, I get the error cannot subscribe to this.fieldConfig. I am relatively new to angular, and I would like to know the best approach to tackle this scenario.


问:
How to set default selected value of ion-option?
I'm using Ionic v2 and I can not set the selected value when showing the page.

```<code><ion-select [(ngModel)]="company.form">
    <ion-option *ngFor="let form of forms" [value]="form" [selected]="true">{{form.name}}</ion-option>
</ion-select>
</code>```

I've tried with checked, too but that isn't work either. How can I do this?

```<code>Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.13
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.45
</code>```

答:
You do not need to work with the attribute selected or [selected] it is not necessary</p>

```<code><ion-select [(ngModel)]="company.form.id" name="company.form.id">
    <ion-option *ngFor="let form of forms" value="{{ form.id }}">
      {{ form.name }}
    </ion-option>
</ion-select>
</code>```

Body:
I'm using Ionic v2 and I can not set the selected value when showing the page.

<ion-select [(ngModel)]="company.form">
    <ion-option *ngFor="let form of forms" [value]="form" [selected]="true">{{form.name}}</ion-option>
</ion-select>

I've tried with checked, too but that isn't work either. How can I do this?

Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.13
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.45

Body:
You do not need to work with the attribute selected or [selected] it is not necessary

<ion-select [(ngModel)]="company.form.id" name="company.form.id">
    <ion-option *ngFor="let form of forms" value="{{ form.id }}">
      {{ form.name }}
    </ion-option>
</ion-select>


问:
WSO2 Api Manager: how to see the requested URL
WSO2 maps the requested Url called in it to an Url in another server. How can see the mapped URL that WSO2 effectively called?</p>

答:
Just found an answer at WSO2 blog: [Trace API calls and responses](https://wso2.com/blogs/cloud/trace-api-calls-and-responses/}.

Open for editing the API that you want to trace,

Go to step 2 (Implement),

Click the Enable Message Mediation checkbox and then select the debug_ sequences from the dropdowns for all 3 flows below it

Click the Next: Manage button at the bottom of the screen,

Click Save & Publish at the bottom of the last step of the editing wizard.

Open the live log by clicking the Configure / Admin Dashboard menu, and then clicking Log Analyzer / Live Log Viewer in Admin Dashboard’s left-hand menu pane.

Now invoke the API (for example, in the API Store‘s API Console for that API).

You will see detailed information on the API request and response in the log

When you are done troubleshooting, disable the message mediation that you enabled in step 3.

This solution has a great disadvantage: you must have Analytics running (I don't have it now). But you can turn it on just for your own API. If you don't have Analytics running, you can compromise with @Bee solution below and some tail -f|grep .


问:
How to plot a histogram from existing counts with uneven bin widths using ggplot
I want to create an histogram from already existing classes. I have this dataset:

```<code>interval        counts
0 - 8.50        2577
8.51 - 10.00    1199
10.01 - 12.00   1878
12.01 - 14.00   637
14.01 - 16.00   369
16.01 - 18.00   98
18.00 - 20.00   308

library(ggplot2)

plot_tab5_lohn <- ggplot(DS18, aes(x=interval)) + geom_histogram(stat="count")
return(plot_tab5_lohn)})
</code>```

does result in this graph:

I want the counts to be on the y axis and the intervals have to be a different width. How can I do this?

EDIT:
I've made it this far:

using this code

```<code>DS18$interval <- factor(DS18$interval, levels = DS18$interval)
output$DS32 <- renderPlot({
plot_tab5_lohn <- ggplot(DS18, aes(x=interval, y = counts)) +
geom_col() +
geom_point(color = "red") +
geom_line(aes(group = 1), color = "red")
return(plot_tab5_lohn)
})
</code>```

I'd like the bars to be as wide as the interval itself. And the density should be on the Y-Axis. The sum of the areas should be 1 (100%) then.
Something like this link

答:
You can use stat = "identity" and add a y aesthetic to get your desired graph:

```<code>ggplot(DS18, aes(x=interval, y = counts)) +
  geom_histogram(stat="identity")
</code>```

that gives you this:

Body:
I want to create an histogram from already existing classes. I have this dataset:

interval        counts
0 - 8.50        2577
8.51 - 10.00    1199
10.01 - 12.00   1878
12.01 - 14.00   637
14.01 - 16.00   369
16.01 - 18.00   98
18.00 - 20.00   308

library(ggplot2)

plot_tab5_lohn <- ggplot(DS18, aes(x=interval)) + geom_histogram(stat="count")
return(plot_tab5_lohn)})

does result in this graph:

I want the counts to be on the y axis and the intervals have to be a different width. How can I do this?

EDIT:
I've made it this far:

using this code

DS18$interval <- factor(DS18$interval, levels = DS18$interval)
output$DS32 <- renderPlot({
plot_tab5_lohn <- ggplot(DS18, aes(x=interval, y = counts)) +
geom_col() +
geom_point(color = "red") +
geom_line(aes(group = 1), color = "red")
return(plot_tab5_lohn)
})

I'd like the bars to be as wide as the interval itself. And the density should be on the Y-Axis. The sum of the areas should be 1 (100%) then.
Something like this link

Body:
You can use stat = "identity" and add a y aesthetic to get your desired graph:

ggplot(DS18, aes(x=interval, y = counts)) +
  geom_histogram(stat="identity")

that gives you this:


问:
Pygame window flickering
This is my text adventure code, pieces. When i start my code, my buttons and windows always flickering, and i don't know how to fix that problem. I tried pygame.window.update(), but it did not bring anything. Maybe it's problem with FPS, i don't know. :)
...............................................................................</p>

```<code>import pygame,sys

pygame.init()
#############
pygame.mixer.music.load('Invincible.mp3')
pygame.mixer.music.play()

#############

display_width = 800
display_height = 600

black = (0,0,0)
white = (255,255,255)

red = (200,0,0)
green = (0,200,0)

bright_red = (255,0,0)
bright_green = (0,255,0)

block_color = (53,115,255)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('One Day After')
clock = pygame.time.Clock()

gameIcon = pygame.image.load('gameicon.jpg')
pygame.display.set_icon(gameIcon)

pause = False

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def GameOver():
    ####################################
    pygame.mixer.Sound.play("smb_gameover.wav")
    pygame.mixer.music.stop()
    ####################################
    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("Game Over", largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        button("Play Again",150,450,100,50,green,bright_green,game_loop)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()
        clock.tick(15)

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            pygame.mixer.music.stop()
            action()

    else:
        pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    gameDisplay.blit(textSurf, textRect)

def quitgame():
    pygame.quit()
    sys.exit()
    quit()

def unpause():
    global pause
    pygame.mixer.music.unpause()
    pause = False

def paused():
    ############
    pygame.mixer.music.pause()
    #############
    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("Paused", largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        button("Continue",150,450,100,50,green,bright_green,unpause)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()
        clock.tick(15)

def game_intro():

    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        pilt1 = pygame.image.load('apoc2.jpg').convert()
        gameDisplay.blit(pilt1, [0,0])
        pygame.display.flip()

        button("Start",150,450,100,50,green,bright_green,game_loop)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()

def game_loop():
    global pause

    gameExit = False

    while not gameExit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                quit()
        gameDisplay.fill(white)
        pygame.display.flip()
        Backgroundpic = pygame.image.load('back.jpg').convert()
        gameDisplay.blit(Backgroundpic, [0,0])
        pygame.display.flip()
        tekst = "This game will go as far as you choose!"
        meie_font = pygame.font.SysFont("Arial", 36)
        teksti_pilt = meie_font.render(tekst, False, (50,50,155))
        gameDisplay.blit(teksti_pilt, (100, 250))
        tekst2 = "You are the smith of your destiny"
        meie_font = pygame.font.SysFont("Arial", 36)
        teksti_pilt = meie_font.render(tekst2, False, (50,50,155))
        gameDisplay.blit(teksti_pilt, (100, 400))

        pygame.display.flip()

game_intro()
game_loop()
pygame.quit()
quit()
</code>```

答: You seem to be flipping twice. You must flip only once, after everything is drawn. Remove the first call to flip() and your flicker should reduce.

Title: Pygame window flickering

Body:
This is my text adventure code, pieces. When i start my code, my buttons and windows always flickering, and i don't know how to fix that problem. I tried pygame.window.update(), but it did not bring anything. Maybe it's problem with FPS, i don't know. :)
...............................................................................

import pygame,sys

pygame.init()
#############
pygame.mixer.music.load('Invincible.mp3')
pygame.mixer.music.play()

#############

display_width = 800
display_height = 600

black = (0,0,0)
white = (255,255,255)

red = (200,0,0)
green = (0,200,0)

bright_red = (255,0,0)
bright_green = (0,255,0)

block_color = (53,115,255)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('One Day After')
clock = pygame.time.Clock()

gameIcon = pygame.image.load('gameicon.jpg')
pygame.display.set_icon(gameIcon)

pause = False

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def GameOver():
    ####################################
    pygame.mixer.Sound.play("smb_gameover.wav")
    pygame.mixer.music.stop()
    ####################################
    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("Game Over", largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        button("Play Again",150,450,100,50,green,bright_green,game_loop)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()
        clock.tick(15)

def button(msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            pygame.mixer.music.stop()
            action()

    else:
        pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
    smallText = pygame.font.SysFont("comicsansms",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    gameDisplay.blit(textSurf, textRect)

def quitgame():
    pygame.quit()
    sys.exit()
    quit()

def unpause():
    global pause
    pygame.mixer.music.unpause()
    pause = False

def paused():
    ############
    pygame.mixer.music.pause()
    #############
    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("Paused", largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        button("Continue",150,450,100,50,green,bright_green,unpause)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()
        clock.tick(15)

def game_intro():

    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        pilt1 = pygame.image.load('apoc2.jpg').convert()
        gameDisplay.blit(pilt1, [0,0])
        pygame.display.flip()

        button("Start",150,450,100,50,green,bright_green,game_loop)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()

def game_loop():
    global pause

    gameExit = False

    while not gameExit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                quit()
        gameDisplay.fill(white)
        pygame.display.flip()
        Backgroundpic = pygame.image.load('back.jpg').convert()
        gameDisplay.blit(Backgroundpic, [0,0])
        pygame.display.flip()
        tekst = "This game will go as far as you choose!"
        meie_font = pygame.font.SysFont("Arial", 36)
        teksti_pilt = meie_font.render(tekst, False, (50,50,155))
        gameDisplay.blit(teksti_pilt, (100, 250))
        tekst2 = "You are the smith of your destiny"
        meie_font = pygame.font.SysFont("Arial", 36)
        teksti_pilt = meie_font.render(tekst2, False, (50,50,155))
        gameDisplay.blit(teksti_pilt, (100, 400))

        pygame.display.flip()

game_intro()
game_loop()
pygame.quit()
quit()


问:
Algorithm to divide up linked objects (like contiguous US states) by some metric?
Use case: consider the 50 US states on a map, with each state corresponding to some cost function (i.e., market size). Is there an algorithm (and ideal an R/Python package) that divides the 50 states into N groups such that the variation in the sum of the cost function in each group is minimized? The only constraint is that all states in each group are contiguous (i.e., they form one large mass / connected to each other)</p>

答:
There is a related question with a smaller search space that might possibly be more tractable, or at least easier to code for. Given N groups, pick N states and call them roots. One way to divide states into groups is to say that the group associated with a root is the set of states closer to this root than to any other root.  To allow you to fine tune this a bit, have a constant K for each root, and divide up states according to the sum of the distance to the root and the constant K for that root.

Groups created in this way always consist of contiguous states, because if a state is in a group, all of the states on the shortest path from that state to the root of the group are also in that group. If one of them was not in that group, that state would have a shorter path to a different root, which means that the original state would also have a shorter path, via that intermediate state, to the different root, which is a contradiction.

This still isn't a tractable problem, but you call hill-climb on the constants to try and even out the allocations, and you can hill-climb on the choice of roots. If you hill-climb from multiple random starts, you can hope that you will get some decent answers, and you might hope to get an idea of how good your best answer seen so far is by looking at the other hilltops found - I would be optimistic if the best answer seen occurred multiple times.

Here follows some Java with comments trimmed due to limits on bodies

```<code>
import java.util.ArrayList;
import java.util.Arrays;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.util.Collections;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.io.File;
import java.io.FileReader;
import java.awt.Graphics;
import java.util.HashMap;
import java.util.HashSet;
import java.io.IOException;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.awt.Rectangle;
import javax.swing.SwingUtilities;

public class States
{
  /** Info held for State */
  private static class StateInfo
  {
    private final String m_name;
    /** abbreviation of state - drawn on graph */
    private final String m_abbreviation;
    private final double m_latitudeDegrees;
    private final double m_longitudeDegrees;
    private int m_currentX;
    private int m_currentY;
    /** 0-up number allocated and offset in ArrayList */
    private final int m_number;
    /** link to neighbouring states */
    private final ArrayList m_neighbours =
      new ArrayList();
    /** colour to print in. Modified when states are grouped */
    private Color m_color = Color.BLACK;
    /** weight when computing variance */
    private double m_weight = 1.0;
    public String toString()
    {
      StringBuilder sb = new StringBuilder();
      sb.append(m_abbreviation + " color " + m_color);
      return sb.toString();
    }
    public StateInfo(String name, String abbreviation,
      double latitudeDegrees, double longitudeDegrees, int number)
    {
      m_name = name;
      m_abbreviation = abbreviation;
      m_latitudeDegrees = latitudeDegrees;
      m_longitudeDegrees = longitudeDegrees;
      m_number = number;
    }
    public double getLatitudeDegrees()
    {
      return m_latitudeDegrees;
    }
    public double getLongitudeDegrees()
    {
      return m_longitudeDegrees;
    }
    public String getAbbreviation()
    {
      return m_abbreviation;
    }
    public void addNeighbour(StateInfo si)
    {
      m_neighbours.add(si);
    }
    public List getNeighbours()
    {
      return Collections.unmodifiableList(m_neighbours);
    }
    public void setCurrentPos(int x, int y)
    {
      m_currentX = x;
      m_currentY = y;
    }
    public int getX()
    {
      return m_currentX;
    }
    public int getY()
    {
      return m_currentY;
    }
    public int getNumber()
    {
      return m_number;
    }
    public Color getColor()
    {
      return m_color;
    }
    public void setColor(Color newValue)
    {
      m_color = newValue;
    }
    public double getWeight()
    {
      return m_weight;
    }
    public void setWeight(double newValue)
    {
      m_weight = newValue;
    }
  }
  public static class StatePanel extends JPanel
  {
    @Override
    public void paint(Graphics g)
    {
      Rectangle rect = getBounds();
      double minLat = Double.MAX_VALUE;
      double maxLat = -Double.MAX_VALUE;
      double minLon = Double.MAX_VALUE;
      double maxLon = -Double.MAX_VALUE;
      for (StateInfo si: m_stateInfo)
      {
        double lat = si.getLatitudeDegrees();
        double lon = si.getLongitudeDegrees();
        if (lat  maxLat)
        {
          maxLat = lat;
        }
        if (lon  maxLon)
        {
          maxLon = lon;
        }
      }
      int numStates = m_stateInfo.size();
      double gapAdd = 1.0 / (double)(numStates + 1);
      double gapFactor = (numStates - 1) / (double)(numStates + 1);
      for (StateInfo si: m_stateInfo)
      {
        double x = (si.getLongitudeDegrees() - minLon) / (maxLon - minLon);
        x = x * gapFactor + gapAdd;
        double y = (maxLat - si.getLatitudeDegrees()) / (maxLat - minLat);
        y = y * gapFactor + gapAdd;
        int xpos = (int)Math.round(rect.x + x * rect.width);
        int ypos = (int)Math.round(rect.y + y * rect.height);
        g.setColor(si.getColor());
        g.drawString(si.getAbbreviation(), xpos, ypos);
        si.setCurrentPos(xpos, ypos);
      }
      g.setColor(Color.BLACK);
      for (StateInfo si: m_stateInfo)
      {
        int xp = si.getX();
        int yp = si.getY();
        for (StateInfo ti: si.getNeighbours())
        {
          if (si.getNumber()  rows = new ArrayList();
        for (;;)
        {
          String line = br.readLine();
          if (line == null)
          {
            break;
          }
          int len = line.length();
          int l1 = len - 1;
          ArrayList cells = new ArrayList();
          StringBuilder currentCell = new StringBuilder();
          for (int i = 0; i = l1)
              {
                throw new IllegalArgumentException("Unterminated quote in line " + line);
              }
              ch = line.charAt(++i);
              if (ch != '"')
              {
                currentCell.append(ch);
                continue;
              }
              if ((i >= l1) || (line.charAt(i + 1) != '"'))
              {
                break;
              }
              currentCell.append(ch);
              i++;
            }
          }
          if (len > 0)
          {
            cells.add(currentCell.toString());
          }
          String[] row = new String[cells.size()];
          row = cells.toArray(row);
          rows.add(row);
        }
        String[][] result = new String[rows.size()][];
        result = rows.toArray(result);
        return result;
      }
      finally
      {
        fr.close();
      }
    }
    /** Read locations of states and links between them from file */
    public void readLocations(String filename, String linkFile) throws Exception
    {
      // First two lines of file are
      // # State,Latitude,Longitude,Abbreviation,Population
      // Alabama,32.806671,-86.79113,AL,4.859
      // Population is in millions. File is result of hand-editing together info from web
      String[][] data = readCsv(new File(filename));
      m_stateInfo = new ArrayList();
      m_stateInfoByAbbreviation = new HashMap();
      int num = 0;
      for (String[] row: data)
      {
        if (row.length  rootOffsetByColor = new HashMap();
      for (int i = 0; i  reducedWeights[i])
          {
            reducedWeights[i] = reduced;
          }
        }
        if (secondBest  totalByColor = new HashMap();
      for (;;)
      {
        allocateViaDistance(m_roots, initialWeights, m_colors);
        double varianceHere = getVariance(totalByColor);
        double total = 0.0;
        for (Double d: totalByColor.values())
        {
          total += d.doubleValue();
        }
        double target = total / m_roots.length;
        minimumNecessary(m_roots, initialWeights, m_colors, decrease, increase);
        boolean improved = false;
        // Don't need to change weight[0] as we can regard everything else as
        // compared to that as a standard
        for (int i = 1; i  totalByColor)
    {
      totalByColor.clear();
      for (StateInfo si: m_stateInfo)
      {
        Color key = si.getColor();
        Double d = new Double(0.0);
        if (totalByColor.containsKey(key))
        {
          d = totalByColor.get(key);
        }
        totalByColor.put(key, new Double(d.doubleValue() + si.getWeight()));
      }
      int numUsed = totalByColor.size();
      if (numUsed  totalByColor = new HashMap();
      return getVariance(totalByColor);
    }
    public StateInfo getState(String abbreviation)
    {
      return m_stateInfoByAbbreviation.get(abbreviation);
    }
    public void setColorsRoots(Color[] colors, StateInfo[] roots)
    {
      m_roots = roots;
      m_colors = colors;
    }
    public StateInfo[] getRoots()
    {
      return m_roots;
    }
    public double climbRoots(double[] weights)
    {
      for (;;)
      {
        double current = getVariance();
        boolean improved = false;
        for (int i = 0; i  chosen = new HashSet();
        m_roots = new StateInfo[weights.length];
        for (int j = 0; j  m_stateInfo;
    private Map m_stateInfoByAbbreviation;
    private double[][] m_distances;
    private StateInfo[] m_roots;
    private Color[] m_colors;
  }
  /** compute all-pairs distances (Floyd - Warshall) */
  public static void allPairs(double[][] distances)
  {
    int pass = 0;
    for (boolean changed = true; changed;)
    {
      changed = false;
      System.err.println("Pass " + (pass++));
      for (int i = 0; i  totalByColor = new HashMap();
            var = sp.getVariance(totalByColor);
            System.out.println("Multiple start Climbed to variance " + var);
            System.out.println("Roots " + Arrays.toString(sp.getRoots()));
            System.out.println("Totals " + totalByColor.values());
          }
          System.out.println("Allocated result is " + sp.getVariance());
        }
        catch (Exception ex)
        {
          System.err.println("Exception setting up: " + ex);
          ex.printStackTrace();
          return;
        }
        sp.setPreferredSize(new Dimension(400, 400));
        JFrame w = new JFrame();
        w.setTitle("States");
        Container cp = w.getContentPane();
        cp.setLayout(new BorderLayout());
        cp.add(sp, BorderLayout.CENTER);
        w.pack();
        w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        w.setVisible(true);
      }
    };
    SwingUtilities.invokeAndWait(r);
  }
}
</code>```

Body:
There is a related question with a smaller search space that might possibly be more tractable, or at least easier to code for. Given N groups, pick N states and call them roots. One way to divide states into groups is to say that the group associated with a root is the set of states closer to this root than to any other root.  To allow you to fine tune this a bit, have a constant K for each root, and divide up states according to the sum of the distance to the root and the constant K for that root.

Groups created in this way always consist of contiguous states, because if a state is in a group, all of the states on the shortest path from that state to the root of the group are also in that group. If one of them was not in that group, that state would have a shorter path to a different root, which means that the original state would also have a shorter path, via that intermediate state, to the different root, which is a contradiction.

This still isn't a tractable problem, but you call hill-climb on the constants to try and even out the allocations, and you can hill-climb on the choice of roots. If you hill-climb from multiple random starts, you can hope that you will get some decent answers, and you might hope to get an idea of how good your best answer seen so far is by looking at the other hilltops found - I would be optimistic if the best answer seen occurred multiple times.

Here follows some Java with comments trimmed due to limits on bodies

import java.util.ArrayList;
import java.util.Arrays;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.util.Collections;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.io.File;
import java.io.FileReader;
import java.awt.Graphics;
import java.util.HashMap;
import java.util.HashSet;
import java.io.IOException;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.awt.Rectangle;
import javax.swing.SwingUtilities;

public class States
{
  /** Info held for State */
  private static class StateInfo
  {
    private final String m_name;
    /** abbreviation of state - drawn on graph */
    private final String m_abbreviation;
    private final double m_latitudeDegrees;
    private final double m_longitudeDegrees;
    private int m_currentX;
    private int m_currentY;
    /** 0-up number allocated and offset in ArrayList */
    private final int m_number;
    /** link to neighbouring states */
    private final ArrayList m_neighbours =
      new ArrayList();
    /** colour to print in. Modified when states are grouped */
    private Color m_color = Color.BLACK;
    /** weight when computing variance */
    private double m_weight = 1.0;
    public String toString()
    {
      StringBuilder sb = new StringBuilder();
      sb.append(m_abbreviation + " color " + m_color);
      return sb.toString();
    }
    public StateInfo(String name, String abbreviation,
      double latitudeDegrees, double longitudeDegrees, int number)
    {
      m_name = name;
      m_abbreviation = abbreviation;
      m_latitudeDegrees = latitudeDegrees;
      m_longitudeDegrees = longitudeDegrees;
      m_number = number;
    }
    public double getLatitudeDegrees()
    {
      return m_latitudeDegrees;
    }
    public double getLongitudeDegrees()
    {
      return m_longitudeDegrees;
    }
    public String getAbbreviation()
    {
      return m_abbreviation;
    }
    public void addNeighbour(StateInfo si)
    {
      m_neighbours.add(si);
    }
    public List getNeighbours()
    {
      return Collections.unmodifiableList(m_neighbours);
    }
    public void setCurrentPos(int x, int y)
    {
      m_currentX = x;
      m_currentY = y;
    }
    public int getX()
    {
      return m_currentX;
    }
    public int getY()
    {
      return m_currentY;
    }
    public int getNumber()
    {
      return m_number;
    }
    public Color getColor()
    {
      return m_color;
    }
    public void setColor(Color newValue)
    {
      m_color = newValue;
    }
    public double getWeight()
    {
      return m_weight;
    }
    public void setWeight(double newValue)
    {
      m_weight = newValue;
    }
  }
  public static class StatePanel extends JPanel
  {
    @Override
    public void paint(Graphics g)
    {
      Rectangle rect = getBounds();
      double minLat = Double.MAX_VALUE;
      double maxLat = -Double.MAX_VALUE;
      double minLon = Double.MAX_VALUE;
      double maxLon = -Double.MAX_VALUE;
      for (StateInfo si: m_stateInfo)
      {
        double lat = si.getLatitudeDegrees();
        double lon = si.getLongitudeDegrees();
        if (lat  maxLat)
        {
          maxLat = lat;
        }
        if (lon  maxLon)
        {
          maxLon = lon;
        }
      }
      int numStates = m_stateInfo.size();
      double gapAdd = 1.0 / (double)(numStates + 1);
      double gapFactor = (numStates - 1) / (double)(numStates + 1);
      for (StateInfo si: m_stateInfo)
      {
        double x = (si.getLongitudeDegrees() - minLon) / (maxLon - minLon);
        x = x * gapFactor + gapAdd;
        double y = (maxLat - si.getLatitudeDegrees()) / (maxLat - minLat);
        y = y * gapFactor + gapAdd;
        int xpos = (int)Math.round(rect.x + x * rect.width);
        int ypos = (int)Math.round(rect.y + y * rect.height);
        g.setColor(si.getColor());
        g.drawString(si.getAbbreviation(), xpos, ypos);
        si.setCurrentPos(xpos, ypos);
      }
      g.setColor(Color.BLACK);
      for (StateInfo si: m_stateInfo)
      {
        int xp = si.getX();
        int yp = si.getY();
        for (StateInfo ti: si.getNeighbours())
        {
          if (si.getNumber()  rows = new ArrayList();
        for (;;)
        {
          String line = br.readLine();
          if (line == null)
          {
            break;
          }
          int len = line.length();
          int l1 = len - 1;
          ArrayList cells = new ArrayList();
          StringBuilder currentCell = new StringBuilder();
          for (int i = 0; i = l1)
              {
                throw new IllegalArgumentException("Unterminated quote in line " + line);
              }
              ch = line.charAt(++i);
              if (ch != '"')
              {
                currentCell.append(ch);
                continue;
              }
              if ((i >= l1) || (line.charAt(i + 1) != '"'))
              {
                break;
              }
              currentCell.append(ch);
              i++;
            }
          }
          if (len > 0)
          {
            cells.add(currentCell.toString());
          }
          String[] row = new String[cells.size()];
          row = cells.toArray(row);
          rows.add(row);
        }
        String[][] result = new String[rows.size()][];
        result = rows.toArray(result);
        return result;
      }
      finally
      {
        fr.close();
      }
    }
    /** Read locations of states and links between them from file */
    public void readLocations(String filename, String linkFile) throws Exception
    {
      // First two lines of file are
      // # State,Latitude,Longitude,Abbreviation,Population
      // Alabama,32.806671,-86.79113,AL,4.859
      // Population is in millions. File is result of hand-editing together info from web
      String[][] data = readCsv(new File(filename));
      m_stateInfo = new ArrayList();
      m_stateInfoByAbbreviation = new HashMap();
      int num = 0;
      for (String[] row: data)
      {
        if (row.length  rootOffsetByColor = new HashMap();
      for (int i = 0; i  reducedWeights[i])
          {
            reducedWeights[i] = reduced;
          }
        }
        if (secondBest  totalByColor = new HashMap();
      for (;;)
      {
        allocateViaDistance(m_roots, initialWeights, m_colors);
        double varianceHere = getVariance(totalByColor);
        double total = 0.0;
        for (Double d: totalByColor.values())
        {
          total += d.doubleValue();
        }
        double target = total / m_roots.length;
        minimumNecessary(m_roots, initialWeights, m_colors, decrease, increase);
        boolean improved = false;
        // Don't need to change weight[0] as we can regard everything else as
        // compared to that as a standard
        for (int i = 1; i  totalByColor)
    {
      totalByColor.clear();
      for (StateInfo si: m_stateInfo)
      {
        Color key = si.getColor();
        Double d = new Double(0.0);
        if (totalByColor.containsKey(key))
        {
          d = totalByColor.get(key);
        }
        totalByColor.put(key, new Double(d.doubleValue() + si.getWeight()));
      }
      int numUsed = totalByColor.size();
      if (numUsed  totalByColor = new HashMap();
      return getVariance(totalByColor);
    }
    public StateInfo getState(String abbreviation)
    {
      return m_stateInfoByAbbreviation.get(abbreviation);
    }
    public void setColorsRoots(Color[] colors, StateInfo[] roots)
    {
      m_roots = roots;
      m_colors = colors;
    }
    public StateInfo[] getRoots()
    {
      return m_roots;
    }
    public double climbRoots(double[] weights)
    {
      for (;;)
      {
        double current = getVariance();
        boolean improved = false;
        for (int i = 0; i  chosen = new HashSet();
        m_roots = new StateInfo[weights.length];
        for (int j = 0; j  m_stateInfo;
    private Map m_stateInfoByAbbreviation;
    private double[][] m_distances;
    private StateInfo[] m_roots;
    private Color[] m_colors;
  }
  /** compute all-pairs distances (Floyd - Warshall) */
  public static void allPairs(double[][] distances)
  {
    int pass = 0;
    for (boolean changed = true; changed;)
    {
      changed = false;
      System.err.println("Pass " + (pass++));
      for (int i = 0; i  totalByColor = new HashMap();
            var = sp.getVariance(totalByColor);
            System.out.println("Multiple start Climbed to variance " + var);
            System.out.println("Roots " + Arrays.toString(sp.getRoots()));
            System.out.println("Totals " + totalByColor.values());
          }
          System.out.println("Allocated result is " + sp.getVariance());
        }
        catch (Exception ex)
        {
          System.err.println("Exception setting up: " + ex);
          ex.printStackTrace();
          return;
        }
        sp.setPreferredSize(new Dimension(400, 400));
        JFrame w = new JFrame();
        w.setTitle("States");
        Container cp = w.getContentPane();
        cp.setLayout(new BorderLayout());
        cp.add(sp, BorderLayout.CENTER);
        w.pack();
        w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        w.setVisible(true);
      }
    };
    SwingUtilities.invokeAndWait(r);
  }
}


问:
Can I use multiple booleans for conditional rendering in React?
I want to do something like the following in a React component:

```<code><div>
    {this.props.isOpen && this.state.isReady && <div> Hello! </div>}
</div>
</code>```

Is it possible to use multiple booleans for conditionally rendering components in React? Could this ever possibly render a boolean to the user?

答:
You can do it. it will either return the jsx or null (Won't render anything).

Example when condition is true:

const App = () => (

    {true && true &&
 Hello!
}

);

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Example when condition is false:

const App = () => (

    {true && false &&
 Hello!
}

);

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Body:
I want to do something like the following in a React component:

    {this.props.isOpen && this.state.isReady &&
 Hello!
}

Is it possible to use multiple booleans for conditionally rendering components in React? Could this ever possibly render a boolean to the user?

Body:
You can do it. it will either return the jsx or null (Won't render anything).

Example when condition is true:

const App = () => (
  <div>
    {true && true && <div> Hello! </div>}
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Example when condition is false:

const App = () => (
  <div>
    {true && false && <div> Hello! </div>}
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
Get ISO 3166-2 Code from Bing Maps Locations API
Is there a way to get the ISO 3166-2 Code for a specific PostalCode/CountryCode Combination with the Bing Maps Locations API?

Per Example: 1210/AT => AT-9

答:
Use the Bing Maps REST Location API and geocode your query (postal, country...). As part of the request add &incl=ciso2 which will return the country's ISO2 code value. For example:

https://dev.virtualearth.net/REST/v1/Locations?q=1210%2C%20AT&incl=ciso2&key=YOUR_Bing_Maps_Key

Will return the following:

```<code>{
"authenticationResultCode": "ValidCredentials",
"brandLogoUri": "http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
"copyright": "Copyright © 2017 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets": [{
    "estimatedTotal": 1,
    "resources": [{
        "__type": "Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
        "bbox": [48.237850189209, 16.3536491394043, 48.3225288391113, 16.4731197357178],
        "name": "1210, Austria",
        "point": {
            "type": "Point",
            "coordinates": [48.2801895141602, 16.4104042053223]
        },
        "address": {
            "adminDistrict": "Vienna",
            "adminDistrict2": "Vienna",
            "countryRegion": "Austria",
            "formattedAddress": "1210, Austria",
            "locality": "Vienna",
            "postalCode": "1210",
            "countryRegionIso2": "AT"
        },
        "confidence": "High",
        "entityType": "Postcode1",
        "geocodePoints": [{
            "type": "Point",
            "coordinates": [48.2801895141602, 16.4104042053223],
            "calculationMethod": "Rooftop",
            "usageTypes": ["Display"]
        }],
        "matchCodes": ["Good"]
    }]
}],
"statusCode": 200,
"statusDescription": "OK",
"traceId": "cb93431f2caa4f9fb2fcdbaa0ae80b74|CO30324109|7.7.0.0|"
}
</code>```

Notice in the address property of the response there is "countryRegionIso2": "AT"

Documentation on the Bing Maps REST Locaiton API can be found here: https://msdn.microsoft.com/en-US/library/ff701711.aspx

There is a best practices guide here: https://msdn.microsoft.com/en-us/library/dn894107.aspx

If using .NET you may want to use the Bing Maps REST .NET Toolkit: https://github.com/Microsoft/BingMapsRESTToolkit It makes it really easy to use the REST services in .NET and also has a NuGet package for easily including in your project.

Body:
Use the Bing Maps REST Location API and geocode your query (postal, country...). As part of the request add &incl=ciso2 which will return the country's ISO2 code value. For example:

https://dev.virtualearth.net/REST/v1/Locations?q=1210%2C%20AT&incl=ciso2&key=YOUR_Bing_Maps_Key

Will return the following:

{
"authenticationResultCode": "ValidCredentials",
"brandLogoUri": "http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
"copyright": "Copyright © 2017 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets": [{
    "estimatedTotal": 1,
    "resources": [{
        "__type": "Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
        "bbox": [48.237850189209, 16.3536491394043, 48.3225288391113, 16.4731197357178],
        "name": "1210, Austria",
        "point": {
            "type": "Point",
            "coordinates": [48.2801895141602, 16.4104042053223]
        },
        "address": {
            "adminDistrict": "Vienna",
            "adminDistrict2": "Vienna",
            "countryRegion": "Austria",
            "formattedAddress": "1210, Austria",
            "locality": "Vienna",
            "postalCode": "1210",
            "countryRegionIso2": "AT"
        },
        "confidence": "High",
        "entityType": "Postcode1",
        "geocodePoints": [{
            "type": "Point",
            "coordinates": [48.2801895141602, 16.4104042053223],
            "calculationMethod": "Rooftop",
            "usageTypes": ["Display"]
        }],
        "matchCodes": ["Good"]
    }]
}],
"statusCode": 200,
"statusDescription": "OK",
"traceId": "cb93431f2caa4f9fb2fcdbaa0ae80b74|CO30324109|7.7.0.0|"
}

Notice in the address property of the response there is "countryRegionIso2": "AT"

Documentation on the Bing Maps REST Locaiton API can be found here: https://msdn.microsoft.com/en-US/library/ff701711.aspx

There is a best practices guide here: https://msdn.microsoft.com/en-us/library/dn894107.aspx

If using .NET you may want to use the Bing Maps REST .NET Toolkit: https://github.com/Microsoft/BingMapsRESTToolkit It makes it really easy to use the REST services in .NET and also has a NuGet package for easily including in your project.


问:
Android and Google App Engine: supported XML Binding Tool available?
A REST XML (not JSON!) Web Service should exchange XML Schema specified XML between a Google App Engine and an Android app.

I wanted to use XStream for both, however, I could not get it to work for the Google App Engine, therefore to me Apache XMLBeans is the next best choice (JAXB does not work on both).
However, with Google App Engine there is no problem, but on Android, I get several severe exceptions (eg. due to the usage of the Stax API with its javax.xml.* packages).

So,

Is there any other XML-binding possibility to stream XML documents on GAE and Android?

If not, is it possible to patch Apache XMLBeans to work with Android?

Thanks!

答: You can use Castor . Just be sure, in Android 2.1, not to use default android SAXParser. You'll get namespace errors. You do this by defining the parser to be, for example, Xerces (and the you add the required JARS), in core.properties . In android 2.2 it may be ok. Note that if you create an xmlcontext for the unmarsheler with xerces, it still won't work, as the mapping itself would be parsed with android's SAX. It must be done at core (top level properties file) so that even the mapping is parsed by xerces. finally - performance is as slow as you can expect... :( Good luck SM</p>


问:
How do I do df["col1"].astype(float) with a default for unconvertable values?
Here is my code

f["col1"] = df["col1"].astype(float)

col1 has values that can't be converted.

How would I do something like this:

```<code>df["col1"] = df["col1"].astype(float, default=0)
</code>```

答:
You can using pd.to_numeric + fillna

```<code>df["col1"]=pd.to_numeric(df["col1"], errors='coerce', downcast='float').fillna(0)
</code>```

Body:
Here is my code

f["col1"] = df["col1"].astype(float)

col1 has values that can't be converted.

How would I do something like this:

df["col1"] = df["col1"].astype(float, default=0)

Body:
You can using pd.to_numeric + fillna

df["col1"]=pd.to_numeric(df["col1"], errors='coerce', downcast='float').fillna(0)


问:
Dynamically created elements all return the same index
I'm dynamically creating dropdowns in a table, and I'm trying to grab the index of the dropdown that triggered the event, like so:

```<code>$(".template").on('change', '.dataTypes', function () {
    var selectedDatatype = $(this).find(":selected").val();
    var ix = $(this).index(); // get this index

    $.ajax({
        type: "GET",
        url: "http://localhost...",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            populateListDropdown("gs", ix, result.Result);
        },
        error: function () { },
        timeout: 120000
    });
});
</code>```

This code, regardless of the dropdown I interact with always returns a 0 for the index and I'm not sure why.

HTML if it's helpful. The page has a single row loaded at startup, and additional are added via button click.

```<code><table class="tblColumns">
    <tr>
        <td>
            <div class="column">
                Select DataType :
                <select class="dataTypes"></select>
        </td>
    </tr>
</table>
</code>```

答:
For further reading, check out https://api.jquery.com/index/

"If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements."

In your HTML the  is the only element, hence always returning '0'.

As @Azim pointed out, if you use , it might work.

Body:
I'm dynamically creating dropdowns in a table, and I'm trying to grab the index of the dropdown that triggered the event, like so:

$(".template").on('change', '.dataTypes', function () {
    var selectedDatatype = $(this).find(":selected").val();
    var ix = $(this).index(); // get this index

    $.ajax({
        type: "GET",
        url: "http://localhost...",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            populateListDropdown("gs", ix, result.Result);
        },
        error: function () { },
        timeout: 120000
    });
});

This code, regardless of the dropdown I interact with always returns a 0 for the index and I'm not sure why.

HTML if it's helpful. The page has a single row loaded at startup, and additional are added via button click.

                Select DataType :
                <select class="dataTypes"></select>


问:
Re-creating naming conventions for EF6 in EF Core
We're in the process of migrating our moderately large application from Entity Framework 6.2 to Entity Framework Core 2.0, and while many things have been easier than I had dared to hope for, I've run into a problem that I doubt I'm the first (or the thousandth) one to have, but can't find a compact solution for it: Naming conventions.

Specifically, naming conventions for relational properties.

A typical one-to-many entity pair in our application looks something like this:

```<code>public class Foo
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int FooId { get; set; }

    [Required]
    public string Bar { get; set; }

    [InverseProperty(nameof(Baz.Foo))]
    public ICollection<Baz> Bazzes { get; set; }
}

public class Baz
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int BazId { get; set; }

    [Required]
    public string Qux { get; set; }

    [Required]
    public Foo Foo { get; set; }
}
</code>```

In our existing database, EF6 mapped that to the following tables:

```<code>Foos                        Bazzes -- named after the DbSets on the DbContext
****                        ******
FooId : int                 BazId : int
Bar : nvarchar(max)         Qux : nvarchar(max)
                            Foo_FooId : int
</code>```

With the default naming conventions in EF Core, it seems that the ported context looks for a column FooId instead of Foo_FooId.

I've tried modifying this with something what's described here, but I can't figure out what condition to impose on the property metadata to only change the navigational properties. (I also have a couple of complex type, which I configure with .Entity<Owner>().OwnsOne(o => o.Owned), so the solution needs to capture that as well.)

Is there no ready-made solution to make this transition easier?

I've published an MVCE for this problem here: https://github.com/tlycken/MCVE_EfCoreNavigationalProperties

答:
AFAIK you can't change the name of the Shadow Property, but you can change the name of the table column.  Like this

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{

    base.OnModelCreating(modelBuilder);

    //modelBuilder.Model.FindEntityType(typeof(Baz)).FindProperty("FooId").Relational().ColumnName = "Foo_FooId";
    foreach( var m in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var sp in m.GetProperties().Where( p => p.IsShadowProperty ))
        {
            var fk = sp.GetContainingForeignKeys().Where(f => f.Properties.Count == 1).FirstOrDefault();
            if (fk != null && fk.PrincipalKey.Properties.Count == 1)
            {
                sp.Relational().ColumnName = fk.PrincipalEntityType.Relational().TableName + "_" + fk.PrincipalKey.Properties.Single().Relational().ColumnName;
            }
        }
    }

}
</code>```

Of course if you have a Foreign Key Property in your model, you wouldn't have to do this.

Body:
We're in the process of migrating our moderately large application from Entity Framework 6.2 to Entity Framework Core 2.0, and while many things have been easier than I had dared to hope for, I've run into a problem that I doubt I'm the first (or the thousandth) one to have, but can't find a compact solution for it: Naming conventions.

Specifically, naming conventions for relational properties.

A typical one-to-many entity pair in our application looks something like this:

public class Foo
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int FooId { get; set; }

    [Required]
    public string Bar { get; set; }

    [InverseProperty(nameof(Baz.Foo))]
    public ICollection<Baz> Bazzes { get; set; }
}

public class Baz
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int BazId { get; set; }

    [Required]
    public string Qux { get; set; }

    [Required]
    public Foo Foo { get; set; }
}

In our existing database, EF6 mapped that to the following tables:

Foos                        Bazzes -- named after the DbSets on the DbContext
****                        ******
FooId : int                 BazId : int
Bar : nvarchar(max)         Qux : nvarchar(max)
                            Foo_FooId : int

With the default naming conventions in EF Core, it seems that the ported context looks for a column FooId instead of Foo_FooId.

I've tried modifying this with something what's described here, but I can't figure out what condition to impose on the property metadata to only change the navigational properties. (I also have a couple of complex type, which I configure with .Entity<Owner>().OwnsOne(o => o.Owned), so the solution needs to capture that as well.)

Is there no ready-made solution to make this transition easier?

I've published an MVCE for this problem here: https://github.com/tlycken/MCVE_EfCoreNavigationalProperties

Body:
AFAIK you can't change the name of the Shadow Property, but you can change the name of the table column.  Like this

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

    base.OnModelCreating(modelBuilder);

    //modelBuilder.Model.FindEntityType(typeof(Baz)).FindProperty("FooId").Relational().ColumnName = "Foo_FooId";
    foreach( var m in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var sp in m.GetProperties().Where( p => p.IsShadowProperty ))
        {
            var fk = sp.GetContainingForeignKeys().Where(f => f.Properties.Count == 1).FirstOrDefault();
            if (fk != null && fk.PrincipalKey.Properties.Count == 1)
            {
                sp.Relational().ColumnName = fk.PrincipalEntityType.Relational().TableName + "_" + fk.PrincipalKey.Properties.Single().Relational().ColumnName;
            }
        }
    }

}

Of course if you have a Foreign Key Property in your model, you wouldn't have to do this.


问:
How to sort map or which traversal approach i need to follow?
i just want to get a Sorted map my code is like :

```<code>public class SubString {public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("string2");
list.add("STR_str2");
list.add("STR_str3");
getSequesce("STR_str1", list);
List<String> list1 = new ArrayList<>();
list1.add("STR_xyz");
list1.add("STR_ABC");
getSequesce("STR_str2", list1);
List<String> list3 = new ArrayList<>();
list3.add("Anukul");
list3.add("mittal");
getSequesce("STR_str3", list3);
List<String> list4 = new ArrayList<>();
list4.add("Test");
list4.add("STR_XYZ");
getSequesce("STR_ABC", list4);
List<String> list5 = new ArrayList<>();
list5.add("val");
list5.add("var");
getSequesce("STR_XYZ", list5);
List<String> list6 = new ArrayList<>();
list6.add("val6");
list6.add("valtest");
getSequesce("STR_free", list6);
List<String> list7 = new ArrayList<>();
list7.add("val6");
list7.add("STR_free");
getSequesce("STR_7", list7);

}private static void getSequesce(String string, List<String> list) {
Map<String, List<String>> map = new HashMap<>();
Map<String, List<String>> sortedMap = new TreeMap<>();
map.put(string, list);

for (Map.Entry<String, List<String> > itrMap : map.entrySet() ) {

}
}}
</code>```

In my fist call of getSequence method i have put a string "STR_str1" and a list.
i just want to add this into a map where key is STR_str1 and its value is list.
but my problem is  i have to  put STR_str2 ,and STR_str3 as key in map before STR_str1. similarly i have to put STR_ABC and STR_XYZ before STR_str2.
i just want a sortedMap from function getSequesce so that i get output like

STR_free,list6

"STR_7", list7

STR_XYZ,list5

STR_ABC,list4

STR_str3,list3

"STR_str2", list1

"STR_str1", list

if value of list start with STR_ then this STR_ must already avail in map.

position of "STR_free", list6  "STR_XYZ", list5   "STR_str3", list3   can be anywhere because they don't contain any dependency.

please help me to suggest what approach i can follow. i have data that will not create cyclic problem.
Thanks.

答: Map by definition is not sorted (The same as set) so the traversal order is not guaranteed. However there is a interface SortedMap and its implementations (Such as TreeMap). In this case your keys must implement equals() and hashcode() in a meaningful way or implement Comparable interface. In your case you use Strings as keys and String implements comparable. So you can use SortedMap </p>

Body:
i just want to get a Sorted map my code is like :

public class SubString {public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("string2");
list.add("STR_str2");
list.add("STR_str3");
getSequesce("STR_str1", list);
List<String> list1 = new ArrayList<>();
list1.add("STR_xyz");
list1.add("STR_ABC");
getSequesce("STR_str2", list1);
List<String> list3 = new ArrayList<>();
list3.add("Anukul");
list3.add("mittal");
getSequesce("STR_str3", list3);
List<String> list4 = new ArrayList<>();
list4.add("Test");
list4.add("STR_XYZ");
getSequesce("STR_ABC", list4);
List<String> list5 = new ArrayList<>();
list5.add("val");
list5.add("var");
getSequesce("STR_XYZ", list5);
List<String> list6 = new ArrayList<>();
list6.add("val6");
list6.add("valtest");
getSequesce("STR_free", list6);
List<String> list7 = new ArrayList<>();
list7.add("val6");
list7.add("STR_free");
getSequesce("STR_7", list7);

}private static void getSequesce(String string, List<String> list) {
Map<String, List<String>> map = new HashMap<>();
Map<String, List<String>> sortedMap = new TreeMap<>();
map.put(string, list);

for (Map.Entry<String, List<String> > itrMap : map.entrySet() ) {

}
}}

In my fist call of getSequence method i have put a string "STR_str1" and a list.
i just want to add this into a map where key is STR_str1 and its value is list.
but my problem is  i have to  put STR_str2 ,and STR_str3 as key in map before STR_str1. similarly i have to put STR_ABC and STR_XYZ before STR_str2.
i just want a sortedMap from function getSequesce so that i get output like

STR_free,list6

"STR_7", list7

STR_XYZ,list5

STR_ABC,list4

STR_str3,list3

"STR_str2", list1

"STR_str1", list

if value of list start with STR_ then this STR_ must already avail in map.

position of "STR_free", list6  "STR_XYZ", list5   "STR_str3", list3   can be anywhere because they don't contain any dependency.

please help me to suggest what approach i can follow. i have data that will not create cyclic problem.
Thanks.


问:
PyPlot and Jupyter Notebook: dynamic update
Note: this is not about "animating" charts; rather, updating and extending the data of the plot.

I have seen a lot of PyPlot S.O. questions about how to update PyPlot in a loop, but many of these answers either outdated, or beyond the simplicity I seek.

The closest example I have seen is this:

```<code>import pylab as pl
from IPython import display
for i in range(10):
    pl.plot(pl.randn(100))
    display.clear_output(wait=True)
    display.display(pl.gcf())
</code>```

but it plots new data on top of the old at each loop iteration and when finished, produces two charts, where I only want one.

So lets say I have two lines:

```<code>l1 = [i for i in range(10)]
l2 = [i^2 for i in range(10)]
</code>```

and I am going to add new data to each line at each loop iteration:

```<code>for i in range(11, 20):
    l1.append(i)
    l2.append(i^2)
</code>```

all I want is to see a single plot that is showing the updated lines.

some posts suggest using the set_ydata function of a subplot, but this doesnt seem to work for me. Example from https://stackoverflow.com/a/4098938/5623899

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)

# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

for phase in np.linspace(0, 10*np.pi, 500):
    line1.set_ydata(np.sin(x + phase))
    fig.canvas.draw()
</code>```

only produces the plot once the entire thing is done.

changing that example towards the one I postulated fails

```<code>l1 = [i for i in range(10)]
l2 = [i^2 for i in range(10)]
print([i^2 for i in range(10)])
print(l2)
import pylab as pl
from IPython import display

fig = plt.figure()
ax = fig.add_subplot(111)

line1 = ax.plot(l1)
line2 = ax.plot(l2)

for i in range(11, 20):

    l1.append(i)
    l2.append(i^2)

    line1.set_ydata(l1)
    line2.set_ydata(l2)

    fig.canvas.draw()
</code>```

as having only a singluar array in plt.plot(arr) results in the method set_ydata not being present.

so how do I do this?

答:
I don't know why people have reopened this question, but it is of course still a duplicate of Animation in iPython notebook. Just claiming not to want an animation does not mean that it is not an animation that is asked for here. The answers there give several options, and yes using display will result in the last frame being outputted twice if run in a single cell; other solutions dont have this problem - so it would be wise to use any of the other solutions.

Just to correct the example here for what is mentionned in the comments (plt.gca().clear()):

```<code>import pylab as pl
from IPython import display
for i in range(10):
    pl.plot(pl.randn(100))
    display.clear_output(wait=True)
    display.display(pl.gcf())
    plt.gca().clear()
</code>```

Body:
Note: this is not about "animating" charts; rather, updating and extending the data of the plot.

I have seen a lot of PyPlot S.O. questions about how to update PyPlot in a loop, but many of these answers either outdated, or beyond the simplicity I seek.

The closest example I have seen is this:

import pylab as pl
from IPython import display
for i in range(10):
    pl.plot(pl.randn(100))
    display.clear_output(wait=True)
    display.display(pl.gcf())

but it plots new data on top of the old at each loop iteration and when finished, produces two charts, where I only want one.

So lets say I have two lines:

l1 = [i for i in range(10)]
l2 = [i^2 for i in range(10)]

and I am going to add new data to each line at each loop iteration:

for i in range(11, 20):
    l1.append(i)
    l2.append(i^2)

all I want is to see a single plot that is showing the updated lines.

some posts suggest using the set_ydata function of a subplot, but this doesnt seem to work for me. Example from https://stackoverflow.com/a/4098938/5623899

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)

# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

for phase in np.linspace(0, 10*np.pi, 500):
    line1.set_ydata(np.sin(x + phase))
    fig.canvas.draw()

only produces the plot once the entire thing is done.

changing that example towards the one I postulated fails

l1 = [i for i in range(10)]
l2 = [i^2 for i in range(10)]
print([i^2 for i in range(10)])
print(l2)
import pylab as pl
from IPython import display

fig = plt.figure()
ax = fig.add_subplot(111)

line1 = ax.plot(l1)
line2 = ax.plot(l2)

for i in range(11, 20):

    l1.append(i)
    l2.append(i^2)

    line1.set_ydata(l1)
    line2.set_ydata(l2)

    fig.canvas.draw()

as having only a singluar array in plt.plot(arr) results in the method set_ydata not being present.

so how do I do this?

Body:
I don't know why people have reopened this question, but it is of course still a duplicate of Animation in iPython notebook. Just claiming not to want an animation does not mean that it is not an animation that is asked for here. The answers there give several options, and yes using display will result in the last frame being outputted twice if run in a single cell; other solutions dont have this problem - so it would be wise to use any of the other solutions.

Just to correct the example here for what is mentionned in the comments (plt.gca().clear()):

import pylab as pl
from IPython import display
for i in range(10):
    pl.plot(pl.randn(100))
    display.clear_output(wait=True)
    display.display(pl.gcf())
    plt.gca().clear()