问:
App Engine Query Users
I have the User model in my datastore which contains some attributes:

I need to query all users filtering by the company attribute.

So, as I would normally do, I do this:

```<code>from webapp2_extras.appengine.auth.models import User

employees = User.query().filter(User.company == self.company_name).fetch()
</code>```

This gives me:

AttributeError: type object 'User' has no attribute 'company'

And when I do:

```<code>employees = User.query().filter().fetch()
</code>```

It gives me no error and shows the list with all the Users.

How do I query by field? Thanks

答:
Your question is a bit misdirected. You ask how to query by field, which you are already doing with correct syntax. The problem, as Jeff O'Neill noted, is your User model does not have that company field, so your query-by-field attempt results in an error. (Here is some ndb documentation that you should definitely peruse and bookmark if you haven't already.) There are three ways to remedy your missing-field problem:

Subclass the User model, as Jeff shows in his answer. This is quick and simple, and may be the best solution for what you want.

Create your own User model, completely separate from the webapp2 one. This is probably overkill for what you want, just judging from your question, because you would have to write most of your own authentication code that the webapp2 user already handles for you.

Create a new model that contains extra user information, and has a key property containing the corresponding user's key. That would look like this:

```<code>class UserProfile(ndb.Expando):
    user_key = ndb.KeyProperty(kind='User', required=True)
    company = ndb.StringProperty()
    # other possibilities: profile pic? address? etc.
</code>```

with queries like this:

```<code>from models.user_profile import UserProfile
from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb

# get the employee keys
employee_keys = UserProfile.query(UserProfile.company == company_name).fetch(keys_only=True)

# get the actual user objects
employees = ndb.get_multi(employee_keys)
</code>```

What this solution does is it separates your User model that you use for authentication (webapp2's User) from the model that holds extra user information (UserProfile). If you want to store profile pictures or other relatively large amounts of data for each user, you may find this solution works best for you.

Note: you can put your filter criteria in the .query() parentheses to simplify things (I find I rarely use the .filter() method):

```<code># long way
employees = User.query().filter(User.company == self.company_name).fetch()

# shorter way
employees = User.query(User.company == self.company_name).fetch()
</code>```

Title: App Engine Query Users

Body:
I have the User model in my datastore which contains some attributes:

I need to query all users filtering by the company attribute.

So, as I would normally do, I do this:

from webapp2_extras.appengine.auth.models import User

employees = User.query().filter(User.company == self.company_name).fetch()

This gives me:

AttributeError: type object 'User' has no attribute 'company'

And when I do:

employees = User.query().filter().fetch()

It gives me no error and shows the list with all the Users.

How do I query by field? Thanks

Body:
Your question is a bit misdirected. You ask how to query by field, which you are already doing with correct syntax. The problem, as Jeff O'Neill noted, is your User model does not have that company field, so your query-by-field attempt results in an error. (Here is some ndb documentation that you should definitely peruse and bookmark if you haven't already.) There are three ways to remedy your missing-field problem:

Subclass the User model, as Jeff shows in his answer. This is quick and simple, and may be the best solution for what you want.

Create your own User model, completely separate from the webapp2 one. This is probably overkill for what you want, just judging from your question, because you would have to write most of your own authentication code that the webapp2 user already handles for you.

Create a new model that contains extra user information, and has a key property containing the corresponding user's key. That would look like this:

class UserProfile(ndb.Expando):
    user_key = ndb.KeyProperty(kind='User', required=True)
    company = ndb.StringProperty()
    # other possibilities: profile pic? address? etc.

with queries like this:

from models.user_profile import UserProfile
from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb

# get the employee keys
employee_keys = UserProfile.query(UserProfile.company == company_name).fetch(keys_only=True)

# get the actual user objects
employees = ndb.get_multi(employee_keys)

What this solution does is it separates your User model that you use for authentication (webapp2's User) from the model that holds extra user information (UserProfile). If you want to store profile pictures or other relatively large amounts of data for each user, you may find this solution works best for you.

Note: you can put your filter criteria in the .query() parentheses to simplify things (I find I rarely use the .filter() method):

# long way
employees = User.query().filter(User.company == self.company_name).fetch()

# shorter way
employees = User.query(User.company == self.company_name).fetch()


来源: stackexchange

问:
successive errors on hadoop :failed on connection exception then com.google.protobuf.InvalidProtocolBufferException
i am trying to execute the command hadoop dfs -ls, and i got this error

```<code>Call From localhost/127.0.0.1 to yass-SATELLITE-C855-2CF:8021 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
</code>```

once i resolved i got another which is

```<code>ls: Failed on local exception: com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.; Host Details : local host is: "localhost/127.0.0.1"; destination host is: "yass-SATELLITE-C855-2CF":9000;
</code>```

and i keep in loop between this two errors

my core-site.xml

```<code><configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://yass-SATELLITE-C855-2CF:9000</value>
    </property>
</configuration>
</code>```

hdfs-site.xml

```<code><property>
        <name>dfs.replication</name>
        <value>1</value>
     </property>
<property>
        <name>dfs.safemode.threshold.pct</name>
        <value>0</value>
    </property>
  <property>
        <name>dfs.namenode.name.dir</name>
        <value>/hadoop/data/namenode</value>
    </property>
    <property>
        <name>dfs.datanode.data.dir</name>
        <value>/hadoop/data/datanode</value>
    </property>

<property>
    <name>dfs.name.dir</name>
    <value>/home/yass/Téléchargements/hadoop/hdfs/name</value>
</property>
<property>
    <name>dfs.datanode.use.datanode.hostname</name>
    <value>false</value>
 </property>

  <property>
     <name>dfs.namenode.datanode.registration.ip-hostname-check</name>
     <value>false</value>
  </property>
</code>```

etc/hosts

```<code>127.0.0.1   localhost
127.0.0.1   yass-SATELLITE-C855-2CF

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
</code>```

i got the first exception once it dispair i got the second one and i keep always in loop with this two exceptions
Any suggestions please ?

答:
in reality i find somehow a solution in order to not staying with same errors
so i installed Hadoop verion 2.6.2 ,configure the version using the XML then keep working ,is not good solution for everyone but i hope that will show light for others

ContentLicense: CC BY-SA 3.0

Body:
i am trying to execute the command hadoop dfs -ls, and i got this error

Call From localhost/127.0.0.1 to yass-SATELLITE-C855-2CF:8021 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

once i resolved i got another which is

ls: Failed on local exception: com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.; Host Details : local host is: "localhost/127.0.0.1"; destination host is: "yass-SATELLITE-C855-2CF":9000;

and i keep in loop between this two errors

my core-site.xml

<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://yass-SATELLITE-C855-2CF:9000</value>
    </property>
</configuration>

hdfs-site.xml

<property>
        <name>dfs.replication</name>
        <value>1</value>
     </property>
<property>
        <name>dfs.safemode.threshold.pct</name>
        <value>0</value>
    </property>
  <property>
        <name>dfs.namenode.name.dir</name>
        <value>/hadoop/data/namenode</value>
    </property>
    <property>
        <name>dfs.datanode.data.dir</name>
        <value>/hadoop/data/datanode</value>
    </property>

<property>
    <name>dfs.name.dir</name>
    <value>/home/yass/Téléchargements/hadoop/hdfs/name</value>
</property>
<property>
    <name>dfs.datanode.use.datanode.hostname</name>
    <value>false</value>
 </property>

  <property>
     <name>dfs.namenode.datanode.registration.ip-hostname-check</name>
     <value>false</value>
  </property>

etc/hosts

127.0.0.1   localhost
127.0.0.1   yass-SATELLITE-C855-2CF

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

i got the first exception once it dispair i got the second one and i keep always in loop with this two exceptions
Any suggestions please ?


问:
Efficient way of doing ordered permutations
I don't know if it's possible, but I'm trying to find, in C#, an algorithm which can generate all the permutations of a set of number with some "empty space" in it while keeping its order.

Example :

I have an array [1,2] and I need all the ordered permutations with two "Empty space".
In this case, I will have :

```<code>[1,2,null,null]
[1,null,2,null]
[1,null,null,2]
[null,1,2,null]
[null,1,null,2]
[null,null,1,2]
</code>```

I have tried to include all the "empty space" inside the array before doing a permutation, but it yield too much permutations that I do not need.

in C#, the function could be

```<code>    private static List<int[]> PermutateWithSpace(this List<int> set, int numberOfEmptySpace)
    {
        // Algorithm which yield all possible permutations of my N "null" inside my set
    }
</code>```

答:
Sure, that algorithm is straightforward.

Suppose you have n numbers and m nulls.  We're going to start with the nulls and then insert the numbers as we go.

The first thing we do is figure out where the first number goes. We yield 0, 1, 2, ... m nulls, and then yield the first number.

Suppose we yielded x nulls on this permutation. Now we figure out where the second number goes. We yield 0, 1, 2, ... m - x nulls, and then yield the second number.

And so on.

Is that enough of a hint, or do you need to see the algorithm written out?

In case you get stuck:

```<code>static IEnumerable<T> Append<T>(this IEnumerable<T> items, T item)
{
    foreach(var i in items)
        yield return i;
    yield return item;
}

static IEnumerable<IEnumerable<int?>> DoIt(int min, int max, int nulls)
{
    if (min > max)
        yield return Enumerable.Repeat<int?>(null, nulls);
    else
        for(int i = 0; i <= nulls; ++i)
            foreach(var r in DoIt(min + 1, max, nulls - i))
                yield return Enumerable.Repeat<int?>(null, i).Append(min).Concat(r);
}
</code>```

Or, even more compactly, in LINQ style!

```<code>static IEnumerable<IEnumerable<int?>> DoIt(int min, int max, int nulls)
{
    return (min > max) ?
        new[] { Enumerable.Repeat<int?>(null, nulls) } :
        from i in Enumerable.Range(0, nulls + 1)
        from r in DoIt(min + 1, max, nulls - i)
        select Enumerable.Repeat<int?>(null, i).Append(min).Concat(r);
}
</code>```

Body:
I don't know if it's possible, but I'm trying to find, in C#, an algorithm which can generate all the permutations of a set of number with some "empty space" in it while keeping its order.

Example :

I have an array [1,2] and I need all the ordered permutations with two "Empty space".
In this case, I will have :

[1,2,null,null]
[1,null,2,null]
[1,null,null,2]
[null,1,2,null]
[null,1,null,2]
[null,null,1,2]

I have tried to include all the "empty space" inside the array before doing a permutation, but it yield too much permutations that I do not need.

in C#, the function could be

    private static List<int[]> PermutateWithSpace(this List<int> set, int numberOfEmptySpace)
    {
        // Algorithm which yield all possible permutations of my N "null" inside my set
    }

Body:
Sure, that algorithm is straightforward.

Suppose you have n numbers and m nulls.  We're going to start with the nulls and then insert the numbers as we go.

The first thing we do is figure out where the first number goes. We yield 0, 1, 2, ... m nulls, and then yield the first number.

Suppose we yielded x nulls on this permutation. Now we figure out where the second number goes. We yield 0, 1, 2, ... m - x nulls, and then yield the second number.

And so on.

Is that enough of a hint, or do you need to see the algorithm written out?

In case you get stuck:

static IEnumerable<T> Append<T>(this IEnumerable<T> items, T item)
{
    foreach(var i in items)
        yield return i;
    yield return item;
}

static IEnumerable<IEnumerable<int?>> DoIt(int min, int max, int nulls)
{
    if (min > max)
        yield return Enumerable.Repeat<int?>(null, nulls);
    else
        for(int i = 0; i <= nulls; ++i)
            foreach(var r in DoIt(min + 1, max, nulls - i))
                yield return Enumerable.Repeat<int?>(null, i).Append(min).Concat(r);
}

Or, even more compactly, in LINQ style!

static IEnumerable<IEnumerable<int?>> DoIt(int min, int max, int nulls)
{
    return (min > max) ?
        new[] { Enumerable.Repeat<int?>(null, nulls) } :
        from i in Enumerable.Range(0, nulls + 1)
        from r in DoIt(min + 1, max, nulls - i)
        select Enumerable.Repeat<int?>(null, i).Append(min).Concat(r);
}


问:
How to get LatLngBounds of visible region in titled map in andorid
I tried the following code.

```<code>    LatLngBounds b = googleMap.getProjection()
                              .getVisibleRegion().latLngBounds;
    LatLng bNE = b.northeast;
    LatLng bSW = b.southwest;
</code>```

It's not giving correct bounding coordinates if tilt is set to the map

答:
As mentioned in the Google Maps API doc VisibleRegion, the visible region for a map's camera can be in the form of a rectangle in case the camera is centered over the map region which will give you correct bounding coordinates. While it can also be in the form of a trapezoid, in case the camera has tilt, which is your case.

That's why you're getting wrong bounding coordinates!

Body:
I tried the following code.

    LatLngBounds b = googleMap.getProjection()
                              .getVisibleRegion().latLngBounds;
    LatLng bNE = b.northeast;
    LatLng bSW = b.southwest;

It's not giving correct bounding coordinates if tilt is set to the map


问:
Could not create bundle folder for versioned model?
I received project from other developer. Then i opened iOS project in Xcode and build it, i got error as below:

```<code>Volumes/Macintosh D/My workspace/HCProject/Model/HealthCareModel.xcdatamodeld:0: error:
Could not create bundle folder for versioned model at
'/Users/TomMac/Library/Developer/Xcode/DerivedData/HCProject-bdxarurbgcdbaecxaoocaroetsjt/Build/Products/Debug-iphoneos/HCProject.app/HealthCareModel.momd'
</code>```

Sorry if this is a basic question,please help me out.
Thanks a lot.

答: In my case my testsFileName.xctest (in workspace > Products > testsFileName.xctest) somehow has the application target as his target membership.</p>

Body:
I received project from other developer. Then i opened iOS project in Xcode and build it, i got error as below:

Volumes/Macintosh D/My workspace/HCProject/Model/HealthCareModel.xcdatamodeld:0: error:
Could not create bundle folder for versioned model at
'/Users/TomMac/Library/Developer/Xcode/DerivedData/HCProject-bdxarurbgcdbaecxaoocaroetsjt/Build/Products/Debug-iphoneos/HCProject.app/HealthCareModel.momd'

Sorry if this is a basic question,please help me out.
Thanks a lot.


问:
Correct way of implementing Finalize and Dispose(When parent class implements IDisposable)
I was implementing Finalize and Dispose in my classes, I implemented IDisposable on my parent class and override the Dispose(bool) overload in my child classes. I was not sure

whether to use a duplicate isDisposed variable(as its already there in base class) or not?

Whether to implement a finalizer in child class too or not?

Both these things are done in example given here -

http://guides.brucejmack.biz/CodeRules/FxCop/Docs/Rules/Usage/DisposeMethodsShouldCallBaseClassDispose.html

Whereas example in this MSDN article doesn't have any of these two -
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

whereas this example in MSDN is not complete -
http://msdn.microsoft.com/en-us/library/ms182330.aspx

答:
The correct way to implement IDisposable depends on whether you have any unmanaged resources owned by your class. The exact way to implement IDisposable is still something not all developers agree on and some like Stephen Cleary have strong opinions on the disposable paradigm in general.

see: Implementing Finalize and Dispose to Clean Up Unmanaged Resources

The documentation for IDisposable interface also explains this breifly and this article points out some of the same things but also on MSDN.

As far as whether a duplicate boolean field "isDisposed" is required in the base class. It appears that this is mainly just a useful convention that can be used when a subclass itself may add additional unmanaged resources that need to be disposed of. Since Dispose is declared virtual, calling Dispose on a subclass instance always causes that class's Dispose method to be called first which in turn calls base.Dispose as it's last step giving a chance to clear up each level in the inheritance hierarchy. So I would probably summarize this as, if your subclass has additional unmanaged resources above what is owned by the base then you will probably be best to have your own boolean isDisposed field to track it's disposal in a transactional nature inside it's Dispose method but as Ian mentions in his answer, there are other ways to represent an already-disposed state.

ContentLicense: CC BY-SA 2.5


问:
How to find the longest consecutive chain of numbers in an array
For example we have [0, 1, 3, 5, 7, 8, 9, 10, 12, 13] .

The result must be 7, 8, 9, 10 because they are adjacent to each other, index wise and are consecutive integers, and also this chain is longer than 0, 1.

English is not my first language, excuse me if the writing is a bit obscure.

答:
Group the items into subsequences using itertools.groupby based on  constant differences from an increasing count (provided by an itertools.count object), and then take the longest subsequence using the built-in max on key parameter len:

```<code>from itertools import groupby, count

lst = [0, 1, 3, 5, 7, 8, 9, 10, 12, 13]
c = count()
val = max((list(g) for _, g in groupby(lst, lambda x: x-next(c))), key=len)
print(val)
# [7, 8, 9, 10]
</code>```

You may include the group key in the result (suppressed as _) to further understand how this works.

Body:
Group the items into subsequences using itertools.groupby based on  constant differences from an increasing count (provided by an itertools.count object), and then take the longest subsequence using the built-in max on key parameter len:

from itertools import groupby, count

lst = [0, 1, 3, 5, 7, 8, 9, 10, 12, 13]
c = count()
val = max((list(g) for _, g in groupby(lst, lambda x: x-next(c))), key=len)
print(val)
# [7, 8, 9, 10]

You may include the group key in the result (suppressed as _) to further understand how this works.


问:
How to fetch all the child nodes of an XML using python?
This is my XML file

```<code><?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>
</code>```

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

答:
Use ElementTree lib to pull out the child nodes. This might help you.</p>

```<code>import xml.etree.ElementTree as ET
tree = ET.parse("file.xml")
root = tree.getroot()
for child in root:
  print({x.tag for x in root.findall(child.tag+"/*")})
</code>```

Body:
This is my XML file

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

Body:
Use ElementTree lib to pull out the child nodes. This might help you.

import xml.etree.ElementTree as ET
tree = ET.parse("file.xml")
root = tree.getroot()
for child in root:
  print({x.tag for x in root.findall(child.tag+"/*")})


问:
Updating Twitter4j in a Java project
I have an application that streams Twitter data using Twitter4j. In Maven Dependencies, I've got the 4.0.2 version, but I want to update to the 4.0.4.
How do I do that? In Configure Build Path it is not possible to edit the selection of the jar file.

答:
Updating your pom.xml by adding this snippet in the dependencies section:

```<code><dependency>
    <groupId>org.twitter4j</groupId>
    <artifactId>twitter4j-core</artifactId>
    <version>4.0.6</version>
</dependency>
</code>```

Note, that there are several important fixes incoming with 4.0.6. For example, the support for enhanced_media_entities is added, which is quite important for compatibility reasons with Twitter API.

For more details about the API changes in 2016 check this link.

Title: Updating Twitter4j in a Java project

Body:
Updating your pom.xml by adding this snippet in the dependencies section:

<dependency>
    <groupId>org.twitter4j</groupId>
    <artifactId>twitter4j-core</artifactId>
    <version>4.0.6</version>
</dependency>

Note, that there are several important fixes incoming with 4.0.6. For example, the support for enhanced_media_entities is added, which is quite important for compatibility reasons with Twitter API.

For more details about the API changes in 2016 check this link.


问:
Get all Cities of Country from DBpedia using SPARQL
I would like to get all Cities of India from DBpedia database.

I tried many stackoverflow solutions but till now i have not got my required output.

How to fetch all Cities of Country using SPARQL.

答:
I got solution to get Cities of Country. For Example if we want to fetch cities of India then use dbr:India in your Query

```<code>SELECT DISTINCT ?placeName WHERE {
 ?placeName a yago:City108524735 ; dbo:country dbr:India
}
</code>```

Thanks @AKSW for your help.

Body:
I got solution to get Cities of Country. For Example if we want to fetch cities of India then use dbr:India in your Query

SELECT DISTINCT ?placeName WHERE {
 ?placeName a yago:City108524735 ; dbo:country dbr:India
}

Thanks @AKSW for your help.


问:
How To Pass Parameter in javascript find function?
Hie,

I have a json object which have a id field:

```<code>document = {
             id: 'some value',
             ...
           }
</code>```

And a list to store this documents.

```<code>var list = [{document}, {document} ...]
</code>```

Now I am trying to call javascript find() function on the list to return the document with a specific id as

```<code>list.find( document, id) => {
   if (document.id == id)
   return id
}
</code>```

But its not working. I checked and found that the id parameter value is not what I am passing but the index value of the document in the list. I tried changing the name hoping it was a error with keyword but the sae result.

So, How do I pass a custom parameter to the find function?

答:
So, How do I pass a custom parameter to the find function?

Array.prototype.find accepts a second parameter thisArg. You can use it to pass custom parameters as follows:

function finder(doc) {
   return doc.id === this.id;
}

let list = [{id: 1}, {id: 2}, {id: 3}];
let doc = list.find(finder, {id: 2});
console.log(doc);```

If there is no specific need for such a contrived setup however, you should rather go with the much simpler list.find(doc => doc.id === 2). You can replace the hardcoded 2 with a variable declared in the outer scope as demonstrated in Igor's answer.

Body:
Hie,

I have a json object which have a id field:

document = {
             id: 'some value',
             ...
           }

And a list to store this documents.

var list = [{document}, {document} ...]

Now I am trying to call javascript find() function on the list to return the document with a specific id as

list.find( document, id) => {
   if (document.id == id)
   return id
}

But its not working. I checked and found that the id parameter value is not what I am passing but the index value of the document in the list. I tried changing the name hoping it was a error with keyword but the sae result.

So, How do I pass a custom parameter to the find function?

Body:
So, How do I pass a custom parameter to the find function?

Array.prototype.find accepts a second parameter thisArg. You can use it to pass custom parameters as follows:

function finder(doc) {
   return doc.id === this.id;
}

let list = [{id: 1}, {id: 2}, {id: 3}];
let doc = list.find(finder, {id: 2});
console.log(doc);

If there is no specific need for such a contrived setup however, you should rather go with the much simpler list.find(doc => doc.id === 2). You can replace the hardcoded 2 with a variable declared in the outer scope as demonstrated in Igor's answer.


问:
Function calling in openerp reports
How is this sum_taxes method getting its lot parameter set? This is a code sample from the auction addon in openerp.

```<code>    import pooler
    import time
    from report import report_sxw
    from osv import osv

    class seller_form_report(report_sxw.rml_parse):
        def __init__(self, cr, uid, name, context):
            super(seller_form_report, self).__init__(cr, uid, name, context=context)
            lot=self.pool.get('auction.lots').browse(cr,uid,uid)
            #address=lot.bord_vnd_id.address_get(self.cr,self.uid,[partner.id])
        #   partner=lot.bord_vnd_id.partner_id
        #   address=partner.address and partner.address[0] or ""
        #   street = address and address.street or ""

            self.localcontext.update({
                'time': time,
                'sum_taxes': self.sum_taxes,
                'sellerinfo' : self.seller_info,
                'grand_total' : self.grand_seller_total,
        #       'street':street,
        #       'address':address,
    })

    def sum_taxes(self, lot):
        taxes=[]
        amount=0.0
        if lot.bord_vnd_id.tax_id:
            taxes.append(lot.bord_vnd_id.tax_id)
        elif lot.auction_id and lot.auction_id.seller_costs:
            taxes += lot.auction_id.seller_costs
        tax=self.pool.get('account.tax').compute(self.cr,self.uid,taxes,lot.obj_price,1)
        for t in tax:
            amount+=t['amount']
        return amount
    def seller_info(self):
        objects = [object for object in self.localcontext.get('objects')]
        ret_dict = {}
        ret_list = []
        for object in objects:

            partner = ret_dict.get(object.bord_vnd_id.partner_id.id,False)
            if not partner:
                ret_dict[object.bord_vnd_id.partner_id.id] = {'partner' : object.bord_vnd_id.partner_id or False,'lots':[object]}
            else:
                lots = partner.get('lots')
                lots.append(object)
#       buyer_ids=self.pool.get(auction.lots).read(cr,uid,lot)
        return ret_dict.values()
    def grand_seller_total(self,o):
        grand_total = 0
        for oo in o:
            grand_total =grand_total + oo['obj_price']+ self.sum_taxes(oo)
        return grand_total

report_sxw.report_sxw('report.seller_form_report', 'auction.lots', 'addons/auction/report/seller_form_report.rml', parser=seller_form_report)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
</code>```

答:
check following file auction/report/buyer_form_report.sxw

[[ repeatIn(o['lots'],'oo') ]] [[ oo.obj_num ]] Here 'oo' is defined and its called like [[ oo.obj_price  + sum_taxes(oo) ]]

and as this report is registered for the model: auction.lots it will return the BrowseRecord for the active_id when user clicks on report !!!

Title: Function calling in openerp reports

Body:
How is this sum_taxes method getting its lot parameter set? This is a code sample from the auction addon in openerp.

    import pooler
    import time
    from report import report_sxw
    from osv import osv

    class seller_form_report(report_sxw.rml_parse):
        def __init__(self, cr, uid, name, context):
            super(seller_form_report, self).__init__(cr, uid, name, context=context)
            lot=self.pool.get('auction.lots').browse(cr,uid,uid)
            #address=lot.bord_vnd_id.address_get(self.cr,self.uid,[partner.id])
        #   partner=lot.bord_vnd_id.partner_id
        #   address=partner.address and partner.address[0] or ""
        #   street = address and address.street or ""

            self.localcontext.update({
                'time': time,
                'sum_taxes': self.sum_taxes,
                'sellerinfo' : self.seller_info,
                'grand_total' : self.grand_seller_total,
        #       'street':street,
        #       'address':address,
    })

    def sum_taxes(self, lot):
        taxes=[]
        amount=0.0
        if lot.bord_vnd_id.tax_id:
            taxes.append(lot.bord_vnd_id.tax_id)
        elif lot.auction_id and lot.auction_id.seller_costs:
            taxes += lot.auction_id.seller_costs
        tax=self.pool.get('account.tax').compute(self.cr,self.uid,taxes,lot.obj_price,1)
        for t in tax:
            amount+=t['amount']
        return amount
    def seller_info(self):
        objects = [object for object in self.localcontext.get('objects')]
        ret_dict = {}
        ret_list = []
        for object in objects:

            partner = ret_dict.get(object.bord_vnd_id.partner_id.id,False)
            if not partner:
                ret_dict[object.bord_vnd_id.partner_id.id] = {'partner' : object.bord_vnd_id.partner_id or False,'lots':[object]}
            else:
                lots = partner.get('lots')
                lots.append(object)
#       buyer_ids=self.pool.get(auction.lots).read(cr,uid,lot)
        return ret_dict.values()
    def grand_seller_total(self,o):
        grand_total = 0
        for oo in o:
            grand_total =grand_total + oo['obj_price']+ self.sum_taxes(oo)
        return grand_total

report_sxw.report_sxw('report.seller_form_report', 'auction.lots', 'addons/auction/report/seller_form_report.rml', parser=seller_form_report)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


问:
UIApplication.registerForRemoteNotifications() must be called from main thread only
Xcode 9 (iOS 11) showing me an error/warning while registering for Push (remote) notification.

Here is error message

And here is code, I've tried:

```<code>let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
              UIApplication.shared.registerForRemoteNotifications()
        }
 }
</code>```

Error/Warning Line:

UIApplication.shared.registerForRemoteNotifications()

How to resolve this?

答:
In swift4

You can solve this issue with

DispatchQueue.main.async {
  UIApplication.shared.registerForRemoteNotifications()
}
```

Hope this will help...

Body:
Xcode 9 (iOS 11) showing me an error/warning while registering for Push (remote) notification.

Here is error message

And here is code, I've tried:

let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
              UIApplication.shared.registerForRemoteNotifications()
        }
 }

Error/Warning Line:

UIApplication.shared.registerForRemoteNotifications()

How to resolve this?

Body:
In swift4

You can solve this issue with

DispatchQueue.main.async {
  UIApplication.shared.registerForRemoteNotifications()
}

Hope this will help...

ContentLicense: CC BY-SA 4.0


问:
Google Column Chart Draws Y Axis Values Mixed
Google Column Chart Drawing Y Axis values mix as you see in image below. I want to be Y values should be increased in ordinary.

Jquery

```<code>var result_glb;
$.post(base_url+"dashboard/get_bar_chart_data",function(result){
  result_glb = $.parseJSON(result);
}).done(function(){
  google.charts.load('current', {'packages':['corechart','bar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable(result_glb);

    var options = {
      vAxis : { format: 'decimal' },
      legend: {position: 'none'},
      colors: ['#08A3CC', '#89C4F4', '#02617A','#42617A']

    };

    var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
    chart.draw(data, options);
    //chart.draw(data, google.charts.Bar.convertOptions(options)); has been tried.
  }
});
</code>```

Result of the request

My results is not in ordinary increased but Column chart puts them like increasing day by day and after that place the Y values for each bar. Is there any option of the chart to handle this problem?

答:
you could manually re-order the values for each column

```<code>for (var r = 0; r < data.getNumberOfRows(); r++) {
  var colValues = [];
  for (var c = 1; c < data.getNumberOfColumns(); c++) {
    colValues.push(data.getValue(r, c));
  }
  colValues.sort(function (a, b) {
    return a - b;
  });
  for (var c = 1; c < data.getNumberOfColumns(); c++) {
    data.setValue(r, c, colValues[c - 1])
  }
}
</code>```

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['bar']
});

function drawChart() {
  //var data = google.visualization.arrayToDataTable(result_glb);

  var data = google.visualization.arrayToDataTable([
    ['Date', 'A', 'B', 'C', 'D', 'E', 'F'],
    ['2017-06-01', 165, 938, 522, 998, 450, 250],
    ['2017-06-02', 135, 1120, 599, 1268, 288, 250],
    ['2017-06-03', 157, 1167, 587, 807, 397, 250],
    ['2017-06-04', 139, 1110, 615, 968, 215, 250],
    ['2017-06-05', 136, 691, 629, 1026, 366, 250]
  ]);

  for (var r = 0; r < data.getNumberOfRows(); r++) {
    var colValues = [];
    for (var c = 1; c < data.getNumberOfColumns(); c++) {
      colValues.push(data.getValue(r, c));
    }
    colValues.sort(function (a, b) {
      return a - b;
    });
    for (var c = 1; c < data.getNumberOfColumns(); c++) {
      data.setValue(r, c, colValues[c - 1])
    }
  }

  var options = {
    legend: {position: 'none'},
    colors: ['#08A3CC', '#89C4F4', '#02617A','#42617A']
  };

  var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_material"></div></code>```

however, re-ordering the column values will remove any relationship to the column heading.

which means values originally in column A, may now be in column F...

Body:
Google Column Chart Drawing Y Axis values mix as you see in image below. I want to be Y values should be increased in ordinary.

Jquery

var result_glb;
$.post(base_url+"dashboard/get_bar_chart_data",function(result){
  result_glb = $.parseJSON(result);
}).done(function(){
  google.charts.load('current', {'packages':['corechart','bar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable(result_glb);

    var options = {
      vAxis : { format: 'decimal' },
      legend: {position: 'none'},
      colors: ['#08A3CC', '#89C4F4', '#02617A','#42617A']

    };

    var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
    chart.draw(data, options);
    //chart.draw(data, google.charts.Bar.convertOptions(options)); has been tried.
  }
});

Result of the request

My results is not in ordinary increased but Column chart puts them like increasing day by day and after that place the Y values for each bar. Is there any option of the chart to handle this problem?

Body:
you could manually re-order the values for each column

for (var r = 0; r < data.getNumberOfRows(); r++) {
  var colValues = [];
  for (var c = 1; c < data.getNumberOfColumns(); c++) {
    colValues.push(data.getValue(r, c));
  }
  colValues.sort(function (a, b) {
    return a - b;
  });
  for (var c = 1; c < data.getNumberOfColumns(); c++) {
    data.setValue(r, c, colValues[c - 1])
  }
}

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['bar']
});

function drawChart() {
  //var data = google.visualization.arrayToDataTable(result_glb);

  var data = google.visualization.arrayToDataTable([
    ['Date', 'A', 'B', 'C', 'D', 'E', 'F'],
    ['2017-06-01', 165, 938, 522, 998, 450, 250],
    ['2017-06-02', 135, 1120, 599, 1268, 288, 250],
    ['2017-06-03', 157, 1167, 587, 807, 397, 250],
    ['2017-06-04', 139, 1110, 615, 968, 215, 250],
    ['2017-06-05', 136, 691, 629, 1026, 366, 250]
  ]);

  for (var r = 0; r < data.getNumberOfRows(); r++) {
    var colValues = [];
    for (var c = 1; c < data.getNumberOfColumns(); c++) {
      colValues.push(data.getValue(r, c));
    }
    colValues.sort(function (a, b) {
      return a - b;
    });
    for (var c = 1; c < data.getNumberOfColumns(); c++) {
      data.setValue(r, c, colValues[c - 1])
    }
  }

  var options = {
    legend: {position: 'none'},
    colors: ['#08A3CC', '#89C4F4', '#02617A','#42617A']
  };

  var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
  chart.draw(data, options);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_material"></div>

however, re-ordering the column values will remove any relationship to the column heading.

which means values originally in column A, may now be in column F...


问:
Randomization of Associative Array in System Verilog
I have an associative array:

```<code>    rand uvm_reg_field array_assoc[string];
</code>```

The array contains the handle of the UVM register fields for registers in the DUT and is indexed by a string (string is the name of the field).
Say I have 2 register fields with names "reg_field_1" and "reg_field_2".

As described,

```<code>    array_assoc["reg_field_1"]= handle of field 1;
    array_assoc["reg_field_2"]= handle of field 2;
</code>```

I need to randomize only one of the fields, so, I selectively turn the rand_mode off for one of the fields, say "reg_field_1":

```<code>    array_assoc["reg_field_1"].rand_mode(0);
</code>```

Now, if I randomize the associative array, both register fields are getting randomized.

What is even more surprising is that, if i declare a normal array with integer indexes, such that :

```<code>   rand uvm_reg_field array_normal[2];

   array_normal[0]= handle of field 1;
   array_normal[1]= handle of field 2;
</code>```

and then turn of the rand_mode for field 1:

```<code>   array_normal[0].rand_mode(0);
</code>```

It works fine and field 1 is not randomized.

The question is: Why is the register field "reg_field_1" getting randomized even when its rand_mode has been set to 0 in case of associative array ?

答:
The ability to set rand_mode() on individual elements of an associative array seems to have sporadic support. The following works for me in Questa and one other simulator; gives me a "not supported yet" in another, and the results you are seeing in yet another. So I would contact your tool vendor.</p>

```<code>module top;
class B;
   rand byte m;
endclass
class A;
   rand B a1[2];
   rand B a2[string];
   function void run;
      a2["0"]  = new;
      a2["1"]  = new;
      a1[0]    = new;
      a1[1]    = new;
      a1[0].rand_mode(0);
      a2["0"].rand_mode(0);
      void'(randomize());
      $display(a1[0].m, a1[1].m,,a2["0"].m,a2["1"].m);

      endfunction
endclass
   A a  = new();
   initial repeat(3) a.run();
endmodule
</code>```

Body:
I have an associative array:

    rand uvm_reg_field array_assoc[string];

The array contains the handle of the UVM register fields for registers in the DUT and is indexed by a string (string is the name of the field).
Say I have 2 register fields with names "reg_field_1" and "reg_field_2".

As described,

    array_assoc["reg_field_1"]= handle of field 1;
    array_assoc["reg_field_2"]= handle of field 2;

I need to randomize only one of the fields, so, I selectively turn the rand_mode off for one of the fields, say "reg_field_1":

    array_assoc["reg_field_1"].rand_mode(0);

Now, if I randomize the associative array, both register fields are getting randomized.

What is even more surprising is that, if i declare a normal array with integer indexes, such that :

   rand uvm_reg_field array_normal[2];

   array_normal[0]= handle of field 1;
   array_normal[1]= handle of field 2;

and then turn of the rand_mode for field 1:

   array_normal[0].rand_mode(0);

It works fine and field 1 is not randomized.

The question is: Why is the register field "reg_field_1" getting randomized even when its rand_mode has been set to 0 in case of associative array ?

Body:
The ability to set rand_mode() on individual elements of an associative array seems to have sporadic support. The following works for me in Questa and one other simulator; gives me a "not supported yet" in another, and the results you are seeing in yet another. So I would contact your tool vendor.

module top;
class B;
   rand byte m;
endclass
class A;
   rand B a1[2];
   rand B a2[string];
   function void run;
      a2["0"]  = new;
      a2["1"]  = new;
      a1[0]    = new;
      a1[1]    = new;
      a1[0].rand_mode(0);
      a2["0"].rand_mode(0);
      void'(randomize());
      $display(a1[0].m, a1[1].m,,a2["0"].m,a2["1"].m);

      endfunction
endclass
   A a  = new();
   initial repeat(3) a.run();
endmodule


问:
Sending a slash through mysql
I'm not sure why this has stumped me. I have the following code

```<code>$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}
</code>```

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

```<code>$name       = mysql_real_escape_string($name);
</code>```

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

答:
try

```<code>if(!empty($website)) {
   $name = "[url={$website}]{$name}[/url]";
}
</code>```

then use,

```<code>mysql_real_escape_string ($name);
</code>```

Title: Sending a slash through mysql

Body:
I'm not sure why this has stumped me. I have the following code

$website = "http://www.google.com";
$name = "Person";

if(!empty($website) {
   $name = "[url=$website]$name[/url]";
}

Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.

$name       = mysql_real_escape_string($name);

Still no luck though. Any advice? What am I missing? It's giving me this error

"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"

Body:
try

if(!empty($website)) {
   $name = "[url={$website}]{$name}[/url]";
}

then use,

mysql_real_escape_string ($name);


问:
Need to Escape the Character After Special Characters in Python's regex?
I have the following python code:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import re
line = 'div><div class="fieldRow jr_name"><div class="fieldLabel">name<'
regex0 = re.compile('(.+?)\v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex1 = re.compile('(.+?)v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex2 = re.compile('(.+?) class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)

m0 = regex0.match(line)
m1 = regex1.match(line)
m2 = regex2.match(line)

if m0:
    print 'regex0 is good'
else:
    print 'regex0 is no good'

if m1:
    print 'regex1 is good'
else:
    print 'regex1 is no good'

if m2:
    print 'regex2 is good'
else:
    print 'regex2 is no good'
</code>```

The output is

```<code>regex0 is good
regex1 is no good
regex2 is good
</code>```

I don't quite understand why I need to escape the character 'v' after "(.+?)" in regex0.  If I don't escape, which will become regex1, then the matching will fail.  However, for space right after "(.+?)" in regex3, I don't have to escape.

Any idea?

Thanks in advance.

答:
There is a special symbol in Python regex \v, about which you can read here:
https://docs.python.org/2/library/re.html

Python regex usually are written in r'your regex' block, where "r" means raw string. (https://docs.python.org/3/reference/lexical_analysis.html)

In your code all special characters should be escaped to be understood as normal characters. E.g. if you write s - this is space, \s is just "s". To make it work in an opposite way use raw strings.
The line below is the solution you need, I believe.

```<code>regex1 = re.compile(r'(.+?)v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
</code>```

Body:
I have the following python code:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import re
line = 'div>

name<'
regex0 = re.compile('(.+?)\v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex1 = re.compile('(.+?)v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)
regex2 = re.compile('(.+?) class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)

m0 = regex0.match(line)
m1 = regex1.match(line)
m2 = regex2.match(line)

if m0:
    print 'regex0 is good'
else:
    print 'regex0 is no good'

if m1:
    print 'regex1 is good'
else:
    print 'regex1 is no good'

if m2:
    print 'regex2 is good'
else:
    print 'regex2 is no good'

The output is

regex0 is good
regex1 is no good
regex2 is good

I don't quite understand why I need to escape the character 'v' after "(.+?)" in regex0.  If I don't escape, which will become regex1, then the matching will fail.  However, for space right after "(.+?)" in regex3, I don't have to escape.

Any idea?

Thanks in advance.

Body:
There is a special symbol in Python regex \v, about which you can read here:
https://docs.python.org/2/library/re.html

Python regex usually are written in r'your regex' block, where "r" means raw string. (https://docs.python.org/3/reference/lexical_analysis.html)

In your code all special characters should be escaped to be understood as normal characters. E.g. if you write s - this is space, \s is just "s". To make it work in an opposite way use raw strings.
The line below is the solution you need, I believe.

regex1 = re.compile(r'(.+?)v class="fieldLabel">name.+?', re.VERBOSE | re.UNICODE)


问:
Grid columns shrink in Kendo grid after excel export
I am new to Kendo-UI and Web-Engineering and I am facing a problem which I haven't solved after investing hours of time.

I have a grid with 8 columns, and a Excel toolbar button. When I fire the excelExport event, i show 2 more hidden columns to include their data in the report, and after that I hide them again.

My Problem is that my columns shrink for the hidden columns when they are shown, yet dont expand their width afterwards when they're hidden again.

Here's my script for the excelExport event:

```<code><script type="text/javascript">
    var exportFlag = false;

    $(window).load(function() {
        $("#pr-grid").data("kendoGrid").bind("excelExport",function(e) {
            if (!exportFlag) {
                e.sender.showColumn("CallOff");
                e.sender.showColumn("LastChange");
                e.preventDefault();
                exportFlag = true;
                setTimeout(function() {
                    e.sender.saveAsExcel();
                });
            } else {
                e.sender.hideColumn("CallOff");
                e.sender.hideColumn("LastChange");
                exportFlag = false;
            }
        });
     });
</script>
</code>```

I'd appreciate any help.
Regards Paparis

答:
$('#pr-grid table').width('100%');

```<code><script type="text/javascript">
        var exportFlag = false;

        function excelExport(e) {
            if (!exportFlag) {
                e.sender.showColumn("CallOff");
                e.sender.showColumn("LastChange");
                e.preventDefault();
                exportFlag = true;
                setTimeout(function() {
                    e.sender.saveAsExcel();
                });
            } else {
                e.sender.hideColumn("CallOff");
                e.sender.hideColumn("LastChange");
                exportFlag = false;
                $('#grid table').width('100%');
            }
        }
    </script>
</code>```

Body:
I am new to Kendo-UI and Web-Engineering and I am facing a problem which I haven't solved after investing hours of time.

I have a grid with 8 columns, and a Excel toolbar button. When I fire the excelExport event, i show 2 more hidden columns to include their data in the report, and after that I hide them again.

My Problem is that my columns shrink for the hidden columns when they are shown, yet dont expand their width afterwards when they're hidden again.

Here's my script for the excelExport event:

I'd appreciate any help.
Regards Paparis

Body:
$('#pr-grid table').width('100%');

<script type="text/javascript">
        var exportFlag = false;

        function excelExport(e) {
            if (!exportFlag) {
                e.sender.showColumn("CallOff");
                e.sender.showColumn("LastChange");
                e.preventDefault();
                exportFlag = true;
                setTimeout(function() {
                    e.sender.saveAsExcel();
                });
            } else {
                e.sender.hideColumn("CallOff");
                e.sender.hideColumn("LastChange");
                exportFlag = false;
                $('#grid table').width('100%');
            }
        }
    </script>


问:
Automating Software installation in Amazon Windows Instance
I would like to use Amazon Windows Instance to test the compatibility of the code which is developed on Mac. I may use the instance once a month for few hours for testing purposes that's it. I don't want my instance running the whole month and costing me.

Hence I am planning to create an instance whenever I want. To test the code I have to install g++, openGL, boost libraries etc. How can do this using scripts?

I am looking for some scripts which install packages on a freshly installed Windows instance, clone the files from git, build and test the software.

For example for AWS Ubuntu instance I can do the following,

```<code>./> ssh -i KeyPairForUbuntu.pem ubuntu@instance.eu-central-1.compute.amazonaws.com
./> sudo apt install <packages>
./> git clone pathToTheGit
./> run scons scripts to build and run the project
</code>```

Is there any similar way to do this for Windows?

Please give any suggestions,

Thanks

答:
try using https://chocolatey.org/

its a package management like apt-get for windows

Body:
I would like to use Amazon Windows Instance to test the compatibility of the code which is developed on Mac. I may use the instance once a month for few hours for testing purposes that's it. I don't want my instance running the whole month and costing me.

Hence I am planning to create an instance whenever I want. To test the code I have to install g++, openGL, boost libraries etc. How can do this using scripts?

I am looking for some scripts which install packages on a freshly installed Windows instance, clone the files from git, build and test the software.

For example for AWS Ubuntu instance I can do the following,

./> ssh -i KeyPairForUbuntu.pem ubuntu@instance.eu-central-1.compute.amazonaws.com
./> sudo apt install <packages>
./> git clone pathToTheGit
./> run scons scripts to build and run the project

Is there any similar way to do this for Windows?

Please give any suggestions,

Thanks


问:
onchange="" doesn't work in select tag
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

```<code><select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
    #a , #b , #c , #d , #f , #g , #h , #j , #k , #e , #i {
        display: none;
    }
</style>
</code>```

JS:

```<code>$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});
</code>```

And after run the code the css code which I  want don't launch.
What's the problem here ?

答:
I guess what you want is that when you select the value pri in the first select the second take the value aa. As you use jquery I'll give you an example.

```<code> $( document ).ready(function() {
  $("#study-phase").change(function(){
  if($(this).val() === "pri")
    {
       $("#study-year").val("aa");
    }
  });
})
</code>```

https://codepen.io/anon/pen/VWLaqv

Title: onchange="" doesn't work in select tag

Body:
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

<select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>

JS:

$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});

And after run the code the css code which I  want don't launch.
What's the problem here ?

Body:
I guess what you want is that when you select the value pri in the first select the second take the value aa. As you use jquery I'll give you an example.

 $( document ).ready(function() {
  $("#study-phase").change(function(){
  if($(this).val() === "pri")
    {
       $("#study-year").val("aa");
    }
  });
})

https://codepen.io/anon/pen/VWLaqv


问:
Python - Exclude variable if list element doesn't exist
Python novice here - was unable to find anything similar online.

I am trying to analyze a large data set containing many rows with varying column lengths. An example of my data may be: "LY R15 515 750 601 999" where the number of elements is different for each row. I want the column variables to refer to each subsequent element, but only if that element exists. I am going to use all column variables for if statements with numeric expressions later on.

```<code>data = 'LY R15 515 750 601 999'
remove_blanks = ['']
entries = data.split()
''.join([i for i in entries if i not in remove_blanks])
trash = (entries[0], entries[1])
time = int(entries[2])
column_1 = int(entries[3])
column_2 = int(entries[4])
column_3 = int(entries[5])
column_4 = int(entries[6])
column_5 = int(entries[7])
column_6 = int(entries[8])
column_7 = int(entries[9])
column_8 = int(entries[10])
column_9 = int(entries[11])
column_10 = int(entries[12])
column_11 = int(entries[13])
column_12 = int(entries[14])
column_13 = int(entries[15])
column_14 = int(entries[16])
column_15 = int(entries[17])
column_16 = int(entries[18])
column_17 = int(entries[19])
column_18 = int(entries[20])
print(entries)
</code>```

The error I am receiving:

column_3 = int(entries[5])

IndexError: list index out of range

I understand it is happening because that element does not exist in the list. Essentially, if an element does not exist, I do not want that variable to be considered. Please help!

P.S. I am sure there is a much simpler way to write this, so if there is, please let me know!

答:
Having variables named column_1 to column_18 is not very handy.

Instead of

```<code>column_1 = int(entries[3])
column_2 = int(entries[4])
column_3 = int(entries[5])
... etc, etc ...
</code>```

consider

```<code>column = [None] + [int(v) for v in entries[3:]]
</code>```

and then use column[3] instead of column_3.

The [None] + is a dodge to get the list subscripts (which are zero based) to match your variable names, which are 1-based.

Body:
Python novice here - was unable to find anything similar online.

I am trying to analyze a large data set containing many rows with varying column lengths. An example of my data may be: "LY R15 515 750 601 999" where the number of elements is different for each row. I want the column variables to refer to each subsequent element, but only if that element exists. I am going to use all column variables for if statements with numeric expressions later on.

data = 'LY R15 515 750 601 999'
remove_blanks = ['']
entries = data.split()
''.join([i for i in entries if i not in remove_blanks])
trash = (entries[0], entries[1])
time = int(entries[2])
column_1 = int(entries[3])
column_2 = int(entries[4])
column_3 = int(entries[5])
column_4 = int(entries[6])
column_5 = int(entries[7])
column_6 = int(entries[8])
column_7 = int(entries[9])
column_8 = int(entries[10])
column_9 = int(entries[11])
column_10 = int(entries[12])
column_11 = int(entries[13])
column_12 = int(entries[14])
column_13 = int(entries[15])
column_14 = int(entries[16])
column_15 = int(entries[17])
column_16 = int(entries[18])
column_17 = int(entries[19])
column_18 = int(entries[20])
print(entries)

The error I am receiving:

column_3 = int(entries[5])

IndexError: list index out of range

I understand it is happening because that element does not exist in the list. Essentially, if an element does not exist, I do not want that variable to be considered. Please help!

P.S. I am sure there is a much simpler way to write this, so if there is, please let me know!

Body:
Having variables named column_1 to column_18 is not very handy.

Instead of

column_1 = int(entries[3])
column_2 = int(entries[4])
column_3 = int(entries[5])
... etc, etc ...

consider

column = [None] + [int(v) for v in entries[3:]]

and then use column[3] instead of column_3.

The [None] + is a dodge to get the list subscripts (which are zero based) to match your variable names, which are 1-based.


问:
ruby read lines from string variable using character count
I have been using to split the file content based on the character count, since one of my application which doesn't support for any number of characters. So I have to split the content based on the character count and update it multiple times based on the total character count.

```<code>c_max = 50000
f = File.new(filename)
u_count = (c_count / c_max.to_f).ceil
i = 1
while i <= u_count do
    u_characters = f.sysread(c_max)
    # do stuffs
    i+=1
end
</code>```

But its not working when I use strings instead of filename.

```<code>content=File.read(filename)
#doing some stuffs on the contents
irb(main):006:0> content.sysread(10)
NoMethodError: undefined method `sysread' for #<String:0x7f5f2eedd368>
        from (irb):6
        from :0
irb(main):007:0>
</code>```

答:
The problem is that a String object doesn't have a sysread method. To get the first n characters of a String object you can use String slice(range):

```<code>content[0...10]
</code>```

or slice(start, length):

```<code>content[0, 10]
</code>```

Body:
I have been using to split the file content based on the character count, since one of my application which doesn't support for any number of characters. So I have to split the content based on the character count and update it multiple times based on the total character count.

c_max = 50000
f = File.new(filename)
u_count = (c_count / c_max.to_f).ceil
i = 1
while i <= u_count do
    u_characters = f.sysread(c_max)
    # do stuffs
    i+=1
end

But its not working when I use strings instead of filename.

content=File.read(filename)
#doing some stuffs on the contents
irb(main):006:0> content.sysread(10)
NoMethodError: undefined method `sysread' for #<String:0x7f5f2eedd368>
        from (irb):6
        from :0
irb(main):007:0>

Body:
The problem is that a String object doesn't have a sysread method. To get the first n characters of a String object you can use String slice(range):

content[0...10]

or slice(start, length):

content[0, 10]


问:
Coloring non generic contours
I am using C# and I am drawing the picture programmatically (since the picture can differ according to run time values of the parameters in my application). I end up with non generic closed contours (which consist of straight lines and curves). Now I need to fill those with different colors.
Any idea how can I accomplish this?

Thanks in advance.

答:
You can use the PathGradientBrush for this. Here's a code example.

```<code>Public NotInheritable Class PathGradientBrush
          Inherits System.Drawing.Brush
     Member of System.Drawing.Drawing2D
Summary:
Encapsulates a System.Drawing.Brush object that fills the interior of a System.Drawing.Drawing2D.GraphicsPath object with a gradient. This class cannot be inherited.
</code>```

Title: Coloring non generic contours

Body:
You can use the PathGradientBrush for this. Here's a code example.

Public NotInheritable Class PathGradientBrush
          Inherits System.Drawing.Brush
     Member of System.Drawing.Drawing2D
Summary:
Encapsulates a System.Drawing.Brush object that fills the interior of a System.Drawing.Drawing2D.GraphicsPath object with a gradient. This class cannot be inherited.


问:
Lots of path on screen makes tooltip slow on iPhone
I am drawing 21 * 9 windBarbs in my d3 chart using PATH.
Sample path looks like this:

```<code><path marker-start="url(#meteo-barbheadLight)" stroke="black" stroke-width="0.5" class="meteo-aloft-barb meteo-aloft-barb-group-0 moderate" d="M1 2 L8 2 M0 0 L1 2 Z" transform="translate(0, 225.64285714285714) scale(1.875), rotate(339.35300899956496, 0, 0), translate(-4, -2)" style="opacity: 0.2;"></path>
</code>```

This is working fine on desktop web browser. But when I run it on iOS safari. Due to some reason tooltip-trendline performance becomes very poor.

I am not sure what is causing this issue. I even tried to isolate these barbs from trendline -tooltip functionality, but still it is slow. If I dont draw these barbs then tooltip is pretty smooth.

So question is :

1) Are those 21 * 9 barbs making page so heavy that tooltip is having lag on mobile browser?

2) What can be a better way to do this?

Application URL:

http://ec2.buser.net/bnforecast/meteogramv2/#!/app/dashboard?start=KBTP&product=MAV

答:
A better way to do this is either draw all those paths inside a canvas instead of SVG or just export those paths to canvas using canvg library and then remove SVG path container  element. Canvas is way lighter than SVG.

Also, one tip is to use display: none instead of opacity for performance boost.

Body:
I am drawing 21 * 9 windBarbs in my d3 chart using PATH.
Sample path looks like this:

<path marker-start="url(#meteo-barbheadLight)" stroke="black" stroke-width="0.5" class="meteo-aloft-barb meteo-aloft-barb-group-0 moderate" d="M1 2 L8 2 M0 0 L1 2 Z" transform="translate(0, 225.64285714285714) scale(1.875), rotate(339.35300899956496, 0, 0), translate(-4, -2)" style="opacity: 0.2;"></path>

This is working fine on desktop web browser. But when I run it on iOS safari. Due to some reason tooltip-trendline performance becomes very poor.

I am not sure what is causing this issue. I even tried to isolate these barbs from trendline -tooltip functionality, but still it is slow. If I dont draw these barbs then tooltip is pretty smooth.

So question is :

1) Are those 21 * 9 barbs making page so heavy that tooltip is having lag on mobile browser?

2) What can be a better way to do this?

Application URL:

http://ec2.buser.net/bnforecast/meteogramv2/#!/app/dashboard?start=KBTP&product=MAV


问:
how to store multiple listbox values in database using mvc5
I want to store multiple listbox values in db using asp.net Mvc5

I have tried like this. I want to pass multiple selected fields here
please provide soultion regarding this

In Controller Part:-

```<code>public bool ReportToFavourites(ReportsModel model)
    {

            var NewReport = new Report
            {
                TableName=model.Tables,
                ColumnName=model.SelectedFields
            };
            bool Result = DBFunctionOBj.SaveNewReportToFavourites(NewReport);
            return Result;
    }
</code>```

In view Part:-

```<code> @Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { @class = "form-control editable" })
</code>```

答:
Change your public string SelectedFields { get; set; } to public List<string> SelectedFields { get; set; }

While saving do as below:

```<code>var NewReport = new Report
{
  TableName=model.Tables,
  ColumnName=string.Join(",", model.SelectedFields)
};
</code>```

Body:
I want to store multiple listbox values in db using asp.net Mvc5

I have tried like this. I want to pass multiple selected fields here
please provide soultion regarding this

In Controller Part:-

public bool ReportToFavourites(ReportsModel model)
    {

            var NewReport = new Report
            {
                TableName=model.Tables,
                ColumnName=model.SelectedFields
            };
            bool Result = DBFunctionOBj.SaveNewReportToFavourites(NewReport);
            return Result;
    }

In view Part:-

 @Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { @class = "form-control editable" })

Body:
Change your public string SelectedFields { get; set; } to public List<string> SelectedFields { get; set; }

While saving do as below:

var NewReport = new Report
{
  TableName=model.Tables,
  ColumnName=string.Join(",", model.SelectedFields)
};


问:
Visual Studio 2015 does not show the tree structure of an exe file
I'm trying to open the setup.exe file created by Visual Studio Installer in order to change its icon.

It seems that Visual Studio 2013 shows a tree when you open an exe file,
example:

Visual Studio 2015 shows the binary content of the exe file instead:

How to see the exe tree structure using Visual Studio 2015?

答: I had the same problem. What did the trick for me I suppose was to re-run the Visual Studio installer and install the Visual Studio Extensibility Tools.</p>


问:
Should I always use virtualenvs in Django?
I'm a beginner, and I'm learning Django for web development. So I want to know for my little test, should in always have a virtualenv or can I continue to learn without installing it? I've asked because in youtube Django videos, some instructors are installing it, and others aren't.</p>

答:
No. It's not mandatory to use virtualenvs but it might help.

I think you need to understand what virtualenvs does and when to use it.
What virtualenvs does is creating an isolated environment(for example, a django project) from others.
It's not just a Django component. It can be used for other projects as well.

Let's assume that there are two different projects, A and B. It doesn't matter if they are Django projects.

In project A, you might want to use python module AAA(version 1.00). And in project B, you also want to use python module AAA(version 2.00). Both use the same module but their versions are different.

In those cases you can use virtualenvs to create two different environments and isolate those. And install AAA version 1.0, AAA version 2.0 in those environment respectively.

When people start a new project, it's very natural and common to create a new isolated environment only for it. Then it would be easy to move the project to another computer or recreate exactly the same environment in other machines. Also it won't be affected by other previously installed modules or configuration. If there are other modules before your project might work differently and you might not find that until you deploy.

So it's not mandatory but using it is a good practice.

Also there are many tools for creating an isolated environment in different layers like Conda, Docker etc... Take a look at those as well.


问:
Append external svg using d3 and Webpack in IE11
What I want to do is load in multiple external svg images using import with webpack, and append them to a group using d3. I'm currently using d3's .html method to do so, but it doesn't work in IE11 and below.

Here's how it's set up now:

```<code>import aerosolsImage from '../../images/topic-aerosols.svg'
import cloudsImage from '../../images/topic-clouds.svg'
import fireImage from '../../images/topic-fire.svg'

const topicsToImages = {
  'aerosols': aerosolsImage,
  'clouds': cloudsImage,
  'fire': fireImage
}

...

// called every few seconds to trigger new animation
function start (topic, animationLayer) {
  const g = animationLayer.append('g')
  ...
  g.append('g')
    .html(topicsToImages[topic]);
}
</code>```

Loading the SVG with webpack returns a string like this:

```<code>"<svg xmlns="http://www.w3.org/2000/svg">...</svg>"
</code>```

Is there another way to append the SVGs using d3 that works in IE? Open to ideas, thanks!

答:
For future coders who have this same issue, I found a solution.

You can use this innerSVG polyfill mirror.

Install with npm:

```<code>npm install innersvg-polyfill --save-dev
</code>```

import with webpack:

```<code>import * as innerSVG from 'innersvg-polyfill'
</code>```

and voila, you can now use d3's .html or vanilla .innerHTML method with svg nodes cross-browser :)

Body:
What I want to do is load in multiple external svg images using import with webpack, and append them to a group using d3. I'm currently using d3's .html method to do so, but it doesn't work in IE11 and below.

Here's how it's set up now:

import aerosolsImage from '../../images/topic-aerosols.svg'
import cloudsImage from '../../images/topic-clouds.svg'
import fireImage from '../../images/topic-fire.svg'

const topicsToImages = {
  'aerosols': aerosolsImage,
  'clouds': cloudsImage,
  'fire': fireImage
}

...

// called every few seconds to trigger new animation
function start (topic, animationLayer) {
  const g = animationLayer.append('g')
  ...
  g.append('g')
    .html(topicsToImages[topic]);
}

Loading the SVG with webpack returns a string like this:

"<svg xmlns="http://www.w3.org/2000/svg">...</svg>"

Is there another way to append the SVGs using d3 that works in IE? Open to ideas, thanks!

Body:
For future coders who have this same issue, I found a solution.

You can use this innerSVG polyfill mirror.

Install with npm:

npm install innersvg-polyfill --save-dev

import with webpack:

import * as innerSVG from 'innersvg-polyfill'

and voila, you can now use d3's .html or vanilla .innerHTML method with svg nodes cross-browser :)


问:
"contains" method with Set does not work even after overriding the equals method
There is an entity :

```<code>@Entity
@Table(name = "menu")
public class Menu {

    @Id
    @SequenceGenerator(name="s_menu", sequenceName="s_menu", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_menu")
    @Column(name = "menu_id")
    private int id;

    @Column(name = "gmnu_code")
    private Integer groupeMenu;

    @Column(name = "menu_lib")
    private String lib;

    @Column(name = "menu_ordre")
    private Integer ordre;

    @Column(name = "menu_visible")
    private Integer visible;

    @Column(name = "menu_deleted")
    private Integer deleted;

    @Column(name = "menu_bouton")
    private Integer bouton;

    @Column(name = "menu_parent")
    private Integer parent;

    @Column(name = "menu_controlleur")
    private String controlleur;

    @Column(name = "menu_navigation")
    private String navigation;

    @Column(name = "menu_flag_trace")
    private Integer flag_trace;

    @Column(name = "menu_trace")
    private String trace;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "menus")
    @JsonBackReference
    private Set<Role> roles = new HashSet<Role>();

    @Transient
    private int depth;

    @Transient
    private boolean affectedToARole;

    @Transient
    private Environment env;

    public Menu() {
        super();
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace, Set<Role> roles) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
        this.roles = roles;
    }

    public int getId() {
        return id;
    }

    public void setId(int menu_id) {
        this.id = menu_id;
    }

    public Integer getGroupeMenu() {
        return groupeMenu;
    }

    public void setGroupeMenu(Integer gmnu_code) {
        this.groupeMenu = gmnu_code;
    }

    public String getLib() {
        if (this.env != null)
            return env.getProperty(lib.trim());
        return lib;
    }

    public void setLib(String menu_lib) {
        this.lib = menu_lib;
    }

    public Integer getOrdre() {
        return ordre;
    }

    public void setOrdre(Integer menu_ordre) {
        this.ordre = menu_ordre;
    }

    public Integer getVisible() {
        return visible;
    }

    public void setVisible(Integer menu_visible) {
        this.visible = menu_visible;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer menu_deleted) {
        this.deleted = menu_deleted;
    }

    public Integer getBouton() {
        return bouton;
    }

    public void setBouton(Integer menu_bouton) {
        this.bouton = menu_bouton;
    }

    public Integer getParent() {
        return parent;
    }

    public void setParent(Integer menu_parent) {
        this.parent = menu_parent;
    }

    public String getControlleur() {
        return controlleur;
    }

    public void setControlleur(String menu_controlleur) {
        this.controlleur = menu_controlleur;
    }

    public String getNavigation() {
        try {
            if (this.env != null)
                return env.getProperty(navigation.trim());
            return navigation.trim();
        } catch (NullPointerException npe) {
            return " --- ";
        }
    }

    public void setNavigation(String menu_navigation) {
        this.navigation = menu_navigation;
    }

    public String getTrace() {
        if (this.env != null)
            return HtmlUtils.htmlUnescape(env.getProperty(trace));
        return trace;
    }

    public void setTrace(String menu_trace) {
        this.trace = HtmlUtils.htmlUnescape(menu_trace);
    }

    public Integer getFlag_trace() {
        return flag_trace;
    }

    public void setFlag_trace(Integer menu_flag_trace) {
        this.flag_trace = menu_flag_trace;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

    public boolean isAffectedToARole() {
        return affectedToARole;
    }

    public void setAffectedToARole(boolean affectedToARole) {
        this.affectedToARole = affectedToARole;
    }

    @Override
    public boolean equals(Object obj) { // pour pouvoir utiliser la méthode "contains" sur une liste de Menu

        if (this == null && obj == null)
            return true;

        if (this != null && obj != null && obj instanceof Menu)
            return id == ((Menu)obj).getId();

        return super.equals(obj);

    }

}
</code>```

I want to test if a Set of Menu's contains a particular Menu :

```<code>Set<Menu> affected_menus = roleDao.getListMenu(role_code); // gets all menus affected to a role_code

for (Menu menu : temp) {
    if (!affected_menus.isEmpty() && affected_menus.contains(menu))
        menu.setAffectedToARole(true);
    else
        menu.setAffectedToARole(false);
}
</code>```

At runtime all code goes to menu.setAffectedToARole(false);

So what is wrong ?

答:
The javadoc of the the int hashCode() method from the Object class explains that :

it  returns a hash code value for the object. This method is supported
  for the benefit of hash tables such as those provided by
  java.util.HashMap.

The hashCode() method intention is clear : being using in collections relying on hash tables : HashMap, HashSet, LinkedHashMap, etc…

Besides, the general contract of hashcode() mentions the relation between equals() and hashcode() :

If two objects are equal according to the equals(Object) method, then
  calling the hashCode method on each of the two objects must produce
  the same integer result.

So to be able to use your custom class with a HashSet, you need to override both equals() and hashcode() in a consistent way.

Body:
There is an entity :

@Entity
@Table(name = "menu")
public class Menu {

    @Id
    @SequenceGenerator(name="s_menu", sequenceName="s_menu", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_menu")
    @Column(name = "menu_id")
    private int id;

    @Column(name = "gmnu_code")
    private Integer groupeMenu;

    @Column(name = "menu_lib")
    private String lib;

    @Column(name = "menu_ordre")
    private Integer ordre;

    @Column(name = "menu_visible")
    private Integer visible;

    @Column(name = "menu_deleted")
    private Integer deleted;

    @Column(name = "menu_bouton")
    private Integer bouton;

    @Column(name = "menu_parent")
    private Integer parent;

    @Column(name = "menu_controlleur")
    private String controlleur;

    @Column(name = "menu_navigation")
    private String navigation;

    @Column(name = "menu_flag_trace")
    private Integer flag_trace;

    @Column(name = "menu_trace")
    private String trace;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "menus")
    @JsonBackReference
    private Set<Role> roles = new HashSet<Role>();

    @Transient
    private int depth;

    @Transient
    private boolean affectedToARole;

    @Transient
    private Environment env;

    public Menu() {
        super();
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace, Set<Role> roles) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
        this.roles = roles;
    }

    public int getId() {
        return id;
    }

    public void setId(int menu_id) {
        this.id = menu_id;
    }

    public Integer getGroupeMenu() {
        return groupeMenu;
    }

    public void setGroupeMenu(Integer gmnu_code) {
        this.groupeMenu = gmnu_code;
    }

    public String getLib() {
        if (this.env != null)
            return env.getProperty(lib.trim());
        return lib;
    }

    public void setLib(String menu_lib) {
        this.lib = menu_lib;
    }

    public Integer getOrdre() {
        return ordre;
    }

    public void setOrdre(Integer menu_ordre) {
        this.ordre = menu_ordre;
    }

    public Integer getVisible() {
        return visible;
    }

    public void setVisible(Integer menu_visible) {
        this.visible = menu_visible;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer menu_deleted) {
        this.deleted = menu_deleted;
    }

    public Integer getBouton() {
        return bouton;
    }

    public void setBouton(Integer menu_bouton) {
        this.bouton = menu_bouton;
    }

    public Integer getParent() {
        return parent;
    }

    public void setParent(Integer menu_parent) {
        this.parent = menu_parent;
    }

    public String getControlleur() {
        return controlleur;
    }

    public void setControlleur(String menu_controlleur) {
        this.controlleur = menu_controlleur;
    }

    public String getNavigation() {
        try {
            if (this.env != null)
                return env.getProperty(navigation.trim());
            return navigation.trim();
        } catch (NullPointerException npe) {
            return " --- ";
        }
    }

    public void setNavigation(String menu_navigation) {
        this.navigation = menu_navigation;
    }

    public String getTrace() {
        if (this.env != null)
            return HtmlUtils.htmlUnescape(env.getProperty(trace));
        return trace;
    }

    public void setTrace(String menu_trace) {
        this.trace = HtmlUtils.htmlUnescape(menu_trace);
    }

    public Integer getFlag_trace() {
        return flag_trace;
    }

    public void setFlag_trace(Integer menu_flag_trace) {
        this.flag_trace = menu_flag_trace;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

    public boolean isAffectedToARole() {
        return affectedToARole;
    }

    public void setAffectedToARole(boolean affectedToARole) {
        this.affectedToARole = affectedToARole;
    }

    @Override
    public boolean equals(Object obj) { // pour pouvoir utiliser la méthode "contains" sur une liste de Menu

        if (this == null && obj == null)
            return true;

        if (this != null && obj != null && obj instanceof Menu)
            return id == ((Menu)obj).getId();

        return super.equals(obj);

    }

}

I want to test if a Set of Menu's contains a particular Menu :

Set<Menu> affected_menus = roleDao.getListMenu(role_code); // gets all menus affected to a role_code

for (Menu menu : temp) {
    if (!affected_menus.isEmpty() && affected_menus.contains(menu))
        menu.setAffectedToARole(true);
    else
        menu.setAffectedToARole(false);
}

At runtime all code goes to menu.setAffectedToARole(false);

So what is wrong ?


问:
Serializing vector of objects to std::string for use with MPI
I am trying to communicate a std::vector<MyClass> with varying size via MPI. MyClass contains members that are vectors that may be uninitialized or vary in size. To do that, I wrote a serialize() und deserialize() function that reads and writes such a std::vector<MyClass> to a std::string, which I then communicate via MPI.

```<code>class MyClass {
    ...
    int some_int_member;
    std::vector<float> some_vector_member;
}

std::vector<MyClass> deserialize(const std::string &in) {
    std::istringstream iss(in);

    size_t total_size;
    iss.read(reinterpret_cast<char *>(&total_size), sizeof(total_size));

    std::vector<MyClass> out_vec;
    out_vec.resize(total_size);

    for(MyClass &d: out_vec) {
        size_t v_size;
        iss.read(reinterpret_cast<char *>(&d.some_int_member), sizeof(d.some_int_member));
        iss.read(reinterpret_cast<char *>(&v_size), sizeof(v_size));
        d.some_vector_member.resize(v_size);
        iss.read(reinterpret_cast<char *>(&d.some_vector_member[0]), v_size * sizeof(float));
    }

    return out_vec;
}

std::string serialize(std::vector<MyClass> &data) {
    std::ostringstream os;

    size_t total_size = data.size();
    os.write(reinterpret_cast<char *>(&total_size), sizeof(total_size));

    for(MyClass &d: data) {
        size_t v_size = d.some_vector_member.size();
        os.write(reinterpret_cast<char *>(&some_int_member), sizeof(some_int_member));
        os.write(reinterpret_cast<char *>(&v_size), sizeof(v_size));
        os.write(reinterpret_cast<char *>(&d.some_vector_member[0]), v_size * sizeof(float));
    }
    return os.str();
}
</code>```

My implementation works in principle, but sometimes (not always!) MPI processes crash at positions I think are related to the serialization. The payload sent can be as big as hundrets of MB. I suspect that using std::string as a container is not a good choice. Are there some limitations using std::string as a container for char[] with huge binary data that I may be running into here?

(Note, that I don't want to use boost::mpi along with its serialization routines, neither do I want to pull in a huge library such as cereal into my project)

答:
Generally, using std::string for binary data is fine although some people might prefer std::vector<char> - or std::vector<std::byte> in C++17 (see also, note C++11 strings guarantee contiguous data). There are two significant efficiency issues in your code:

You always have three copies of the whole data. The original objects, the serialized string and the intermediate [io]stringstream.

You cannot pre-allocate (reserve) data in ostringstream, which may lead to over-allocation and frequent reallocation.

Hence, you waste a significant amount of memory, which might contribute to bad_alloc. That said, it may be perfectly fine and you just have a memory leak somewhere. It's impossible to tell if this is a practical issue for you without knowing the cause of the bad_alloc and a performance analysis of your application.

Body:
I am trying to communicate a std::vector<MyClass> with varying size via MPI. MyClass contains members that are vectors that may be uninitialized or vary in size. To do that, I wrote a serialize() und deserialize() function that reads and writes such a std::vector<MyClass> to a std::string, which I then communicate via MPI.

class MyClass {
    ...
    int some_int_member;
    std::vector<float> some_vector_member;
}

std::vector<MyClass> deserialize(const std::string &in) {
    std::istringstream iss(in);

    size_t total_size;
    iss.read(reinterpret_cast<char *>(&total_size), sizeof(total_size));

    std::vector<MyClass> out_vec;
    out_vec.resize(total_size);

    for(MyClass &d: out_vec) {
        size_t v_size;
        iss.read(reinterpret_cast<char *>(&d.some_int_member), sizeof(d.some_int_member));
        iss.read(reinterpret_cast<char *>(&v_size), sizeof(v_size));
        d.some_vector_member.resize(v_size);
        iss.read(reinterpret_cast<char *>(&d.some_vector_member[0]), v_size * sizeof(float));
    }

    return out_vec;
}

std::string serialize(std::vector<MyClass> &data) {
    std::ostringstream os;

    size_t total_size = data.size();
    os.write(reinterpret_cast<char *>(&total_size), sizeof(total_size));

    for(MyClass &d: data) {
        size_t v_size = d.some_vector_member.size();
        os.write(reinterpret_cast<char *>(&some_int_member), sizeof(some_int_member));
        os.write(reinterpret_cast<char *>(&v_size), sizeof(v_size));
        os.write(reinterpret_cast<char *>(&d.some_vector_member[0]), v_size * sizeof(float));
    }
    return os.str();
}

My implementation works in principle, but sometimes (not always!) MPI processes crash at positions I think are related to the serialization. The payload sent can be as big as hundrets of MB. I suspect that using std::string as a container is not a good choice. Are there some limitations using std::string as a container for char[] with huge binary data that I may be running into here?

(Note, that I don't want to use boost::mpi along with its serialization routines, neither do I want to pull in a huge library such as cereal into my project)


问:
Entity Framework 6 memory leak
I use EF6 with an SQLite database. I create and dispose DBContext objects for each request, but want to I cache the SQLiteConnection objects, so the database stays cached in memory. It looks as if EF leaks memory under these circumstances.

Here's a minimal working sample:

```<code>class Program
{
    static void Main(string[] args)
    {
        // use one connection for the lifetime of the application
        using (var conn = new System.Data.SQLite.SQLiteConnection("Data Source=:MEMORY:"))
        {
            // create sample DB
            conn.Open();
            using (var context = new MyContext(conn, false))
                context.Database.ExecuteSqlCommand("CREATE TABLE SomeTable(Id INTEGER PRIMARY KEY AUTOINCREMENT)");

            while (true)
            {
                // access database
                using (var context = new MyContext(conn, false))
                {
                    var x = System.Linq.Enumerable.Count(context.SomeTable);
                }
                // show memory usage
                System.Console.Write("{0:0,0} Bytes   \r", System.GC.GetTotalMemory(false));
            }
        }
    }
}

class MyContext : System.Data.Entity.DbContext
{
    public MyContext(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection)
        : base(existingConnection, contextOwnsConnection)
    { }

    public System.Data.Entity.DbSet<SomeTableRow> SomeTable { get; set; }
}

[System.ComponentModel.DataAnnotations.Schema.Table("SomeTable")]
class SomeTableRow
{
    public int Id { get; set; }
}
</code>```

If I run this, the process memory usage keeps increasing.

I think the problem is that System.Data.Entity.Core.EntityClient.EntityConnection subscribes to the StateChange event on the connection object and never unsubscribes from it.

My (very ugly) workaround is to manually "clear" the StateChange event field after each use, like this:

```<code>conn
    .GetType()
    .GetField("StateChange", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
    .SetValue(conn, null);
</code>```

Is this a known problem? Is there a better workaround?

答:
I had the same problem.  Calling Dispose() on the EntityConnection seems to resolve the issue.</p>

```<code>public class CustomDbContext : DbContext
{
    private EntityConnection _entityConnection;

    public CustomDbContext(EntityConnection connection)
        : base(connection, false)
    {
        _entityConnection = connection;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing && _entityConnection != null)
            _entityConnection.Dispose();
    }
}
</code>```

Title: Entity Framework 6 memory leak

Body:
I use EF6 with an SQLite database. I create and dispose DBContext objects for each request, but want to I cache the SQLiteConnection objects, so the database stays cached in memory. It looks as if EF leaks memory under these circumstances.

Here's a minimal working sample:

class Program
{
    static void Main(string[] args)
    {
        // use one connection for the lifetime of the application
        using (var conn = new System.Data.SQLite.SQLiteConnection("Data Source=:MEMORY:"))
        {
            // create sample DB
            conn.Open();
            using (var context = new MyContext(conn, false))
                context.Database.ExecuteSqlCommand("CREATE TABLE SomeTable(Id INTEGER PRIMARY KEY AUTOINCREMENT)");

            while (true)
            {
                // access database
                using (var context = new MyContext(conn, false))
                {
                    var x = System.Linq.Enumerable.Count(context.SomeTable);
                }
                // show memory usage
                System.Console.Write("{0:0,0} Bytes   \r", System.GC.GetTotalMemory(false));
            }
        }
    }
}

class MyContext : System.Data.Entity.DbContext
{
    public MyContext(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection)
        : base(existingConnection, contextOwnsConnection)
    { }

    public System.Data.Entity.DbSet<SomeTableRow> SomeTable { get; set; }
}

[System.ComponentModel.DataAnnotations.Schema.Table("SomeTable")]
class SomeTableRow
{
    public int Id { get; set; }
}

If I run this, the process memory usage keeps increasing.

I think the problem is that System.Data.Entity.Core.EntityClient.EntityConnection subscribes to the StateChange event on the connection object and never unsubscribes from it.

My (very ugly) workaround is to manually "clear" the StateChange event field after each use, like this:

conn
    .GetType()
    .GetField("StateChange", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
    .SetValue(conn, null);

Is this a known problem? Is there a better workaround?

Body:
I had the same problem.  Calling Dispose() on the EntityConnection seems to resolve the issue.

public class CustomDbContext : DbContext
{
    private EntityConnection _entityConnection;

    public CustomDbContext(EntityConnection connection)
        : base(connection, false)
    {
        _entityConnection = connection;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing && _entityConnection != null)
            _entityConnection.Dispose();
    }
}