问:
getYear(), getMonth(), getDay are deprecated in Calendar, what to use then?
I want to parse a date from a string and set it in the DatePickerDialog:

```<code>try {
    myCalendar.setTime(mySimpleFormatter.parse(jsonObj.getString("dob")));
} catch (ParseException e) {
    System.out.println("!!!");
}

myEditBox.setText(mySimpleFormatter.format(myCalendar.getTime()));
myDatePickerDialog.getDatePicker().updateDate(myCalendar.getTime().getYear()); // depricated
</code>```

But the issue is that myCalendar.getTime().getYear(), getMonth(), getDay are deprecated. What should be used then?

答:
```<code>Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int day= cal.get(Calendar.DAY_OF_MONTH);
</code>```

Body:
I want to parse a date from a string and set it in the DatePickerDialog:

try {
    myCalendar.setTime(mySimpleFormatter.parse(jsonObj.getString("dob")));
} catch (ParseException e) {
    System.out.println("!!!");
}

myEditBox.setText(mySimpleFormatter.format(myCalendar.getTime()));
myDatePickerDialog.getDatePicker().updateDate(myCalendar.getTime().getYear()); // depricated

But the issue is that myCalendar.getTime().getYear(), getMonth(), getDay are deprecated. What should be used then?


来源: stackexchange

问:
Python import from parent directory
I have the following:

```<code>         ModuleFolder
              |
              |-->. ModuleFile.py .
              |
              '-->. TestsFolder .
                         |
                         '---> UnitTest1.py
</code>```

I'm trying to import from the parent directory.  In this case I am trying to run "UnitTest1.py" from the test folder, and import from the directory immediately above it (the file "ModuleFile.py").

I know there are plenty of answers to this already.  SO Question1, SO Question2, Every Other SO Question.  I just couldn't find "using ../" as a relative import rather than the explicit path.

I know that as of Python 2.5 they supported "relative imports" as per the documentation that mentions the use of from .. import * but I am specifically trying to do an import MyModuleName so I can be more explicit in the unittest and avoid mangling/collisions of names.

What I am doing (and it is working for me) is the following:

```<code>sys.path.append("../")
</code>```

And then importing what I need from the parent directory.

Yes, there is an __init__.py in the parent directory,

No, my parent path is not part of the Python path or environment variable

Why don't I just add the parent path to the sys.path?  Because it's relative.  If I am running from /home/workspace/MyModule/unittests/ and my module is under /home/workspace/MyModule/ I assumed adding /home/workspace/MyModule/ to the path won't necessarily be true if a coworker runs this on his machine under his own directory of /home/documents/MyModule.

My Question:

Is this Python-proper?  If not, what's wrong with this.  Is there a better way?  Or is this truly an RTFM moment where the answer is in one of the 7+ SO questions I've already looked at?  (I saw those all recommending the explicit path rather than the relative path approach I took).

Other useful information:

Python 2.6

Working in Linux but could just as easily jump over to Win.

答:
You can also make symlink of the module path which you want to import and then use that symlink to import. Create a symlink in the python dist-packages.

To create a symlink:

ln -s "/path/to/ModuleFolder" "/path/to/python/dist/packages/module_symlink_name"

To import module in the script:

```<code>from module_symlink_name import ModuleFile
</code>```

No need to export python path or modifying sys path.

ContentLicense: CC BY-SA 3.0

Title: Python import from parent directory

Body:
I have the following:

         ModuleFolder
              |
              |-->. ModuleFile.py .
              |
              '-->. TestsFolder .
                         |
                         '---> UnitTest1.py

I'm trying to import from the parent directory.  In this case I am trying to run "UnitTest1.py" from the test folder, and import from the directory immediately above it (the file "ModuleFile.py").

I know there are plenty of answers to this already.  SO Question1, SO Question2, Every Other SO Question.  I just couldn't find "using ../" as a relative import rather than the explicit path.

I know that as of Python 2.5 they supported "relative imports" as per the documentation that mentions the use of from .. import * but I am specifically trying to do an import MyModuleName so I can be more explicit in the unittest and avoid mangling/collisions of names.

What I am doing (and it is working for me) is the following:

sys.path.append("../")

And then importing what I need from the parent directory.

Yes, there is an __init__.py in the parent directory,

No, my parent path is not part of the Python path or environment variable

Why don't I just add the parent path to the sys.path?  Because it's relative.  If I am running from /home/workspace/MyModule/unittests/ and my module is under /home/workspace/MyModule/ I assumed adding /home/workspace/MyModule/ to the path won't necessarily be true if a coworker runs this on his machine under his own directory of /home/documents/MyModule.

My Question:

Is this Python-proper?  If not, what's wrong with this.  Is there a better way?  Or is this truly an RTFM moment where the answer is in one of the 7+ SO questions I've already looked at?  (I saw those all recommending the explicit path rather than the relative path approach I took).

Other useful information:

Python 2.6

Working in Linux but could just as easily jump over to Win.

Body:
You can also make symlink of the module path which you want to import and then use that symlink to import. Create a symlink in the python dist-packages.

To create a symlink:

ln -s "/path/to/ModuleFolder" "/path/to/python/dist/packages/module_symlink_name"

To import module in the script:

from module_symlink_name import ModuleFile

No need to export python path or modifying sys path.


问:
C# rounding differently depending on platform?
I have this tiny piece of code

```<code>double s = -2.6114289999999998;
double s7 = Math.Round(s, 7);
double s5 = Math.Round(s, 5);
double s6 = Math.Round(s, 6);
</code>```

With Platform = Any CPU, I get

```<code>s7: -2.611429
s5: -2.61143
s6: -2.611429
</code>```

With Platform = x64, I get

```<code>s7: -2.6114289999999998
s5: -2.61143
s6: -2.6114289999999998
</code>```

Why? (Output copied from VS's Locals window)

The whole piece of code is:

```<code>    private void btnAlign_Click(object sender, EventArgs e)
    {
        double s = -2.6114289999999998;
        double s7 = Math.Round(s, 7);
        double s5 = Math.Round(s, 5);
        double s6 = Math.Round(s, 6);
    }
</code>```

答:
Answered here : https://stackoverflow.com/a/19978623/4891523

x64 managed code will use SSE for double/float computation instead of
  x87 FPU when using x86 managed code.

Body:
I have this tiny piece of code

double s = -2.6114289999999998;
double s7 = Math.Round(s, 7);
double s5 = Math.Round(s, 5);
double s6 = Math.Round(s, 6);

With Platform = Any CPU, I get

s7: -2.611429
s5: -2.61143
s6: -2.611429

With Platform = x64, I get

s7: -2.6114289999999998
s5: -2.61143
s6: -2.6114289999999998

Why? (Output copied from VS's Locals window)

The whole piece of code is:

    private void btnAlign_Click(object sender, EventArgs e)
    {
        double s = -2.6114289999999998;
        double s7 = Math.Round(s, 7);
        double s5 = Math.Round(s, 5);
        double s6 = Math.Round(s, 6);
    }


问:
A Better way to rename XAML file class when renaming the file?
EDIT: The main issue when renaming the file is to rename xaml contents

My intuition is screaming that there is a better way to do this, but the following works, my question is to see if there a better or an already existing method that can do this

I have a small WPF app that loads xaml files and can be imported/edited and exported.
When the WPF app initialises it makes a placeholder xaml file that you can edit,
"StartingXamlFile.xaml" when exporting I used a SaveFileDialog and the user can change the name. But the contents of the XAML file is not changed according to the file name. Also when importing an existing XAMLfile then editing and exporting(changing name when exporting) the same thing occurs.

Solution:

I set up a Singleton object to hold the file name XamlFile with property content and path. Now the default is set to "StartingXamlFile" when importing this is replaced. This is done following Gang of four Singleton technique

SaveFile code that doesnt work:

```<code> SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = "StartingXamlFile"; // Default file name
            dlg.DefaultExt = ".xaml"; // Default file extension
            dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*"; // Filter files by extension

            // Show save file dialog box
            var result = dlg.ShowDialog();
            if (result == true)
            {
                File.WriteAllText(dlg.FileName, editedContent);
            }
</code>```

Save File code that does work using Replace:

```<code>if (result == true)
            {
                var name = Path.GetFileNameWithoutExtension(dlg.FileName);
                var testing = XamlFile.Content.Replace(XamlFile.Path,name);
                File.WriteAllText(dlg.FileName, testing);
            }
</code>```

答:
Just to give this question an accepted answer, I have not found a better way to this other than:

```<code>SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = "StartingXamlFile"; // Default file name
            dlg.DefaultExt = ".xaml"; // Default file extension
            dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*";

            // Show save file dialog box
            var result = dlg.ShowDialog();
            if (result == true)
            {
        //X:Class replacement is done here
               var name = Path.GetFileNameWithoutExtension(dlg.FileName);
               var testing = XamlFile.Content.Replace(XamlFile.Path,name);
               File.WriteAllText(dlg.FileName, testing);
            }
</code>```

XamlFile is a singleton object that contains the content of the xaml
and initial name of file when starting up or importing, so when you export it
replaces all references to the initial name

Body:
EDIT: The main issue when renaming the file is to rename xaml contents

My intuition is screaming that there is a better way to do this, but the following works, my question is to see if there a better or an already existing method that can do this

I have a small WPF app that loads xaml files and can be imported/edited and exported.
When the WPF app initialises it makes a placeholder xaml file that you can edit,
"StartingXamlFile.xaml" when exporting I used a SaveFileDialog and the user can change the name. But the contents of the XAML file is not changed according to the file name. Also when importing an existing XAMLfile then editing and exporting(changing name when exporting) the same thing occurs.

Solution:

I set up a Singleton object to hold the file name XamlFile with property content and path. Now the default is set to "StartingXamlFile" when importing this is replaced. This is done following Gang of four Singleton technique

SaveFile code that doesnt work:

 SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = "StartingXamlFile"; // Default file name
            dlg.DefaultExt = ".xaml"; // Default file extension
            dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*"; // Filter files by extension

            // Show save file dialog box
            var result = dlg.ShowDialog();
            if (result == true)
            {
                File.WriteAllText(dlg.FileName, editedContent);
            }

Save File code that does work using Replace:

if (result == true)
            {
                var name = Path.GetFileNameWithoutExtension(dlg.FileName);
                var testing = XamlFile.Content.Replace(XamlFile.Path,name);
                File.WriteAllText(dlg.FileName, testing);
            }

Body:
Just to give this question an accepted answer, I have not found a better way to this other than:

SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = "StartingXamlFile"; // Default file name
            dlg.DefaultExt = ".xaml"; // Default file extension
            dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*";

            // Show save file dialog box
            var result = dlg.ShowDialog();
            if (result == true)
            {
        //X:Class replacement is done here
               var name = Path.GetFileNameWithoutExtension(dlg.FileName);
               var testing = XamlFile.Content.Replace(XamlFile.Path,name);
               File.WriteAllText(dlg.FileName, testing);
            }

XamlFile is a singleton object that contains the content of the xaml
and initial name of file when starting up or importing, so when you export it
replaces all references to the initial name


问:
How to get Method object in Java without using method string names
I'm looking for a convenient workaround for getting the Method object from a method. The idea:

```<code>Method fooMethod = getMethod( new MyObject().foo() ) // returns method "foo" in MyObject
</code>```

The obvious way is to use the name of the method as a string:

```<code>Method fooMethod = MyObject.class.getMethod("foo")
</code>```

but I want to avoid this because if I rename foo() that code will stop working or I have rename the string in all the places where it is used.

The use case is that I want to use something similar to ProperyChangeListeners however those rely on the method name as string. I'd like to use the actual method (safely) and not rely on strings.

What could I use to get the method in a rename safe way?

UPDATE:
I'd like to find a pure java solution that does not rely on IDE features

答:
We have published the small library reflection-util that can be used to capture a method.

Example:

```<code>class MyClass {

    public void myMethod() {
    }

}

Method method = ClassUtils.getVoidMethod(MyClass.class, MyClass::myMethod);
System.out.println(method.getName()); // prints "myMethod"
</code>```

Implementation details: A Proxy subclass of MyClass is created with ByteBuddy and a call to the method is captured to retrieve its name.
ClassUtils caches the information such that we do not need to create a new proxy on every invocation.

Body:
I'm looking for a convenient workaround for getting the Method object from a method. The idea:

Method fooMethod = getMethod( new MyObject().foo() ) // returns method "foo" in MyObject

The obvious way is to use the name of the method as a string:

Method fooMethod = MyObject.class.getMethod("foo")

but I want to avoid this because if I rename foo() that code will stop working or I have rename the string in all the places where it is used.

The use case is that I want to use something similar to ProperyChangeListeners however those rely on the method name as string. I'd like to use the actual method (safely) and not rely on strings.

What could I use to get the method in a rename safe way?

UPDATE:
I'd like to find a pure java solution that does not rely on IDE features

Body:
We have published the small library reflection-util that can be used to capture a method.

Example:

class MyClass {

    public void myMethod() {
    }

}

Method method = ClassUtils.getVoidMethod(MyClass.class, MyClass::myMethod);
System.out.println(method.getName()); // prints "myMethod"

Implementation details: A Proxy subclass of MyClass is created with ByteBuddy and a call to the method is captured to retrieve its name.
ClassUtils caches the information such that we do not need to create a new proxy on every invocation.

ContentLicense: CC BY-SA 4.0


问:
How to add a link that would let user change their Gravatar on my site?
How do I add a link that would let user change their Gravatar on my site?
(The same way you can change your Gravatar on Wordpress)

Thanks,
Kenneth

答:
Looking at the html source on wordpress.com, it looks like they're using something like ThickBox to load the Gravatar site in an iframe:</p>

```<code><a href="https://secure.gravatar.com/accounts/force-by-email/wpcom/username/somecode?TB_iframe=true&height=475&width=960" id="gravatar_ui" class="thickbox" title="gravatar.com" onclick="return false;">
   <img src="https://secure.gravatar.com/avatar/gravatarid?s=128&r=any&time=43179786" class="no-grav">
   <p style="text-align: center;">Change your Gravatar</p>
</a>
</code>```

OwnerDisplayName: ksuralta

ContentLicense: CC BY-SA 2.5

Body:
Looking at the html source on wordpress.com, it looks like they're using something like ThickBox to load the Gravatar site in an iframe:

<a href="https://secure.gravatar.com/accounts/force-by-email/wpcom/username/somecode?TB_iframe=true&amp;height=475&amp;width=960" id="gravatar_ui" class="thickbox" title="gravatar.com" onclick="return false;">
   <img src="https://secure.gravatar.com/avatar/gravatarid?s=128&amp;r=any&amp;time=43179786" class="no-grav">
   <p style="text-align: center;">Change your Gravatar</p>
</a>


问:
EF code first many to many relation when no relation in DB
Suppose I have two classes model like:

```<code> public class AuthorityUser
{
    public string GUID { get; set; }
    public int UserID { get; set; }
    public ICollection<Authority1> Authorities { get; set; }
    public AuthorityUser()
    {
        Authorities = new HashSet<Authority1>();
    }
}
public partial class Authority1
{
    public virtual int AID
    {
        get;
        set;
    }
    public virtual ICollection<AuthorityUser> AuthorityUsers { get; set; }
    public Authority1()
    {
        AuthorityUsers = new HashSet<AuthorityUser>();
    }
}
</code>```

I am going to make Many To Many relation between them based on UserAuthorityMap connected table in DB.

so I did this to make M:N relation in OnModelCreating()

```<code>modelBuilder.Entity<AuthorityUser>().ToTable("Gainer").HasKey(x => x.UserID);
modelBuilder.Entity<Authority1>().ToTable("Authority").HasKey(x => x.AID);
modelBuilder.Entity<AuthorityUser>()
          .HasMany<Authority1>(s => s.Authorities)
          .WithMany(c => c.AuthorityUsers)
          .Map(cs =>
          {
              cs.MapLeftKey("UserID");
              cs.MapRightKey("AID");
              cs.ToTable("UserAuthorityMap");
          });
</code>```

As I mentioned in title there is no relation between them in DB so the diagram in DB is like picture below :

when I run this :

```<code>dbContext.AuthorityUsers.SingleOrDefault(x => x.UserID == 65);
</code>```

the related Authorities won't be loaded from DB.

so should I use HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) to make it right or something else?

答:
If you followed the Entity Framework Code-First conventions you wouldn't have this problem.

If you really need to use non-conventional names for your tables and your primary keys, then indeed your two ModelBuilder statements for AuthorityUser and Authority will do what you want.

However, to make your many-to-many relationship easier, reconsider your method, and make your life easier by following the entity-framework conventions for many-to-many relation

In your case this would lead to two changes:

Make AuthorityUser.Authorities virtual

Let your classes represent your tables: let it be simple POCOs: no HashSet, no Constructor.

The reason to make your table classes simple POCOs, is because the class represents a table in a database. This table has no HashSet, and if you don't need it, why limit yourself to a HashSet? (See later)

In your case the proper many-to-many without the need tell the model builder that you configured a many-to-many would be:

```<code>class AuthorityUser
{
    // Primary Key (reconsider: Id)
    public int UserID { get; set; }
    // an AuthorityUser belongs to zero or more Authorities (many-to-many)
    public virtual ICollection<Authority> Authorities { get; set; }
    ... // other properties
}
class Authority
{
    // primary key (reconsider: Id)
    public int AID {get; set;}
    // an Authority has zero or more AuthorityUsers (many-to-many)
    public virtual ICollection<AuthorityUser> AuthorityUsers { get; set; }
    ... // other users
}

class MyDbContext : DbContext
{
    public DbSet<AuthorityUser> AuthorityUsers {get; set;}
    public DbSet<Authority> Authorities {get; set;}
}
</code>```

You already understood that you need some Model Building to inform entity framework about your non-conventional primary keys and table names.

But removing the HashSet and declaring both ICollections in the many-to-many is enough for entity framework to understand that a many-to-many is intended. You don't need to do some model building for this. Enityt Framework will create a junction table and use it whenever needed.

When using the many-to-many you won't do a join with the junction table. Instead you think in collections:

Give me all AuthorityUsers that have xxx with their Authorities that have yyy

```<code>var result = dbContext.AuthorityUsers
    .Where(authorityUser => xxx)
    .Select(authorityUser => new
    {
        // take only the properties from authorityuser you'll need:
        UserId = authorityUser.UserId,
        GUID = authorityUser.GUID,

        // take all authorities from this authorityUser that have yyy
        Authorities = authorityUser.Authorities
            .Where(authority => yyy)
            .Select(authority => new
            {
                // take only the authority properties you'll use:
                AID = authority.AID,
                ...
            })
            .ToList(),
    });
}
</code>```

Entity Framework knows that this needs two joins with the junction table, and perform the proper SQL statement for you.

The query: give me all Authorities that ... with all their AuthorityUsers which ... is similar.

Is your hashset needed?

No, in all your queries, entity framework will replace the HashSet by its own virtual ICollection<...>.

Your HashSet would only be useful if you'd add a new Authority with its AuthorityUsers. Without HashSet this would be like:

```<code>Authority addedAuthority = myDbContext.Authorieties.Add(new Authority()
    {
         GUID = ...
         ... // other properties

         // this Authority has the following AuthorityUsers:
         AuthorityUsers = new List<AuthorityUsers>()
         {
              new AuthorityUser() {...},
              new AuthorityUser() {...},
              ...
         },
    });
</code>```

Instead of a List you couls assign any ICollection, like an array, or even from a Dictionary:

```<code>Dictionary<int, AuthorityUser> authorityUsers = ...
Authority addedAuthority = myDbContext.Authorieties.Add(new Authority()
    {
         ...
         // this Authority has the following AuthorityUsers:
         AuthorityUsers = authorityUsers.Values,
    });
</code>```

So you see that removing the HashSet give you more freedom to provide the ICollection: Better reusability. Less code, which makes it better understandable when someone else needs to maintain it. Besides it is a waste of processing power to create a HashSet that is most of the time not used.

Body:
Suppose I have two classes model like:

 public class AuthorityUser
{
    public string GUID { get; set; }
    public int UserID { get; set; }
    public ICollection<Authority1> Authorities { get; set; }
    public AuthorityUser()
    {
        Authorities = new HashSet<Authority1>();
    }
}
public partial class Authority1
{
    public virtual int AID
    {
        get;
        set;
    }
    public virtual ICollection<AuthorityUser> AuthorityUsers { get; set; }
    public Authority1()
    {
        AuthorityUsers = new HashSet<AuthorityUser>();
    }
}

I am going to make Many To Many relation between them based on UserAuthorityMap connected table in DB.

so I did this to make M:N relation in OnModelCreating()

modelBuilder.Entity<AuthorityUser>().ToTable("Gainer").HasKey(x => x.UserID);
modelBuilder.Entity<Authority1>().ToTable("Authority").HasKey(x => x.AID);
modelBuilder.Entity<AuthorityUser>()
          .HasMany<Authority1>(s => s.Authorities)
          .WithMany(c => c.AuthorityUsers)
          .Map(cs =>
          {
              cs.MapLeftKey("UserID");
              cs.MapRightKey("AID");
              cs.ToTable("UserAuthorityMap");
          });

As I mentioned in title there is no relation between them in DB so the diagram in DB is like picture below :

when I run this :

dbContext.AuthorityUsers.SingleOrDefault(x => x.UserID == 65);

the related Authorities won't be loaded from DB.

so should I use HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) to make it right or something else?

Body:
If you followed the Entity Framework Code-First conventions you wouldn't have this problem.

If you really need to use non-conventional names for your tables and your primary keys, then indeed your two ModelBuilder statements for AuthorityUser and Authority will do what you want.

However, to make your many-to-many relationship easier, reconsider your method, and make your life easier by following the entity-framework conventions for many-to-many relation

In your case this would lead to two changes:

Make AuthorityUser.Authorities virtual

Let your classes represent your tables: let it be simple POCOs: no HashSet, no Constructor.

The reason to make your table classes simple POCOs, is because the class represents a table in a database. This table has no HashSet, and if you don't need it, why limit yourself to a HashSet? (See later)

In your case the proper many-to-many without the need tell the model builder that you configured a many-to-many would be:

class AuthorityUser
{
    // Primary Key (reconsider: Id)
    public int UserID { get; set; }
    // an AuthorityUser belongs to zero or more Authorities (many-to-many)
    public virtual ICollection<Authority> Authorities { get; set; }
    ... // other properties
}
class Authority
{
    // primary key (reconsider: Id)
    public int AID {get; set;}
    // an Authority has zero or more AuthorityUsers (many-to-many)
    public virtual ICollection<AuthorityUser> AuthorityUsers { get; set; }
    ... // other users
}

class MyDbContext : DbContext
{
    public DbSet<AuthorityUser> AuthorityUsers {get; set;}
    public DbSet<Authority> Authorities {get; set;}
}

You already understood that you need some Model Building to inform entity framework about your non-conventional primary keys and table names.

But removing the HashSet and declaring both ICollections in the many-to-many is enough for entity framework to understand that a many-to-many is intended. You don't need to do some model building for this. Enityt Framework will create a junction table and use it whenever needed.

When using the many-to-many you won't do a join with the junction table. Instead you think in collections:

Give me all AuthorityUsers that have xxx with their Authorities that have yyy

var result = dbContext.AuthorityUsers
    .Where(authorityUser => xxx)
    .Select(authorityUser => new
    {
        // take only the properties from authorityuser you'll need:
        UserId = authorityUser.UserId,
        GUID = authorityUser.GUID,

        // take all authorities from this authorityUser that have yyy
        Authorities = authorityUser.Authorities
            .Where(authority => yyy)
            .Select(authority => new
            {
                // take only the authority properties you'll use:
                AID = authority.AID,
                ...
            })
            .ToList(),
    });
}

Entity Framework knows that this needs two joins with the junction table, and perform the proper SQL statement for you.

The query: give me all Authorities that ... with all their AuthorityUsers which ... is similar.

Is your hashset needed?

No, in all your queries, entity framework will replace the HashSet by its own virtual ICollection<...>.

Your HashSet would only be useful if you'd add a new Authority with its AuthorityUsers. Without HashSet this would be like:

Authority addedAuthority = myDbContext.Authorieties.Add(new Authority()
    {
         GUID = ...
         ... // other properties

         // this Authority has the following AuthorityUsers:
         AuthorityUsers = new List<AuthorityUsers>()
         {
              new AuthorityUser() {...},
              new AuthorityUser() {...},
              ...
         },
    });

Instead of a List you couls assign any ICollection, like an array, or even from a Dictionary:

Dictionary<int, AuthorityUser> authorityUsers = ...
Authority addedAuthority = myDbContext.Authorieties.Add(new Authority()
    {
         ...
         // this Authority has the following AuthorityUsers:
         AuthorityUsers = authorityUsers.Values,
    });

So you see that removing the HashSet give you more freedom to provide the ICollection: Better reusability. Less code, which makes it better understandable when someone else needs to maintain it. Besides it is a waste of processing power to create a HashSet that is most of the time not used.


问:
Inbound calc fields do not reference outgoing app
When trying to parse a calc field to determine the source of the incoming relationship, I realized that the calc field only returns 1) the relationship field_id which is connecting the two apps and 2) the field_id in which the data is being pulled from. Example here:

“(in_sum_153102047_153102037)“

As this doesn't provide the app_id, this causes issues as there is no cohesive way to find the app in which the field is in. This is the case as the "Get App Field" call requires an app_id parameter. If this is true, the only way to find the app in which these fields are contained is to run app-by-app on the org until you happen to run into the field_id in question. As this is both API and time intensive, I'm hoping there is a better way.

Please advise.

"Thank you"

Nate

答:
An easiest way(but not a final solution) is,

You will get the app or set of apps which are connected to the reference field.
Try iterating them to find where the field coming from.
Hope it helps.


问:
Difference in days between two dates one of which is user's input
I am writing an 'age to seconds' converter, but I keep getting various errors.

```<code>#

!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime

print ('Welcome to a simple age to seconds converter. ')

def get_date():
    print ('Please enter the year of your birth in the format YYYY, MM, DD:')
    date_of_birth = str(input())
    converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
    date_now = datetime.strftime("%Y-%m-%d")
    total_seconds = ((date_now - converted_date).days)*86400
    return ('You have lived for:', total_seconds, 'seconds.')

print (get_date())
if __name__ == "__main__":
    main()
</code>```

I think this is the most correct version of the program, but I keep getting an error TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'.

Does anyone know how I can correct that? And also how to count seconds to the precise moment of inputting the date to now?
Thanks in advance

答:
You're calling the method strftime() straight from the class, which instead should be called on a datetime instance. I've added the .now() in the code below:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime

print ('Welcome to a simple age to seconds converter. ')

def get_date():
    print ('Please enter the year of your birth in the format YYYY, MM, DD:')
    date_of_birth = str(input())
    converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
    date_now = datetime.now()
    total_seconds = ((date_now - converted_date).days)*8640000
    return ('You have lived for:', total_seconds, 'seconds.')

print (get_date())
if __name__ == "__main__":
    main()
</code>```

Edit: I just realized that the next line in your code might actually generate an error, because then a datetime instance is subtracted from a string. You might want to remove the .strftime() call entirely.

Body:
I am writing an 'age to seconds' converter, but I keep getting various errors.

#

!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime

print ('Welcome to a simple age to seconds converter. ')

def get_date():
    print ('Please enter the year of your birth in the format YYYY, MM, DD:')
    date_of_birth = str(input())
    converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
    date_now = datetime.strftime("%Y-%m-%d")
    total_seconds = ((date_now - converted_date).days)*86400
    return ('You have lived for:', total_seconds, 'seconds.')

print (get_date())
if __name__ == "__main__":
    main()

I think this is the most correct version of the program, but I keep getting an error TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'.

Does anyone know how I can correct that? And also how to count seconds to the precise moment of inputting the date to now?
Thanks in advance

Body:
You're calling the method strftime() straight from the class, which instead should be called on a datetime instance. I've added the .now() in the code below:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#This program converts your age to seconds
from datetime import datetime

print ('Welcome to a simple age to seconds converter. ')

def get_date():
    print ('Please enter the year of your birth in the format YYYY, MM, DD:')
    date_of_birth = str(input())
    converted_date = datetime.strptime(date_of_birth, '%Y, %m, %d')
    date_now = datetime.now()
    total_seconds = ((date_now - converted_date).days)*8640000
    return ('You have lived for:', total_seconds, 'seconds.')

print (get_date())
if __name__ == "__main__":
    main()

Edit: I just realized that the next line in your code might actually generate an error, because then a datetime instance is subtracted from a string. You might want to remove the .strftime() call entirely.


问:
Individual plots worked but once added subplot, nothing shows up
I am trying to put together four subplots that are made using pandas.plot() method. When plotting separately, they show up fine as below:

But once I started using subplot, it became this:

I know there might be something to do with either naming the plot objects or using pyplot instead of the pandas .plot method, but couldn't figure out after tried different things. Any hint is appreciated.

答:
You can try also in this way for example:</p>

```<code>fig = plt.figure()
ax = fig.add_subplot(221)
plt.plot(x,y)

ax = fig.add_subplot(222)
plt.plot(x,z)
...

plt.show()
</code>```

Body:
You can try also in this way for example:

fig = plt.figure()
ax = fig.add_subplot(221)
plt.plot(x,y)

ax = fig.add_subplot(222)
plt.plot(x,z)
...

plt.show()


问:
Why can't I see the mongo PID in process state list on mac
I'm using docker. so docker is a process, not a VM. to check this. So  I tried to run 'docker run --name mongo -d mongo', it works fine . then I checked the 'PID' using 'docker top mongo' it return the 'PID' details. then i tried 'ps aux' to see all process states. but I cannot see that mongo 'PID' in the list. why is that. I'm using mac with newest mac os.</p>

答:
As others have mentioned, when running on MAC, Docker is actually running in the backgound inside a VM and thus you will not be able to see the container process directly.

Moreover, even if you connect to the actual VM and check the PID for mongo container it will be different from the PID reported back when you run docker top mongo.

This is due to PID namespaces that docker uses to isolate processes running inside the docker container. So don't rely on the PID to detect the process.


问:
Fluent NHibernate and class with indexer mapping
How can I map the class AttributeSet with Fluent NHibernate using a fluent mapping</p>

```<code>public class AttributeSet : DictionaryBase
{
    private readonly Dictionary<string, object> _cache;

    public AttributeSet()
    {
        _cache = new Dictionary<string, object>();
    }

    public object this[string index]
    {
        get
        {
            return _cache[index];
        }
        set
        {
            _cache[index] = value;
        }
    }
}

public class Entity
{
    protected Entity()
    {
        Attributes = new AttributeSet();
    }

    public virtual int Id { get; set; }
    public virtual string Label { get; set; }
    public virtual string Description { get; set; }
    public virtual DateTime CreatedDate { get; set; }

    public virtual AttributeSet Attributes { get; set; }
}
</code>```

答:
I don't think there's a way to map your indexer directly, but you can expose the underlying dictionary type and map that instead.

If you don't want to expose the dictionary as public you can map it as a private property instead as explained here. For mapping a dictionary, see here.

An example might be

```<code>HasMany<object>(Reveal.Member<AttributeSet>("Cache"))
    .KeyColumn("AttributeSetId")
    .AsMap<string>(idx => idx.Column("Index"), elem => elem.Column("Value"))
    .Access.CamelCaseField(Prefix.Underscore)
</code>```

Mapping the object type in the dictionary might be interesting, I don't know if NHibernate will be able to translate it directly to an underlying database type.

Body:
How can I map the class AttributeSet with Fluent NHibernate using a fluent mapping

public class AttributeSet : DictionaryBase
{
    private readonly Dictionary<string, object> _cache;

    public AttributeSet()
    {
        _cache = new Dictionary<string, object>();
    }

    public object this[string index]
    {
        get
        {
            return _cache[index];
        }
        set
        {
            _cache[index] = value;
        }
    }
}

public class Entity
{
    protected Entity()
    {
        Attributes = new AttributeSet();
    }

    public virtual int Id { get; set; }
    public virtual string Label { get; set; }
    public virtual string Description { get; set; }
    public virtual DateTime CreatedDate { get; set; }

    public virtual AttributeSet Attributes { get; set; }
}

Body:
I don't think there's a way to map your indexer directly, but you can expose the underlying dictionary type and map that instead.

If you don't want to expose the dictionary as public you can map it as a private property instead as explained here. For mapping a dictionary, see here.

An example might be

HasMany<object>(Reveal.Member<AttributeSet>("Cache"))
    .KeyColumn("AttributeSetId")
    .AsMap<string>(idx => idx.Column("Index"), elem => elem.Column("Value"))
    .Access.CamelCaseField(Prefix.Underscore)

Mapping the object type in the dictionary might be interesting, I don't know if NHibernate will be able to translate it directly to an underlying database type.


问:
Algorithm: Looking for ideas for 'Favorite Color' sorter
I've been puzzling over this problem for a while now, and can't seem to come up with a good solution. I'd love to hear peoples thoughts (or if someone knows of an existing solution) Let me describe the problem.

The end goal is to find the overall 'favorite color' in the data set after running our algorithm and sorting the results.

Say we allow users to vote on their favorite color. For the example we have blue, red, green, and yellow. We let users vote not on their overall favorite, but on their favorite out of two colors. (eg. red over blue)

Over time our data might look like this: (numbers in braces being the amount of votes that color has)

Red (7) vs Blue (2)

Red (6) vs Green (3)

Red (3) vs Yellow (4)

Blue (3) vs Green (5)

Blue (4) vs Yellow (4)

Green (1) vs Yellow (5)

I assume that we would need to assign a 'confidence' score to each pairing describing how sure we are that the result is correct. (maybe a 0 in a tie, and a 1 if we are 100% sure) I imagine we would have to take into account the overall number of votes for each pairing. For example, a pairing with only 1 vote and thus a 100% confidence score needs to be 'dampened'.

Anyways, if anyone has any ideas I'd love to hear them.

Cheers and thanks for reading.

答:
What you are looking for is a method for finding a ranking from pairwise comparisons. ELO might be a good start. This question has also been asked for different settings in

How to rank a million images with a crowdsourced sort

and

Ranking from pairwise comparisons


问:
How to compare the same columns in different rows?
I have extracted data like below

```
Name   Session     CATEGORY   HT     WT     BMI
John   SESSION 1   OW         1.5    64.6   28.71
John   SESSION 3   OW         1.52   63.2   27.35
Eric   SESSION 1   OW         1.48   55.7   25.43
Eric   SESSION 3   OW         1.52   55.4   23.98
```

I would want it in the below format

```
Name  session_1_Category  Session_1_height  session_1_weight  session_1_BMI  session_3_Category  Session_3_height  session_3_weight  session_3_BMI
John  OW                  1.5               64.6              28.71          OW                  1.52              63.2              27.35
Eric  OW                  1.48              55.7              25.43          OW                  1.52              55.4              23.98
```

I'm using oracle database. Please help me with a SQL query to extract data in the above format.

答:
In Oracle, you can use PIVOT:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE TABLE_NAME ( Name, "Session", CATEGORY, HT, WT, BMI ) AS
SELECT 'John', 'SESSION 1', 'OW', 1.5,  64.6, 28.71 FROM DUAL UNION ALL
SELECT 'John', 'SESSION 3', 'OW', 1.52, 63.2, 27.35 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 1', 'OW', 1.48, 55.7, 25.43 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 3', 'OW', 1.52, 55.4, 23.98 FROM DUAL;
</code>```

Query 1:

```<code>SELECT *
FROM   table_name
PIVOT(
  MAX( HT ) AS height,
  MAX( WT ) AS weight,
  MAX( BMI ) AS BMI
  FOR "Session" IN (
    'SESSION 1' AS Session_1,
    'SESSION 3' AS Session_3
  )
)
</code>```

Results:

```<code>| NAME | CATEGORY | SESSION_1_HEIGHT | SESSION_1_WEIGHT | SESSION_1_BMI | SESSION_3_HEIGHT | SESSION_3_WEIGHT | SESSION_3_BMI |
|------|----------|------------------|------------------|---------------|------------------|------------------|---------------|
| John |       OW |              1.5 |             64.6 |         28.71 |             1.52 |             63.2 |         27.35 |
| Eric |       OW |             1.48 |             55.7 |         25.43 |             1.52 |             55.4 |         23.98 |
</code>```

Body:
I have extracted data like below

Name   Session     CATEGORY   HT     WT     BMI
John   SESSION 1   OW         1.5    64.6   28.71
John   SESSION 3   OW         1.52   63.2   27.35
Eric   SESSION 1   OW         1.48   55.7   25.43
Eric   SESSION 3   OW         1.52   55.4   23.98

I would want it in the below format

Name  session_1_Category  Session_1_height  session_1_weight  session_1_BMI  session_3_Category  Session_3_height  session_3_weight  session_3_BMI
John  OW                  1.5               64.6              28.71          OW                  1.52              63.2              27.35
Eric  OW                  1.48              55.7              25.43          OW                  1.52              55.4              23.98

I'm using oracle database. Please help me with a SQL query to extract data in the above format.

Body:
In Oracle, you can use PIVOT:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE TABLE_NAME ( Name, "Session", CATEGORY, HT, WT, BMI ) AS
SELECT 'John', 'SESSION 1', 'OW', 1.5,  64.6, 28.71 FROM DUAL UNION ALL
SELECT 'John', 'SESSION 3', 'OW', 1.52, 63.2, 27.35 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 1', 'OW', 1.48, 55.7, 25.43 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 3', 'OW', 1.52, 55.4, 23.98 FROM DUAL;

Query 1:

SELECT *
FROM   table_name
PIVOT(
  MAX( HT ) AS height,
  MAX( WT ) AS weight,
  MAX( BMI ) AS BMI
  FOR "Session" IN (
    'SESSION 1' AS Session_1,
    'SESSION 3' AS Session_3
  )
)

Results:

| NAME | CATEGORY | SESSION_1_HEIGHT | SESSION_1_WEIGHT | SESSION_1_BMI | SESSION_3_HEIGHT | SESSION_3_WEIGHT | SESSION_3_BMI |
|------|----------|------------------|------------------|---------------|------------------|------------------|---------------|
| John |       OW |              1.5 |             64.6 |         28.71 |             1.52 |             63.2 |         27.35 |
| Eric |       OW |             1.48 |             55.7 |         25.43 |             1.52 |             55.4 |         23.98 |


问:
WSO2 IS - OAuth 2 curl request fails
I'm using WSO2 IS 5.0 to authorise users using OAuth2. I created a new service provider and followed instructions in http://blog.facilelogin.com/2012/08/testing-wso2-identity-server-oauth-20.html to send a curl request to IS with password grant type

Here is the curl request I sent. What could be the reason for that?

```<code>curl --user mb_tEpcov21kFKUcz5kfstwViB4a:zlmpUy4fQwR5XJ0CjuLIprVMv8Aa  -k -d "grant_type=password&username=admin&password=nt-Type:application/x-www-form-urlencoded"  https://localhost:9443/oauth2/token
</code>```

Then I received following error as the response

```<code><html><head><title>Apache Tomcat/7.0.34 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - Servlet.init() for servlet OAuth2Endpoints threw exception</h1><HR size="1" noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b> <u>Servlet.init() for servlet OAuth2Endpoints threw exception</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b> ```javax.servlet.ServletException: Servlet.init() for servlet OAuth2Endpoints threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
```

<p></p><p><b>root cause</b> ```org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokEP': Cannot resolve reference to bean 'authzEndpointBean' while setting bean property 'serviceBeans' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authzEndpointBean' defined in URL [jndi:/localhost/oauth2/WEB-INF/cxf-servlet.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/wso2/carbon/identity/oauth/cache/UserAttributesCacheKey
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)
```</p><p><b>root cause</b> ```org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authzEndpointBean' defined in URL [jndi:/localhost/oauth2/WEB-INF/cxf-servlet.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/wso2/carbon/identity/oauth/cache/UserAttributesCacheKey
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:964)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)
```</p><p><b>root cause</b> ```java.lang.NoClassDefFoundError: org/wso2/carbon/identity/oauth/cache/UserAttributesCacheKey
    java.lang.Class.getDeclaredConstructors0(Native Method)
    java.lang.Class.privateGetDeclaredConstructors(Class.java:2413)
    java.lang.Class.getConstructor0(Class.java:2723)
    java.lang.Class.getDeclaredConstructor(Class.java:2004)
    org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:65)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:957)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)
```</p><p><b>root cause</b> ```java.lang.ClassNotFoundException: org.wso2.carbon.identity.oauth.cache.UserAttributesCacheKey
    org.wso2.carbon.webapp.mgt.loader.CarbonWebappClassLoader.loadClass(CarbonWebappClassLoader.java:138)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    java.lang.Class.getDeclaredConstructors0(Native Method)
    java.lang.Class.privateGetDeclaredConstructors(Class.java:2413)
    java.lang.Class.getConstructor0(Class.java:2723)
    java.lang.Class.getDeclaredConstructor(Class.java:2004)
    org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:65)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:957)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)
```

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.

Apache Tomcat/7.0.34

答:
you can try with:

curl -v -X POST --basic -u : -H 'Content-Type: application/x-www-form-urlencoded;charset=UTF-8' -k -d 'grant_type=client_credentials&scope=openid' https://localhost:port/oauth2/token

Title: WSO2 IS - OAuth 2 curl request fails

Body:
I'm using WSO2 IS 5.0 to authorise users using OAuth2. I created a new service provider and followed instructions in http://blog.facilelogin.com/2012/08/testing-wso2-identity-server-oauth-20.html to send a curl request to IS with password grant type

Here is the curl request I sent. What could be the reason for that?

curl --user mb_tEpcov21kFKUcz5kfstwViB4a:zlmpUy4fQwR5XJ0CjuLIprVMv8Aa  -k -d "grant_type=password&username=admin&password=nt-Type:application/x-www-form-urlencoded"  https://localhost:9443/oauth2/token

Then I received following error as the response

<title>Apache Tomcat/7.0.34 - Error report</title>
HTTP Status 500 - Servlet.init() for servlet OAuth2Endpoints threw exception

type Exception report

message Servlet.init() for servlet OAuth2Endpoints threw exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception
javax.servlet.ServletException: Servlet.init() for servlet OAuth2Endpoints threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)

root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokEP': Cannot resolve reference to bean 'authzEndpointBean' while setting bean property 'serviceBeans' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authzEndpointBean' defined in URL [jndi:/localhost/oauth2/WEB-INF/cxf-servlet.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/wso2/carbon/identity/oauth/cache/UserAttributesCacheKey
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)

root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authzEndpointBean' defined in URL [jndi:/localhost/oauth2/WEB-INF/cxf-servlet.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/wso2/carbon/identity/oauth/cache/UserAttributesCacheKey
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:964)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)

root cause
java.lang.NoClassDefFoundError: org/wso2/carbon/identity/oauth/cache/UserAttributesCacheKey
    java.lang.Class.getDeclaredConstructors0(Native Method)
    java.lang.Class.privateGetDeclaredConstructors(Class.java:2413)
    java.lang.Class.getConstructor0(Class.java:2723)
    java.lang.Class.getDeclaredConstructor(Class.java:2004)
    org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:65)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:957)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)

root cause
java.lang.ClassNotFoundException: org.wso2.carbon.identity.oauth.cache.UserAttributesCacheKey
    org.wso2.carbon.webapp.mgt.loader.CarbonWebappClassLoader.loadClass(CarbonWebappClassLoader.java:138)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    java.lang.Class.getDeclaredConstructors0(Native Method)
    java.lang.Class.privateGetDeclaredConstructors(Class.java:2413)
    java.lang.Class.getConstructor0(Class.java:2723)
    java.lang.Class.getDeclaredConstructor(Class.java:2004)
    org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:65)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:957)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:910)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:484)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
    org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:153)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1327)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1085)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:516)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    org.apache.cxf.transport.servlet.CXFServlet.createSpringContext(CXFServlet.java:160)
    org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:74)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:71)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.

Apache Tomcat/7.0.34


问:
Symfony best pratice
I'm using symfony 3.3 and I want to know what is the best practice for these cases :

on render() for display template

```<code>- folder:view.html.twig
- folder/view.html.twig
- @folder...
</code>```

on getRepository()

```<code>- 'AppBundle:EntityName'
- Entityname::class
</code>```

on formtype

```<code>$resolver->setDefaults(array(
    'data_class' => EntityName::class
));
</code>```

or

```<code>$resolver->setDefaults(array(
    'data_class' => 'AppBundle\Entity\EntityName'
));
</code>```

on formtype like entitytype

```<code>   ->add(
        'words',
        EntityType::class,
        array(
            'class'        => Word::class,
        )
    )
</code>```

or

```<code>   ->add(
        'words',
        EntityType::class,
        array(
            'class'        => 'AppBundle\Entity\Word',
        )
    )
</code>```

On controller Action()

```<code>newAction(EntityManagerInterface $em)
</code>```

or

```<code>    public function newAction()
    {
        $em = $this->getDoctrine()->getManager();
    }
</code>```

I have read the best practice on symfony website but I have not see those informations.

答:
"Extraction is better than abstraction"

That's why I choose:

Class names defined by operator :: like EntityName :: class

Physical paths like Folder/view.html

Dependency Injection rather than the Service locator pattern or deep diving for a dependency.

For example: I can rely on the IDE to not let me go wrong in the definition of an absolute class name. I can use native functions for validation and path transformations.

Generalizing. I always try to avoid domain dependencies other than native.

This is my practice and it's not related only to the great Symfony.

Title: Symfony best pratice

Body:
I'm using symfony 3.3 and I want to know what is the best practice for these cases :

on render() for display template

- folder:view.html.twig
- folder/view.html.twig
- @folder...

on getRepository()

- 'AppBundle:EntityName'
- Entityname::class

on formtype

$resolver->setDefaults(array(
    'data_class' => EntityName::class
));

or

$resolver->setDefaults(array(
    'data_class' => 'AppBundle\Entity\EntityName'
));

on formtype like entitytype

   ->add(
        'words',
        EntityType::class,
        array(
            'class'        => Word::class,
        )
    )

or

   ->add(
        'words',
        EntityType::class,
        array(
            'class'        => 'AppBundle\Entity\Word',
        )
    )

On controller Action()

newAction(EntityManagerInterface $em)

or

    public function newAction()
    {
        $em = $this->getDoctrine()->getManager();
    }

I have read the best practice on symfony website but I have not see those informations.


问:
How to embed matplotlib graph into popup window using python Tkinter
I have a tkinter program that displays a matplotlib graph when I initially run it. I am having trouble, however, embedding a second matplotlib plot in my other popup window.

Ideally I want to be able to click a button and have a window with a matplotlib in it appear.

```<code>from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import Tkinter as Tk

class Window():
    def __init__(self, master):
        self.master = master
        self.frame = Tk.Frame(master)
        self.button1 = Tk.Button(self.master, text = 'Open Graph Window', width = 25,command= self.new_window)
        self.button1.pack()
        self.f = Figure( figsize=(7, 6), dpi=80 )
        self.ax0 = self.f.add_axes( (0.05, .05, .50, .50), axisbg=(.75,.75,.10), frameon=True)
        self.ax0.plot(np.max(np.random.rand(100,10)*10,axis=1),"r-")

        self.frame = Tk.Frame(root)
        self.frame.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)

        self.canvas = FigureCanvasTkAgg(self.f, master=self.frame)
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self.canvas.show()

    def new_window(self):
        self.newWindow = Tk.Toplevel(self.master)
        self.app = Graph(self.newWindow)

class Graph():
    def __init__(self, master):
        self.master = master
        self.frame = Tk.Frame(master)
        self.f1 = Figure( figsize=(10, 9), dpi=80 )
        self.ax10 = self.f1.add_axes( (0.05, .05, .50, .50), axisbg=(.75,.75,.10), frameon=True)
        self.ax10.plot(np.max(np.random.rand(100,10)*10,axis=1),"r-")
        self.quitButton = Tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.canvas = FigureCanvasTkAgg(self.f1, master=self.master)
        self.canvas.show()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

if __name__ == '__main__':
    root = Tk.Tk()
    app = Window(root)
    root.title( "MatplotLib with Tkinter" )
    root.update()
    root.deiconify()
    root.mainloop()
</code>```

I have the code I thought should work in place to generate another matplotlib graph when I open another window. This doesnt work however.
What can I do to get the second graph to appear when I click on the 'open window button'?

Any help would be greatly appreciated

答:
You have just forgotten to pack the canvas in the Graph class. Add the line

```<code>self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
</code>```

in the __init__ method of Graph, and the graph should show up in the toplevel.

Body:
I have a tkinter program that displays a matplotlib graph when I initially run it. I am having trouble, however, embedding a second matplotlib plot in my other popup window.

Ideally I want to be able to click a button and have a window with a matplotlib in it appear.

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import Tkinter as Tk

class Window():
    def __init__(self, master):
        self.master = master
        self.frame = Tk.Frame(master)
        self.button1 = Tk.Button(self.master, text = 'Open Graph Window', width = 25,command= self.new_window)
        self.button1.pack()
        self.f = Figure( figsize=(7, 6), dpi=80 )
        self.ax0 = self.f.add_axes( (0.05, .05, .50, .50), axisbg=(.75,.75,.10), frameon=True)
        self.ax0.plot(np.max(np.random.rand(100,10)*10,axis=1),"r-")

        self.frame = Tk.Frame(root)
        self.frame.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)

        self.canvas = FigureCanvasTkAgg(self.f, master=self.frame)
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self.canvas.show()

    def new_window(self):
        self.newWindow = Tk.Toplevel(self.master)
        self.app = Graph(self.newWindow)

class Graph():
    def __init__(self, master):
        self.master = master
        self.frame = Tk.Frame(master)
        self.f1 = Figure( figsize=(10, 9), dpi=80 )
        self.ax10 = self.f1.add_axes( (0.05, .05, .50, .50), axisbg=(.75,.75,.10), frameon=True)
        self.ax10.plot(np.max(np.random.rand(100,10)*10,axis=1),"r-")
        self.quitButton = Tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.canvas = FigureCanvasTkAgg(self.f1, master=self.master)
        self.canvas.show()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

if __name__ == '__main__':
    root = Tk.Tk()
    app = Window(root)
    root.title( "MatplotLib with Tkinter" )
    root.update()
    root.deiconify()
    root.mainloop()

I have the code I thought should work in place to generate another matplotlib graph when I open another window. This doesnt work however.
What can I do to get the second graph to appear when I click on the 'open window button'?

Any help would be greatly appreciated

Body:
You have just forgotten to pack the canvas in the Graph class. Add the line

self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

in the __init__ method of Graph, and the graph should show up in the toplevel.


问:
Execute code just before onComplete() in RxJava 2?
I need to close socket connection in my observable before RxLifecycle dispose it. How can I do that?

答:
one can try this too in case if you're iterating objects using filter and map for combining result.</p>

```<code>.doOnTerminate(() -> Log.d(LOGGER, "terminated"))
</code>```

Body:
one can try this too in case if you're iterating objects using filter and map for combining result.

.doOnTerminate(() -> Log.d(LOGGER, "terminated"))