Rectangle 27 367

In Python, what is the purpose of __slots__ and what are the cases one...

The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:

The space savings is from

  • Storing value references in slots instead of __dict__.
  • Denying __dict__ and __weakref__ creation if parent classes deny them and you declare __slots__.

The biggest caveat is for multiple inheritance - multiple "parent classes with nonempty slots" cannot be combined. To accomodate this restriction, follow best practices: Factor out all but one or all parents' abstraction which their concrete class respectively and your new concrete class collectively will inherit from - giving the abstraction(s) empty slots (just like abstract base classes in the standard library).

There are a lot of details if you wish to keep reading.

The creator of Python, Guido van Rossum, states that he actually created __slots__ for faster attribute access.

import timeit

class Foo(object): __slots__ = 'foo',

class Bar(object): pass

slotted = Foo()
not_slotted = Bar()

def get_set_delete_fn(obj):
    def get_set_delete():
        obj.foo = 'foo'
        obj.foo
        del obj.foo
    return get_set_delete

and

>>> min(timeit.repeat(get_set_delete_fn(slotted)))
0.2846834529991611
>>> min(timeit.repeat(get_set_delete_fn(not_slotted)))
0.3664822799983085

The slotted access is almost 30% faster in Python 3.5 on Ubuntu.

>>> 0.3664822799983085 / 0.2846834529991611
1.2873325658284342

In Python 2 on Windows I have measured it about 15% faster.

Another purpose of __slots__ is to reduce the space in memory that each object instance takes up.

The space saved over using __dict__ can be significant.

To verify this, using the Anaconda distribution of Python 2.7 on Ubuntu Linux, with guppy.hpy (aka heapy) and sys.getsizeof, the size of a class instance without __slots__ declared, and nothing else, is 64 bytes. That does not include the __dict__. Thank you Python for lazy evaluation again, the __dict__ is apparently not called into existence until it is referenced, but classes without data are usually useless. When called into existence, the __dict__ attribute is a minimum of 280 bytes additionally.

In contrast, a class instance with __slots__ declared to be () (no data) is only 16 bytes, and 56 total bytes with one item in slots, 64 with two.

I tested when my particular implementation of dicts size up by enumerating alphabet characters into a dict, and on the sixth item it climbs to 1048, 22 to 3352, then 85 to 12568 (rather impractical to put that many attributes on a single class, probably violating the single responsibility principle there.)

attrs  __slots__    no slots declared + __dict__
none       16        64 (+ 280 if __dict__ referenced)
one        56        64 + 280
two        64        64 + 280
six        96        64 + 1048
22        224        64 + 3352

So we see how nicely __slots__ scale for instances to save us memory, and that is the reason you would want to use __slots__.

To deny the creation of a __dict__, you must subclass object:

class Base(object): 
    __slots__ = ()
>>> b = Base()
>>> b.a = 'a'
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    b.a = 'a'
AttributeError: 'Base' object has no attribute 'a'

Or subclass another class that defines __slots__

class Child(Base):
    __slots__ = ('a',)
>>> c = Child()
>>> c.a = 'a'
>>> c.b = 'b'
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    c.b = 'b'
AttributeError: 'Child' object has no attribute 'b'

To allow __dict__ creation while subclassing slotted objects, just add '__dict__' to the __slots__ (note that slots are ordered, and you shouldn't repeat slots that are already in parent classes):

class SlottedWithDict(Child): 
    __slots__ = ('__dict__', 'b')

>>> swd = SlottedWithDict()
>>> swd.a = 'a'
>>> swd.b = 'b'
>>> swd.c = 'c'
>>> swd.__dict__
{'c': 'c'}

Or you don't even need to declare __slots__ in your subclass, and you will still use slots from the parents, but not restrict the creation of a __dict__:

>>> class NoSlots(Child): pass
>>> ns = NoSlots()
>>> ns.a = 'a'
>>> ns.b = 'b'
>>> ns.__dict__
{'b': 'b'}
>>> class BaseA(object): __slots__ = ('a',)
>>> class BaseB(object): __slots__ = ('b',)
>>> class Child(BaseA, BaseB): __slots__ = ()
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    class Child(BaseA, BaseB): __slots__ = ()
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict

If you run into this problem, just remove __slots__, and put it back in where you have a lot of instances.

>>> class BaseA(object): __slots__ = ()
>>> class BaseB(object): __slots__ = ()
>>> class Child(BaseA, BaseB): __slots__ = ('a', 'b')
>>> c = Child
>>> c.a = 'a'
>>> c.b = 'b'
>>> c.c = 'c'
>>> c.__dict__
<dictproxy object at 0x10C944B0>
>>> c.__dict__['c']
'c'
class Foo(object):
    __slots__ = 'bar', 'baz', '__dict__'

and now:

>>> foo = Foo()
>>> foo.boink = 'boink'

So with '__dict__' in slots we lose some of the size benefits with the upside of having dynamic assignment and still having slots for the names we do expect.

When you inherit from an object that isn't slotted, you get the same sort of semantics when you use __slots__ - names that are in __slots__ point to slotted values, while any other values are put in the instance's __dict__.

Avoiding __slots__ because you want to be able to add attributes on the fly is actually not a good reason - just add "__dict__" to your __slots__ if this is required.

You can similarly add __weakref__ to __slots__ explicitly if you need that feature.

The namedtuple builtin make immutable instances that are very lightweight (essentially, the size of tuples) but to get the benefits, you need to do it yourself if you subclass them:

from collections import namedtuple
class MyNT(namedtuple('MyNT', 'bar baz')):
    """MyNT is an immutable and lightweight object"""
    __slots__ = ()
>>> nt = MyNT('bar', 'baz')
>>> nt.bar
'bar'
>>> nt.baz
'baz'

And trying to assign an unexpected attribute raises an AttributeError because we have prevented the creation of __dict__:

>>> nt.quux = 'quux'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyNT' object has no attribute 'quux'

You can allow __dict__ creation by leaving off __slots__ = (), but you can't use non-empty __slots__ with subtypes of tuple.

Even when non-empty slots are the same for multiple parents, they cannot be used together:

'__dict__'

the creation of a __dict__

>>> class Foo(object): __slots__ = ()
>>> class Bar(object): __slots__ = ()
>>> class Baz(Foo, Bar): __slots__ = ('foo', 'bar')
>>> b = Baz()
>>> b.foo, b.bar = 'foo', 'bar'

You don't have to have slots - so if you add them, and remove them later, it shouldn't cause any problems.

Going out on a limb here: If you're composing mixins or using abstract base classes, which aren't intended to be instantiated, an empty __slots__ in those parents seems to be the best way to go in terms of flexibility for subclassers.

  • Avoid them when you want to perform __class__ assignment with another class that doesn't have them (and you can't add them) unless the slot layouts are identical. (I am very interested in learning who is doing this and why.)
  • Avoid them if you want to subclass variable length builtins like long, tuple, or str, and you want to add attributes to them.
  • Avoid them if you insist on providing default values via class attributes for instance variables.
  • Avoid them for parent classes in the case of multiple inheritance - you can reinsert them for a child where you have a lot of instances (see previous section for recommendation).

You may be able to tease out further caveats from the rest of the __slots__ documentation (the 3.7 dev docs are the most current), which I have made significant recent contributions to.

The current top answers cite outdated information and are quite hand-wavy and miss the mark in some important ways.

"You would want to use __slots__ if you are going to instantiate a lot (hundreds, thousands) of objects of the same class."

Abstract Base Classes, for example, from the collections module, are not instantiated, yet __slots__ are declared for them.

If a user wishes to deny __dict__ or __weakref__ creation, those things must not be available in the parent classes.

__slots__

It is true that many Python users aren't writing for reusability, but when you are, having the option to deny unnecessary space usage is valuable.

When pickling a slotted object, you may find it complains with a misleading TypeError:

This is actually incorrect. This message comes from the oldest protocol, which is the default. You can select the latest protocol with the -1 argument. In Python 2.7 this would be 2 (which was introduced in 2.3), and in 3.6 it is 4.

in Python 2.7:

in Python 3.6

>>> pickle.loads(pickle.dumps(f, 4))
<__main__.Foo object at 0x1129C770>

So I would keep this in mind, as it is a solved problem.

The first paragraph is half short explanation, half predictive. Here's the only part that actually answers the question

The proper use of __slots__ is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots

The second half is wishful thinking, and off the mark:

While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.

Python actually does something similar to this, only creating the __dict__ when it is accessed, but creating lots of objects with no data is fairly ridiculous.

The second paragraph oversimplifies and misses actual reasons to avoid __slots__. The below is not a real reason to avoid slots (for actual reasons, see the rest of my answer above.):

They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies.

It then goes on to discuss other ways of accomplishing that perverse goal with Python, not discussing anything to do with __slots__.

The third paragraph is more wishful thinking. Together it is mostly off-the-mark content that the answerer didn't even author and contributes to ammunition for critics of the site.

>>> class Foo(object): pass
>>> class Bar(object): __slots__ = ()

Instantiate a million of them:

>>> foos = [Foo() for f in xrange(1000000)]
>>> bars = [Bar() for b in xrange(1000000)]
guppy.hpy().heap()
>>> guppy.hpy().heap()
Partition of a set of 2028259 objects. Total size = 99763360 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 1000000  49 64000000  64  64000000  64 __main__.Foo
     1     169   0 16281480  16  80281480  80 list
     2 1000000  49 16000000  16  96281480  97 __main__.Bar
     3   12284   1   987472   1  97268952  97 str
...

Access the regular objects and their __dict__ and inspect again:

>>> for f in foos:
...     f.__dict__
>>> guppy.hpy().heap()
Partition of a set of 3028258 objects. Total size = 379763480 bytes.
 Index  Count   %      Size    % Cumulative  % Kind (class / dict of class)
     0 1000000  33 280000000  74 280000000  74 dict of __main__.Foo
     1 1000000  33  64000000  17 344000000  91 __main__.Foo
     2     169   0  16281480   4 360281480  95 list
     3 1000000  33  16000000   4 376281480  99 __main__.Bar
     4   12284   0    987472   0 377268952  99 str
...

If you subclass a built-in type, extra space is automatically added to the instances to accomodate __dict__ and __weakrefs__. (The __dict__ is not initialized until you use it though, so you shouldn't worry about the space occupied by an empty dictionary for each instance you create.) If you don't need this extra space, you can add the phrase "__slots__ = []" to your class.

python - Usage of __slots__? - Stack Overflow

python slots
Rectangle 27 52

What behaviour or state are you verifying? Specifically, are you verifying that the collaborator (data) is having its ListCount method called (interaction based testing), or do you just want to make ListCount return a canned value to drive the class under test while verifying the result elsewhere (traditional state based testing)?

MockRepository.CreateMock<IMyInterface>()
myMock.Expect(x => x.ListCount())
MockRepository.CreateStub<IMyInterface>()
myStub.Stub(x => x.ListCount())

(aside: I know you can use stub.AssertWasCalled() to achieve much the same thing as mock.Expect and with arguably better reading syntax, but I'm just drilling into the difference between mocks & stubs).

We need a complete picture of how you're creating the stub (or mock) and how the result is used with respect to the class under test. Does ListCount have an input parameter? If so, what does it represent? Do you care if it was called with a certain value? Do you care if ListCount returns a certain value?

As Simon Laroche pointed out, if the Manager is not actually doing anything with the mocked/stubbed return value of ListCount, then the test won't pass or fail because of it. All the test would expect is that the mocked/stubbed method is called -- nothing more.

To better understand the problem, consider three pieces of information and you will soon figure this out:

  • What is the expected result?

Interaction based testing with mocks

State based testing with a stub. The stub drives the test, but is not a part of the expectation.

[Test]
public void calling_ListCount_returns_same_count_as_DAL()
{
   // Arrange
   var dalStub = MockRepository.Stub<IDAL>();
   var dalStub.Stub(x => x.ListCount()).Returns(1);
   var manager = new Manager(dalMock);

   // Act
   int listCount = manager.ListCount();

   // Assert -- Test is 100% state based
   Assert.That(listCount, Is.EqualTo(1),
       "count should've been identical to the one returned by the dal!");
}

The distinction between a mock and a stub in rhino mocks is muddled. Traditionally, stubs aren't meant to have expectations -- so if your test double didn't have its method called, this wouldn't directly cause the test to fail.

... However, the Rhino Mocks API is powerful, but confusing as it lets you set expectations on stubs which, to me, goes against the accepted terminology. I don't think much of the terminology, either, mind. It'd be better if the distinction was eliminated and the methods called on the test double set the role, in my opinion.

+1 from me. Am also new to Rhino Mocks. Thanks for showing .Stub. I had been using .Expect because that was what all the examples used...

I always do behavior testing using stubs, Like it is done in ayende's post: ayende.com/blog/3384/

testing - Rhino Mocks - Stub .Expect vs .AssertWasCalled - Stack Overf...

testing tdd mocking rhino-mocks bdd
Rectangle 27 52

What behaviour or state are you verifying? Specifically, are you verifying that the collaborator (data) is having its ListCount method called (interaction based testing), or do you just want to make ListCount return a canned value to drive the class under test while verifying the result elsewhere (traditional state based testing)?

MockRepository.CreateMock<IMyInterface>()
myMock.Expect(x => x.ListCount())
MockRepository.CreateStub<IMyInterface>()
myStub.Stub(x => x.ListCount())

(aside: I know you can use stub.AssertWasCalled() to achieve much the same thing as mock.Expect and with arguably better reading syntax, but I'm just drilling into the difference between mocks & stubs).

We need a complete picture of how you're creating the stub (or mock) and how the result is used with respect to the class under test. Does ListCount have an input parameter? If so, what does it represent? Do you care if it was called with a certain value? Do you care if ListCount returns a certain value?

As Simon Laroche pointed out, if the Manager is not actually doing anything with the mocked/stubbed return value of ListCount, then the test won't pass or fail because of it. All the test would expect is that the mocked/stubbed method is called -- nothing more.

To better understand the problem, consider three pieces of information and you will soon figure this out:

  • What is the expected result?

Interaction based testing with mocks

State based testing with a stub. The stub drives the test, but is not a part of the expectation.

[Test]
public void calling_ListCount_returns_same_count_as_DAL()
{
   // Arrange
   var dalStub = MockRepository.Stub<IDAL>();
   var dalStub.Stub(x => x.ListCount()).Returns(1);
   var manager = new Manager(dalMock);

   // Act
   int listCount = manager.ListCount();

   // Assert -- Test is 100% state based
   Assert.That(listCount, Is.EqualTo(1),
       "count should've been identical to the one returned by the dal!");
}

The distinction between a mock and a stub in rhino mocks is muddled. Traditionally, stubs aren't meant to have expectations -- so if your test double didn't have its method called, this wouldn't directly cause the test to fail.

... However, the Rhino Mocks API is powerful, but confusing as it lets you set expectations on stubs which, to me, goes against the accepted terminology. I don't think much of the terminology, either, mind. It'd be better if the distinction was eliminated and the methods called on the test double set the role, in my opinion.

+1 from me. Am also new to Rhino Mocks. Thanks for showing .Stub. I had been using .Expect because that was what all the examples used...

I always do behavior testing using stubs, Like it is done in ayende's post: ayende.com/blog/3384/

testing - Rhino Mocks - Stub .Expect vs .AssertWasCalled - Stack Overf...

testing tdd mocking rhino-mocks bdd
Rectangle 27 1

This is the expected result here is why:

The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

EDIT: Here is additional info from Microsoft's docs to answer the question that you posted in your comment:

Model validation occurs prior to each controller action being invoked, and it is the action methods responsibility to inspect ModelState.IsValid and react appropriately. In many cases, the appropriate reaction is to return some kind of error response, ideally detailing the reason why model validation failed.

So as mentioned in the documentation:

Thanks Univ, I am however in doubt, whether this approach describes the situation. The key here is, that the Id field does not get validated at all, as it is not part of the modelstate object. To reiterate, the Id property does not go through validation at all, it doesn't have either a false nor a true state, as it isn't one of modelstate key,value pairs. Even though, the parameter variable, upon construction, has the Id property set to 0 (because that is the default for Int), the 0 is set there by the constructor because it is not recieved from the view.

Thanks, thats a good explanation there in that doc, that the validation will only be applied to items submitted by the form. Since the view doesn't send that property, it does not go through validation at all.

c# - ModelState.IsValid ignores validation of the non-nullable propert...

c# .net asp.net-mvc validation
Rectangle 27 257

It's done so that addition doesn't need to have any special logic for dealing with negative numbers. Check out the article on Wikipedia.

Say you have two numbers, 2 and -1. In your "intuitive" way of representing numbers, they would be 0010 and 1001, respectively (I'm sticking to 4 bits for size). In the two's complement way, they are 0010 and 1111. Now, let's say I want to add them.

Two's complement addition is very simple. You add numbers normally and any carry bit at the end is discarded. So they're added as follows:

0010
+ 1111
=10001
= 0001 (discard the carry)

0001 is 1, which is the expected result of "2+(-1)" to be.

0010
+ 1001
= 1011

Which is -3, right? Simple addition doesn't work in this case. You need to note that one of the numbers is negative and use a different algorithm if that's the case.

For this "intuitive" storage method, subtraction is a different operation than addition, requiring additional checks on the numbers before they can be added. Since you want the most basic operations (addition, subtraction, etc) to be as fast as possible, you need to store numbers in a way that lets you use the simplest algorithms possible.

Additionally, in the "intuitive" storage method, there are two zeroes:

0000  "zero"
1000  "negative zero"

Which are intuitively the same number but have two different values when stored. Every application will need to take extra steps to make sure that non-zero values are also not negative zero.

There's another bonus with storing ints this way, and that's when you need to extend the width of the register the value is being stored in. With two's complement, storing a 4-bit number in an 8-bit register is a matter of repeating its most significant bit:

It's just a matter of looking at the sign bit of the smaller word and repeating it until it pads the width of the bigger word.

With your method you would need to clear the existing bit, which is an extra operation in addition to padding:

0001 (one, in four bits)
00000001 (one, in eight bits)
    1010 (negative two, in four bits)
10000010 (negative two, in eight bits)

You still need to set those extra 4 bits in both cases, but in the "intuitive" case you need to clear the 5th bit as well. It's one tiny extra step in one of the most fundamental and common operations present in every application.

cool thanks. that's been bugging me for a while

Did you actually type this up in two minutes?? The original question was asked 8 minutes ago, and this answer was posted 6 minutes ago. Are you truly the Fastest Gun in the West?

@Nathan Fellman: Two's complement math isn't hard. I wrote most of it within my 5-minute edit window.

how we arrived at 2s compliment the first place.

binary - Why prefer two's complement over sign-and-magnitude for signe...

binary math twos-complement negative-number internal-representation
Rectangle 27 2

You have mixed up | and &. Your expected result corresponds to the iteration of:

flags |= (1 << i);

The bitwise OR in |= will "add" bits to your bitset flags, whereas the bitwise AND can only remove bits.

C++ Logical AND Operator - Stack Overflow

c++ operators bitwise-operators logical-operators
Rectangle 27 2

Well, for me this is the expected result; adding six months to Jan. 1st July.

mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01                                 | 
+--------------------------------------------+

In fact the desired result for me would be to have "2011-06-30", but don't really know how to get it...

or you explicitly have to use > and < instead of BETWEEN

The DATE_SUB works fine, thank you. In fact, i focused on the 6 months interval, and didn't really thjough about removing one day afterwards x(

sql - MySQL - DATE_ADD month interval - Stack Overflow

mysql sql select dateadd
Rectangle 27 5

I changed your procedure a bit and added the output of Debug.Print as comment to better explain why this is an expected result:

Option Explicit 'in the first line of your modules: Ensures you need to declare all variables

Sub test6()
    Dim wRange As Range, aRow As Variant
    Set wRange = Range("B3:P10")

    For Each aRow In wRange.Rows
                                                ' Outputs of the first loop run:
        Debug.Print aRow.Address                ' $B$3:$P$3
        Debug.Print aRow.Cells(1, 2).Address    ' $C$3
        Debug.Print Cells(aRow.Row, 2).Address  ' $B$3
    Next
End Sub

ExplanationaRow is a sub range ($B$3:$P$3) out of the original range B3:P10 containing only one row (but not an entire row of the worksheet as you assume) so aRow.Cells(1, 2) refers to column 2 relative to aRow which is C because the range is starting with B not with A.

Cells(aRow.Row, 2) is exactly the same as writing ActiveSheet.Cells(aRow.Row, 2) and refers to column 2 relative to the ActiveSheet which is B because the range of the sheet is starting at A.

aRow.EntireRow.Cells(1, 2).Address
Cells(aRow.Row, 2).Address

Side note: I recommend not to assume the worksheet and fully qualify your cells/ranges so you always see to which range the cells are relative to.

excel - Difference between two ways of accessing a row's cells - Stack...

excel vba excel-vba
Rectangle 27 4

You could use DynamcLinq. I haven't touched it in over a year, but I had the expected results. Your code would change to:

queryResults = queryResults.OrderBy(sort);

c# - Avoid switch case -linq - Stack Overflow

c# .net linq
Rectangle 27 4

You could use DynamcLinq. I haven't touched it in over a year, but I had the expected results. Your code would change to:

queryResults = queryResults.OrderBy(sort);

c# - Avoid switch case -linq - Stack Overflow

c# .net linq
Rectangle 27 23

Using a union query will remove duplicates, and this is different than the behavior of full outer join that never removes any duplicate:

[Table: t1]                            [Table: t2]
value                                  value
-------                                -------
1                                      1
2                                      2
4                                      2
4                                      5

This is the expected result of full outer join:

This is the result of using left and right Join with union:

value | value
------+-------
Null  | 5 
1     | 1
2     | 2
4     | Null
select 
    t1.value, t2.value
from t1 
left outer join t2  
  on t1.value = t2.value
union all      -- Using `union all` instead of `union`
select 
    t1.value, t2.value
from t2 
left outer join t1 
  on t1.value = t2.value
where 
    t1.value IS NULL

Result of above query that is as same as expected result:

value | value
------+-------
1     | 1
2     | 2
2     | 2
4     | NULL
4     | NULL
NULL  | 5
UNION ALL
UNION

I decided to add another solution that comes from full outer join visualization and math, it is not better that above but more readable:

Full outer join means (t1 t2): all in t1 or in t2(t1 t2) = (t1 t2) + t1_only + t2_only: all in both t1 and t2 plus all in t1 that aren't in t2 and plus all in t2 that aren't in t1:

-- (t1  t2): all in both t1 and t2
select t1.value, t2.value
from t1 join t2 on t1.value = t2.value    
union all  -- And plus 
-- all in t1 that not exists in t2
select t1.value, null
from t1
where not exists( select 1 from t2 where t2.value = t1.value)    
union all  -- and plus
-- all in t2 that not exists in t1
select null, t2.value
from t2
where not exists( select 1 from t1 where t2.value = t1.value)
[SQL Fiddle]

We are doing same task tow times , If there are sub query for t1 and t2 then mysql have to do same task more times, is not it ? Can we remove this using alias in this situation ?:

FULL OUTER JOIN

sql - How to do a FULL OUTER JOIN in MySQL? - Stack Overflow

sql mysql join outer-join full-outer-join
Rectangle 27 23

Using a union query will remove duplicates, and this is different than the behavior of full outer join that never removes any duplicate:

[Table: t1]                            [Table: t2]
value                                  value
-------                                -------
1                                      1
2                                      2
4                                      2
4                                      5

This is the expected result of full outer join:

This is the result of using left and right Join with union:

value | value
------+-------
Null  | 5 
1     | 1
2     | 2
4     | Null
select 
    t1.value, t2.value
from t1 
left outer join t2  
  on t1.value = t2.value
union all      -- Using `union all` instead of `union`
select 
    t1.value, t2.value
from t2 
left outer join t1 
  on t1.value = t2.value
where 
    t1.value IS NULL

Result of above query that is as same as expected result:

value | value
------+-------
1     | 1
2     | 2
2     | 2
4     | NULL
4     | NULL
NULL  | 5
UNION ALL
UNION

I decided to add another solution that comes from full outer join visualization and math, it is not better that above but more readable:

Full outer join means (t1 t2): all in t1 or in t2(t1 t2) = (t1 t2) + t1_only + t2_only: all in both t1 and t2 plus all in t1 that aren't in t2 and plus all in t2 that aren't in t1:

-- (t1  t2): all in both t1 and t2
select t1.value, t2.value
from t1 join t2 on t1.value = t2.value    
union all  -- And plus 
-- all in t1 that not exists in t2
select t1.value, null
from t1
where not exists( select 1 from t2 where t2.value = t1.value)    
union all  -- and plus
-- all in t2 that not exists in t1
select null, t2.value
from t2
where not exists( select 1 from t1 where t2.value = t1.value)
[SQL Fiddle]

We are doing same task tow times , If there are sub query for t1 and t2 then mysql have to do same task more times, is not it ? Can we remove this using alias in this situation ?:

FULL OUTER JOIN

sql - How to do a FULL OUTER JOIN in MySQL? - Stack Overflow

sql mysql join outer-join full-outer-join
Rectangle 27 1

Here's a small stylesheet that will lead you to the expected result.

<?xml version="1.0" ?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="*[contains(name(), 'a')]/*[contains(name(), 'a')] | /*[contains(name(), 'a')]">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*">
  </xsl:template>

</xsl:stylesheet>

However I think it's not really clearly stated for the case of the text within an element that has to be skipped.

Morover, how should we process such a case:

<a>
  <z x="x">
    <aa>z
      <ade>Another case</ade>
    </aa>
  </z>
</a>

<z> is to be skipped, but should we do to his contents? Regarding your rules, <ade> should be output because it a child of <aa>, but <aa> is not processed at all because its parent is z (skipped).

It work perfectly! Since it is an assignment, even I don't know what to do in the case presented, the only thing I had to do was understand how to do it for this particular case. That way I understand your code is that you check if any first, second and third child all contains "a" with a 0 to many match... Do I understand it well?

xml - Copy only the nodes where the name contains "a" - Stack Overflow

xml xslt-1.0
Rectangle 27 3

Hey I have noticed the exact same issue. Definitely a chrome thing. Below is an issue I submitted to the chromium project:

Chrome Version       : 21.0.1180.89
OS Version: 6.1 (Windows 7, Windows Server 2008 R2)
URLs (if applicable): http://jsfiddle.net/9vvy6/62/
                      http://castlelaw-kc.fosterwebmarketing.com/
Other browsers tested:
Add OK or FAIL after other browsers where you have tested this issue:
     Safari 5/6:OK
  Firefox 14.0.1:OK
     IE 9:OK
     Chrome:FAIL
  • Background image with background-size:cover
  • Overlaying element (tested with div and a tags) that has a hover effect
  • For best results, use in a large view port, where the bg image is stretched a lot, and the abbarations are most evident

What is the expected result?

When using a activating a hover effect (like underline, margin change, etc.) the background image should stay consistent (and does on all other browsers tested so far)

When the hover effect is activated with mouse, the background image warps oddly. In the area around the element, the bg image shits a few pixels.

Please provide any additional information below. Attach a screenshot if possible.

In the JSFiddle linked above, which uses an ul/li as the example. we determined that changing the ul's display to inline-block corrected the issue.

IMPORTANT: It's super subtle, so you might have to sweep your mouse across the relevant elements a couple times before you notice

css3 - Link hover causes background-size: cover; to shift in Chrome - ...

google-chrome css3 background hover css-transitions
Rectangle 27 2

I'm not sure I understand what should be the expected result at the end so let me just give you some inputs.

To iterate over the entries of a Map and to get the value and the key of the current entry we proceed as next:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>

So here for example, it would be something like:

<c:forEach var="e" items="${images.holder}">
<div class="hex col-sm-6">
    <div>
        <div class="hexagon hexagon2 gallery-item">
            <div class="hexagon-in1">
                <div class="hexagon-in2" style="background-image: url(<c:out value="${e.value}"/>);">
                    <div class="overlay">
                        <a href="<c:out value="${e.value}"/>" data-rel="lightbox" class="fa fa-expand"></a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</c:forEach>

NB: This is meant to give you the main idea not to give you the complete solution.

Thanks a lot. This works perfectly fine. Also if I need to know whether I am iterating first element or second element or third element in a map, how can I do that? I just need an indication basically I need to add a check with if statement that if it is the first element then do this and if it is second element, then do that.

hashmap - How to generate div's dynamically by iterating map using jst...

jsp hashmap jstl
Rectangle 27 9

The problem is the event on which you call this. $(document).ready() is fired when the current DOM has been loaded. So it's triggered when the 3 main frames are loaded. But at this point these frames didn't load their iframes yet. By changing the event to window.onload, you should have the expected result. Like this:

$(window).load(function(){
    ...
window.onload = function(){
    ...

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

Can you also take a look on thing I came across by the way of trying to solve my problem, I mean document.addEventListener does not work while using on document that consist only of frameset, and share your thoughts about it?

The problem with keydown listener (or any event that you apply on window or document), is that these events will be triggered on one of the sub frames, not on the top window. You could add these events on these sub frames, but you'll still need them to be loaded, so your back with the same problem.

javascript - Java Script, Difficulty getting list of all nested frames...

javascript jquery html greasemonkey frames
Rectangle 27 17

If you are using Hibernate, this is the expected result. When you call translationRepository.saveAndFlush(translation) and translationRepository.findOne(t.getId()) one after the other, they hit the same Hibernate session which maintains a cache of all objects that it has worked on. Therefore, the second call simply returns the object passed to the first. There is nothing in those two lines that would have forced Hibernate to fire a SELECT query on the database for the Version entity.

Now, the JPA spec does have a refresh method on the EntityManager interface. Unfortunately, Spring Data JPA does not expose this method using its JpaRepository interface. If this method was available, you could have done t = translationRepository.saveAndFlush(translation) and then versionRepository.refresh(t.getVersion()) to force the JPA provider to synchronize the version entity with the database.

Implementing this method is not difficult. Just extend SimpleJpaRepository class from Spring Data JPA and implement the method yourself. For details see adding custom behaviour to all Spring Data JPA repositories.

An alternate would be to load the version entity as versionRepository.findOne(version.getId()) before setting it on the translation. Since you can hard-code version id in your code, your versions seem to be static. You can therefore mark your Version entity as @Immutable and @Cacheable (the former is a Hibernate-specific annotation). That way, versionRepository.findOne(version.getId()) should not hit the database every time it is called.

thanks, indeed I also came into conclusion and used the second approach. Btw, version is not harcoded, it's here just for simplicity.

java - JpaRepository caches newly created object. How to refresh it? -...

java jpa spring-data-jpa
Rectangle 27 10

/Za
5.4

The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.[ Note: if T is a non-class type that is cv-qualified, the cv-qualifiers are ignored when determining the type of the resulting prvalue; see 3.10. end note ]

Both gcc and clang result in rvalue which is the expected result.

As an aside, I would recommend using rextester over webcompiler since rextester allows you to share your program and also has live sharing.

Mgetz filed a bug report, the response was that this is fixed by using the /Zc:rvalueCast flag, the description of the flag is as follows:

When the /Zc:rvalueCast option is specified, the compiler correctly identifies an rvalue reference type as the result of a cast operation in accordance with the C++11 standard. When the option is not specified, the compiler behavior is the same as in Visual Studio 2012. By default, /Zc:rvalueCast is off. For conformance and to eliminate errors in the use of casts, we recommend that you use /Zc:rvalueCast.

+1 for your recommendation. how long does the live sharing link lives?

@MinimusHeximus not sure, I have only used for short periods and th site does not document it.

The language extension that binds an rvalue to an lvalue-reference only works if there is an object; that's not true for prvalues of fundamental types rextester.com/TOJWJL48414. Strangely, gcc once had a similar "extension" that allowed the result of a cast to be used as an lvalue: gcc.gnu.org/gcc-3.4/changes.html (cast-as-lvalue)

I can only hypothesize that (char) i = 5; is more convenient to write than *((char*)&i) = 5; (in C). You can find some discussion when searching for "cast-as-lvalue". E.g. it seems to have been in early C89 drafts.

c++ - Is the result of a cast an rvalue? - Stack Overflow

c++ visual-c++ casting standards lvalue
Rectangle 27 7

This is the expected result. The use_ok call is at run-time, so the mod_table sub is only compiled and imported after the "call" to it is encountered during compilation, so the "call" to mod_table is interpreted as an illegal bareword.

This code produces the same warnings/error, both on 5.8 and 5.10.

perl -e'use strict; use warnings; my %table; mod_table %table => (1,2,3,4)'

Because the lack of compile-time import can affect the compiled test code in ways like this, it's a good idea to use use instead of use_ok in all tests except a test dedicated to just doing the use_ok (potentially with a BAIL_OUT). (Putting the use_ok in a BEGIN block alleviates these kind of problems but can cause other problems, so isn't a good idea.)

Did Perl 5.10 mess something up with prototypes? - Stack Overflow

perl prototype perl5.10
Rectangle 27 347

alias_method can be redefined if need be. (it's defined in the Module class.)

alias
alias_method
def foo
  "foo"
end

alias_method :baz, :foo

What do you mean by unpredictable. Navely, one would say that the option that is less flexible will be more predictable. Also, can you provide any practical example of benefitting from redefining alias_method?

alias :new_method_name :old_method_name
alias_method :new_method_name, :old_method_name

The word he's looking for here is more expected results. alias_method is determined at runtime and not when the code is read, like alias, so it behaves more how we would expect it to.

expecting that methods are defined on the fly during runtime is not what most programmers expect. At least it's like flying pigs to me.

ruby - Should I use alias or alias_method? - Stack Overflow

ruby alias