问:
UICollectionView cells recalculating sizes (flicker) while scrolling
After initial table load, everything is working correctly. But after inserting a new cell, and scrolling fast up, you can see some cells recalculating their sizes (animating). It's really odd and happens to 2-3 cells max. I'm using a bottom-up collection view with reversed cells, and custom flow layout, but it has no animation either. Also when scrolling, keyboard hides, so it might be something to do with it..

Cell insert :

```<code>  self.collectionView?.insertItems(at: [indexPath])

  UIView.performWithoutAnimation {
      self.collectionView?.reloadItems(at: indexPaths)
      self.view.layoutIfNeeded()
  }
  self.collectionView?.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
</code>```

Video of the issue:

http://vimple.co/3c39cb325b9c4ec19173fea015b6cc8b

```<code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let newIndex : Int = messagesDataArray.count - 1 - indexPath.item
    if messagesDataArray[newIndex].otherPerson == true {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ConversationCellOtherPerson", for: indexPath) as! ConversationCellOtherPerson
        cell.data = messagesDataArray[newIndex]
        cell.personImageView.image = otherPersonImage
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ConversationCellUser", for: indexPath) as! ConversationCellUser
        cell.data = messagesDataArray[newIndex]
        return cell
    }

}
</code>```

Also. ConversationCellUser:

```<code>class ConversationCellUser : UICollectionViewCell {

    let messageLabel = ConversationLabel()
    let mainContainerView = UIView()
    let textContainerView : UIView = {
        let view = UIView()
        view.layer.cornerRadius = 20
        return view
    }()

    var data : MessagesInfo? { didSet { updateCell() } }

    func updateCell() {
        guard let data = data else { return }
        messageLabel.text = data.messageText
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .clear
        clipsToBounds = true

        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        textContainerView.translatesAutoresizingMaskIntoConstraints = false
        mainContainerView.translatesAutoresizingMaskIntoConstraints = false

        mainContainerView.addSubview(textContainerView)
        textContainerView.addSubview(messageLabel)
        contentView.addSubview(mainContainerView)

        NSLayoutConstraint(item: textContainerView, attribute: .right, relatedBy: .equal, toItem: mainContainerView, attribute: .right, multiplier: 1, constant: -10).isActive = true

        textContainerView.addConstraintsWithFormat(format: "H:|-14-[v0]-14-|", views: messageLabel)
        textContainerView.addConstraintsWithFormat(format: "V:|-10-[v0]-10-|", views: messageLabel)

        contentView.addConstraintsWithFormat(format: "H:|[v0]|", views: mainContainerView)
        contentView.addConstraintsWithFormat(format: "V:|[v0]|", views: mainContainerView)

        textContainerView.backgroundColor = .lightGray

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
        super.apply(layoutAttributes)
        transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: 0)
        updateConstraints()
        setNeedsUpdateConstraints()

    }
}
</code>```

ConversationLabel :

```<code>class ConversationLabel : BaseMessageLabel {

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.textColor = .white
        self.font = UIFont(name: "AvenirNext-Medium", size: 14)
        self.lineBreakMode = .byWordWrapping
        self.numberOfLines = 0

        self.preferredMaxLayoutWidth = 200
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

SizeForItem :

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    var height : CGFloat = 80

    let text = messagesDataArray[indexPath.row].messageText

    height = estimateFrameFor(text).height + 20

    return CGSize(width: collectionView.bounds.size.width, height: height)

}

private func estimateFrameFor(_ text : String) -> CGRect {
    let size = CGSize(width: 200, height: 1000)
    return NSString(string: text).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 14)!], context: nil)
}
</code>```

And the FlowLayout I'm using is this :

Github - jochenschoellig - ChatCollectionViewFlowLayout

Hey, I have created a small project with the problem:
Github - testLP

答:
Can't comment, not enough rep. But as was commented, please provide your code for the ConversationLabel class, the sizeForItemAtIndexPath override as well as your custom FlowLayout class. When you add custom layout classes, it's easy to overlook certain resulting behaviors.

Without those methods given, you won't have much luck here. When you do, I'll look and update my answer.

However, judging from the video, here's what I'd look at first:

Since cells are re-added to the visible part of the collectionview when their index becomes visible, it is possible that the animation is either due to sizing that you apply inside of sizeForItemAtIndexPath which might be delayed if whatever cell element you use to apply the size is not updated quickly enough. Or that the animation is somehow visible due to lag, since you do call constraint resetters each time the cell views are brought into view ( this could cause some lag depending on the device).
I'm suggesting the latter, because of your apply(_ layoutAttributes: UICollectionViewLayoutAttributes) override. Given the documentation here: you're calling updateConstraints() once, and then using setNeedsUpdateConstraints() right after, which schedules an updateConstraints() call on layout of the cell view when it becomes visible (which is when you're seeing the animation). So you're doing the work twice here, which could add to the animation queue. Or, since you're also resetting the transform attribute, you're might also be scheduling an extra animation that you might not have taken into account.
Finally, While this might hint at where this behavior is stemming from, it's impossible to say without your custom FlowLayout class. As mentioned here:

If you subclass and implement any custom layout attributes, you must
  also override the inherited isEqual: method to compare the values of
  your properties. In iOS 7 and later, the collection view does not
  apply layout attributes if those attributes have not changed. It
  determines whether the attributes have changed by comparing the old
  and new attribute objects using the isEqual: method.

And, as is referred to in this post about iOS7 and later os builds:
 since you override the apply(_ layoutAttributes: UICollectionViewLayoutAttributes) method, you are also supposed to override the isEqual(_ object: Any?) method with your own code which compares layout attributes the way you want.

An example of the isEqual override:

```<code>override public func isEqual(_ object: Any?) -> Bool {
        guard let rhs = object as? DateClass else {
            return false
        }
        let lhs = self

        return lhs.date1 == rhs.date1 &&
            lhs.date2 == rhs.date2 &&
            lhs.date3 == rhs.date3
    }
</code>```

You'd swap out DateClass with your UICollectionViewLayoutAttributes, putting the override inside the scope of your UICollectionViewLayoutAttributes subclass.

So as far what I can tell with what you've given, it seems like there might be accidental over-calling of certain methods in your code. Or perhaps you didn't subclass UICollectionViewLayoutAttributes properly. Again, these are my best solutions for what you provide. Add the missing code, and I will update answer!

Body:
After initial table load, everything is working correctly. But after inserting a new cell, and scrolling fast up, you can see some cells recalculating their sizes (animating). It's really odd and happens to 2-3 cells max. I'm using a bottom-up collection view with reversed cells, and custom flow layout, but it has no animation either. Also when scrolling, keyboard hides, so it might be something to do with it..

Cell insert :

  self.collectionView?.insertItems(at: [indexPath])

  UIView.performWithoutAnimation {
      self.collectionView?.reloadItems(at: indexPaths)
      self.view.layoutIfNeeded()
  }
  self.collectionView?.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

Video of the issue:

http://vimple.co/3c39cb325b9c4ec19173fea015b6cc8b

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let newIndex : Int = messagesDataArray.count - 1 - indexPath.item
    if messagesDataArray[newIndex].otherPerson == true {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ConversationCellOtherPerson", for: indexPath) as! ConversationCellOtherPerson
        cell.data = messagesDataArray[newIndex]
        cell.personImageView.image = otherPersonImage
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ConversationCellUser", for: indexPath) as! ConversationCellUser
        cell.data = messagesDataArray[newIndex]
        return cell
    }

}

Also. ConversationCellUser:

class ConversationCellUser : UICollectionViewCell {

    let messageLabel = ConversationLabel()
    let mainContainerView = UIView()
    let textContainerView : UIView = {
        let view = UIView()
        view.layer.cornerRadius = 20
        return view
    }()

    var data : MessagesInfo? { didSet { updateCell() } }

    func updateCell() {
        guard let data = data else { return }
        messageLabel.text = data.messageText
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = .clear
        clipsToBounds = true

        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        textContainerView.translatesAutoresizingMaskIntoConstraints = false
        mainContainerView.translatesAutoresizingMaskIntoConstraints = false

        mainContainerView.addSubview(textContainerView)
        textContainerView.addSubview(messageLabel)
        contentView.addSubview(mainContainerView)

        NSLayoutConstraint(item: textContainerView, attribute: .right, relatedBy: .equal, toItem: mainContainerView, attribute: .right, multiplier: 1, constant: -10).isActive = true

        textContainerView.addConstraintsWithFormat(format: "H:|-14-[v0]-14-|", views: messageLabel)
        textContainerView.addConstraintsWithFormat(format: "V:|-10-[v0]-10-|", views: messageLabel)

        contentView.addConstraintsWithFormat(format: "H:|[v0]|", views: mainContainerView)
        contentView.addConstraintsWithFormat(format: "V:|[v0]|", views: mainContainerView)

        textContainerView.backgroundColor = .lightGray

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
        super.apply(layoutAttributes)
        transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: 0)
        updateConstraints()
        setNeedsUpdateConstraints()

    }
}

ConversationLabel :

class ConversationLabel : BaseMessageLabel {

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.textColor = .white
        self.font = UIFont(name: "AvenirNext-Medium", size: 14)
        self.lineBreakMode = .byWordWrapping
        self.numberOfLines = 0

        self.preferredMaxLayoutWidth = 200
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

SizeForItem :

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    var height : CGFloat = 80

    let text = messagesDataArray[indexPath.row].messageText

    height = estimateFrameFor(text).height + 20

    return CGSize(width: collectionView.bounds.size.width, height: height)

}

private func estimateFrameFor(_ text : String) -> CGRect {
    let size = CGSize(width: 200, height: 1000)
    return NSString(string: text).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 14)!], context: nil)
}

And the FlowLayout I'm using is this :

Github - jochenschoellig - ChatCollectionViewFlowLayout

Hey, I have created a small project with the problem:
Github - testLP

Body:
Can't comment, not enough rep. But as was commented, please provide your code for the ConversationLabel class, the sizeForItemAtIndexPath override as well as your custom FlowLayout class. When you add custom layout classes, it's easy to overlook certain resulting behaviors.

Without those methods given, you won't have much luck here. When you do, I'll look and update my answer.

However, judging from the video, here's what I'd look at first:

Since cells are re-added to the visible part of the collectionview when their index becomes visible, it is possible that the animation is either due to sizing that you apply inside of sizeForItemAtIndexPath which might be delayed if whatever cell element you use to apply the size is not updated quickly enough. Or that the animation is somehow visible due to lag, since you do call constraint resetters each time the cell views are brought into view ( this could cause some lag depending on the device).
I'm suggesting the latter, because of your apply(_ layoutAttributes: UICollectionViewLayoutAttributes) override. Given the documentation here: you're calling updateConstraints() once, and then using setNeedsUpdateConstraints() right after, which schedules an updateConstraints() call on layout of the cell view when it becomes visible (which is when you're seeing the animation). So you're doing the work twice here, which could add to the animation queue. Or, since you're also resetting the transform attribute, you're might also be scheduling an extra animation that you might not have taken into account.
Finally, While this might hint at where this behavior is stemming from, it's impossible to say without your custom FlowLayout class. As mentioned here:

If you subclass and implement any custom layout attributes, you must
  also override the inherited isEqual: method to compare the values of
  your properties. In iOS 7 and later, the collection view does not
  apply layout attributes if those attributes have not changed. It
  determines whether the attributes have changed by comparing the old
  and new attribute objects using the isEqual: method.

And, as is referred to in this post about iOS7 and later os builds:
 since you override the apply(_ layoutAttributes: UICollectionViewLayoutAttributes) method, you are also supposed to override the isEqual(_ object: Any?) method with your own code which compares layout attributes the way you want.

An example of the isEqual override:

override public func isEqual(_ object: Any?) -> Bool {
        guard let rhs = object as? DateClass else {
            return false
        }
        let lhs = self

        return lhs.date1 == rhs.date1 &&
            lhs.date2 == rhs.date2 &&
            lhs.date3 == rhs.date3
    }

You'd swap out DateClass with your UICollectionViewLayoutAttributes, putting the override inside the scope of your UICollectionViewLayoutAttributes subclass.

So as far what I can tell with what you've given, it seems like there might be accidental over-calling of certain methods in your code. Or perhaps you didn't subclass UICollectionViewLayoutAttributes properly. Again, these are my best solutions for what you provide. Add the missing code, and I will update answer!


来源: stackexchange

问:
cython - how to iterate over c++ list
I want to initiate a cpp list in cython, assign values to it and then iterate over the list to obtain its values. A generic code could look like this:

```<code>from libcpp.list cimport list as cpplist
from cpython cimport array
import array

cdef int[:] c_volumecheck(int n, int comb):

    cdef:
        array.array match = array.array('i', [0]*(n*comb))
        int[:] match_c = match
        cpplist[int] arr

    asign(match_c, comb, n, arr)

    return match_c

cdef void asign(int[:] match, int row, int col, cpplist[int] arr):

    cdef int j, i

    for j in range(row):
        for i in range(col):
            arr.push_back(1)

    for j in range(row):
        for i in range(col):
            match[j*col + i] = arr[j*col +i]
</code>```

However, when I compile this I get the error:

Indexing list[int] not supported for index type int

Given the way they iterate over cpp vectors here I thought that would be the way to go.

答:
C++ std::lists are doubly linked lists (i.e. each element has a pointer to the next and previous one) which makes adding/inserting elements efficient, but means that indexing isn't supported in either Cython or in C++. Instead you should use the iterator protocol:

```<code># at top of file
from cython.operator import dereference, preincrement

# in function
cdef cpplist[int].iterator it

it = arr.begin()

for j in range(row):
    for i in range(col):
        match[j*col + i] = dereference(it)
        preincrement(it)
</code>```

This is (close to) how you'd do the iteration in C++ too.

In the more general case you'd want to compare the iterator against arr.end() to see when you've reached the end of the list. Since you should know the length here I haven't do so.

ContentLicense: CC BY-SA 4.0

Title: cython - how to iterate over c++ list

Body:
I want to initiate a cpp list in cython, assign values to it and then iterate over the list to obtain its values. A generic code could look like this:

from libcpp.list cimport list as cpplist
from cpython cimport array
import array

cdef int[:] c_volumecheck(int n, int comb):

    cdef:
        array.array match = array.array('i', [0]*(n*comb))
        int[:] match_c = match
        cpplist[int] arr

    asign(match_c, comb, n, arr)

    return match_c

cdef void asign(int[:] match, int row, int col, cpplist[int] arr):

    cdef int j, i

    for j in range(row):
        for i in range(col):
            arr.push_back(1)

    for j in range(row):
        for i in range(col):
            match[j*col + i] = arr[j*col +i]

However, when I compile this I get the error:

Indexing list[int] not supported for index type int

Given the way they iterate over cpp vectors here I thought that would be the way to go.

Body:
C++ std::lists are doubly linked lists (i.e. each element has a pointer to the next and previous one) which makes adding/inserting elements efficient, but means that indexing isn't supported in either Cython or in C++. Instead you should use the iterator protocol:

# at top of file
from cython.operator import dereference, preincrement

# in function
cdef cpplist[int].iterator it

it = arr.begin()

for j in range(row):
    for i in range(col):
        match[j*col + i] = dereference(it)
        preincrement(it)

This is (close to) how you'd do the iteration in C++ too.

In the more general case you'd want to compare the iterator against arr.end() to see when you've reached the end of the list. Since you should know the length here I haven't do so.

ContentLicense: CC BY-SA 3.0


问:
Python3 won't recognize a variable in code
All my code is below.

Just started learning to program this week. I'm attempting to make a Monty Hall simulator (text only) where the player chooses a door by selecting 1, 2 or 3. For some reason, though, Python doesn't seem to be recognizing the input!

Here are links to the game for the uninitiated:

Monty Hall wikipedia page

Monty Hall simulation

What my program attempts to do is as follows. First the player chooses a door, either 1, 2 or 3. Then the program checks to make sure that the player did indeed enter one of those three numbers. If not, then the person needs to choose again.

After this, the game randomly chooses a winning door. Then, per the rules of the game, the program needs to reveal a dummy prize (the goat). So the program randomly chooses one of the doors to be the "goat door." The program first makes sure that this door is not the winning door nor is it the chosen door.

Here's the error I get when running my code:

```<code>line 52, in <module>

     doors()

line 14, in doors

     while goatDoor == chosenDoor or goatDoor == winningDoor:

NameError: name 'chosenDoor' is not defined
</code>```

My issue is that I can't tell why it keeps saying that chosenDoor is not defined!

Here's the code:

```<code>import random

def chooseDoor():   # choose a door
    chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

def doors():    # the winning door and the dummy door are randomly selected
    winningDoor = random.randint(1,3)
    goatDoor = ''
    while goatDoor == chosenDoor or goatDoor == winningDoor:
        goatDoor = random.randint(1, 3)

def keepOrSwitch():
    switchDoor = 1
    if switchDoor == chosenDoor or switchDoor == winningDoor:
        switchDoor = 2
        if switchDoor == chosenDoor or switchDoor == winningDoor:
            switchDoor = 3
    print('Do you want to')
    print('KEEP your choice of door number ' + str(chosenDoor) + '?')
    print('...or...')
    print('Do you want to')
    print('SWITCH and choose door number ' + str(switchDoor) + '?')
    print()
    choice = ''
    while True:
        print('Type \'K\' for keep or type \'S\' for switch.')
        choice = input()
        if choice == 'K' or choice == 'k':
            break
        if choice == 'S' or choice == 's':
            chosenDoor = switchDoor
            break

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':

    chooseDoor()

    doors()

    keepOrSwitch()

    checkWin()

    print('Do you want to play again? (yes or no)')
    playAgain = input()
</code>```

答: In a python program you've only defined chosenDoor in the chooseDoor() function and you haven't passed chosenDoor into the next function doors().  You can pass chosenDoor to doors() by doing doors(chosenDoor).</p>

Body:
All my code is below.

Just started learning to program this week. I'm attempting to make a Monty Hall simulator (text only) where the player chooses a door by selecting 1, 2 or 3. For some reason, though, Python doesn't seem to be recognizing the input!

Here are links to the game for the uninitiated:

Monty Hall wikipedia page

Monty Hall simulation

What my program attempts to do is as follows. First the player chooses a door, either 1, 2 or 3. Then the program checks to make sure that the player did indeed enter one of those three numbers. If not, then the person needs to choose again.

After this, the game randomly chooses a winning door. Then, per the rules of the game, the program needs to reveal a dummy prize (the goat). So the program randomly chooses one of the doors to be the "goat door." The program first makes sure that this door is not the winning door nor is it the chosen door.

Here's the error I get when running my code:

line 52, in <module>

     doors()

line 14, in doors

     while goatDoor == chosenDoor or goatDoor == winningDoor:

NameError: name 'chosenDoor' is not defined

My issue is that I can't tell why it keeps saying that chosenDoor is not defined!

Here's the code:

import random

def chooseDoor():   # choose a door
    chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

def doors():    # the winning door and the dummy door are randomly selected
    winningDoor = random.randint(1,3)
    goatDoor = ''
    while goatDoor == chosenDoor or goatDoor == winningDoor:
        goatDoor = random.randint(1, 3)

def keepOrSwitch():
    switchDoor = 1
    if switchDoor == chosenDoor or switchDoor == winningDoor:
        switchDoor = 2
        if switchDoor == chosenDoor or switchDoor == winningDoor:
            switchDoor = 3
    print('Do you want to')
    print('KEEP your choice of door number ' + str(chosenDoor) + '?')
    print('...or...')
    print('Do you want to')
    print('SWITCH and choose door number ' + str(switchDoor) + '?')
    print()
    choice = ''
    while True:
        print('Type \'K\' for keep or type \'S\' for switch.')
        choice = input()
        if choice == 'K' or choice == 'k':
            break
        if choice == 'S' or choice == 's':
            chosenDoor = switchDoor
            break

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':

    chooseDoor()

    doors()

    keepOrSwitch()

    checkWin()

    print('Do you want to play again? (yes or no)')
    playAgain = input()


问:
why cant i replace __add__ with __radd__?
I am (for exercise) trying to make a class that works with roman numerals. I am trying to put as much functionality into it as possible, so i looked into making operators work on them. I found (example, the problem persists among other pairs of methods) __add__ and __radd__. The documentation says that if __add__ is not defined it (or if it fails) looks into __radd__, but when i try to delete __add__ and edit the __radd__ method it works on 0 + myobject, but not on object1 + object2.

Here is the class (with a few things cut out because they're not important for my problem):

```<code>class Roman:
    num_map = [('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)]

    def __init__(self, num=None):
        self.decimal = 0
        self.roman = 'N'
        if type(num) == type(0):
            self.__setattr__('decimal', num)
        elif type(num) == type(''):
            self.__setattr__('roman', num)

    def __setattr__(self, field, value):
        if field == 'decimal' and type(value) == type(0):
            super().__setattr__('decimal', value)
            super().__setattr__('roman', self.dec2roman(value))
        elif field == 'roman' and type(value) == type(''):
            super().__setattr__('roman', value)
            super().__setattr__('decimal', self.roman2dec(value))
</code>```

The methods self.dec2roman(integer) and self.roman2dec(string) simply convert from one format to the other.

Now if i try to make __radd__ like this:

```<code>def __radd__(self, other):
    if other == 0:
        return self
    return Roman(self.decimal + other.decimal)
</code>```

it doesn't work, but this does:

```<code>def __add__(self,other):
    return Roman(self.decimal + other.decimal)
def __radd__(self, other):
    if other == 0:
        return self
    return self + other
</code>```

Here's the error i get:

```<code>>>> from roman import Roman
>>> a = Roman(3)
>>> b = Roman('X')
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Roman' and 'Roman'
</code>```

Does someone know what is going on?

答:
The __radd__() method is called only if your object is the right hand operand. You can see this by simply printing the __doc__ of this item for integers:

```<code>In [4]: (1).__radd__.__doc__
Out[4]: 'Return value+self.'
</code>```

And You can check this behavior using an example:

```<code>In [7]: class A:
   ...:     def __radd__(self, other):
   ...:         return 10
   ...:

In [8]: a = A()

In [9]: a + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-429dec850246> in <module>()
----> 1 a + 2

TypeError: unsupported operand type(s) for +: 'A' and 'int'

In [10]: 2 + a
Out[10]: 10
</code>```

But when you are using two of these objects python calls the first objects __add__ method and that's why it raises the exception. If you want to get ride of that you can simply handle the problem inside the __add__ method instead of writing a logical code for it.

For example you can use the other as the right hand operand in order to use the __radd__ inside the __add__:

```<code>In [24]: class A:
             def __radd__(self, other):
                 return 10
             def __add__(self, other):
                 return 5 + other
   ....:

In [25]: a = A()

In [26]: a + 2
Out[26]: 7

In [27]: 2 + a
Out[27]: 10

In [28]: a + a
Out[28]: 10
</code>```

Body:
I am (for exercise) trying to make a class that works with roman numerals. I am trying to put as much functionality into it as possible, so i looked into making operators work on them. I found (example, the problem persists among other pairs of methods) __add__ and __radd__. The documentation says that if __add__ is not defined it (or if it fails) looks into __radd__, but when i try to delete __add__ and edit the __radd__ method it works on 0 + myobject, but not on object1 + object2.

Here is the class (with a few things cut out because they're not important for my problem):

class Roman:
    num_map = [('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)]

    def __init__(self, num=None):
        self.decimal = 0
        self.roman = 'N'
        if type(num) == type(0):
            self.__setattr__('decimal', num)
        elif type(num) == type(''):
            self.__setattr__('roman', num)

    def __setattr__(self, field, value):
        if field == 'decimal' and type(value) == type(0):
            super().__setattr__('decimal', value)
            super().__setattr__('roman', self.dec2roman(value))
        elif field == 'roman' and type(value) == type(''):
            super().__setattr__('roman', value)
            super().__setattr__('decimal', self.roman2dec(value))

The methods self.dec2roman(integer) and self.roman2dec(string) simply convert from one format to the other.

Now if i try to make __radd__ like this:

def __radd__(self, other):
    if other == 0:
        return self
    return Roman(self.decimal + other.decimal)

it doesn't work, but this does:

def __add__(self,other):
    return Roman(self.decimal + other.decimal)
def __radd__(self, other):
    if other == 0:
        return self
    return self + other

Here's the error i get:

>>> from roman import Roman
>>> a = Roman(3)
>>> b = Roman('X')
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Roman' and 'Roman'

Does someone know what is going on?

Body:
The __radd__() method is called only if your object is the right hand operand. You can see this by simply printing the __doc__ of this item for integers:

In [4]: (1).__radd__.__doc__
Out[4]: 'Return value+self.'

And You can check this behavior using an example:

In [7]: class A:
   ...:     def __radd__(self, other):
   ...:         return 10
   ...:

In [8]: a = A()

In [9]: a + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-429dec850246> in <module>()
----> 1 a + 2

TypeError: unsupported operand type(s) for +: 'A' and 'int'

In [10]: 2 + a
Out[10]: 10

But when you are using two of these objects python calls the first objects __add__ method and that's why it raises the exception. If you want to get ride of that you can simply handle the problem inside the __add__ method instead of writing a logical code for it.

For example you can use the other as the right hand operand in order to use the __radd__ inside the __add__:

In [24]: class A:
             def __radd__(self, other):
                 return 10
             def __add__(self, other):
                 return 5 + other
   ....:

In [25]: a = A()

In [26]: a + 2
Out[26]: 7

In [27]: 2 + a
Out[27]: 10

In [28]: a + a
Out[28]: 10


问:
Using lodash and trying to update and Object with multiple objects. (editing items)
I am using lodash and redux/react to make a simple app. Right now I have it returning an object with multiple objects in it. So it looks something like this when I get the final object.

Object { 2: Object, 34: Object}

Each Object has a title , id, and description. I used lodash to mapKeys and make each object within the single object to be keyed with the ID. This way it is easier to find each object. For example Mainobject[34] will return that object even though it is second in the Object.

So this is all working well now and I want to be able to update the object or edit some code and replace one of the excising objects. I am using redux/react so understanding of that will be required to understand what I am trying to do.

As you can see I am trying to use the _.get to find the item out of the mainObject and then update that particular item with the _.merge, I then am trying to use _.update, but in my console.log of my current state I am getting this in the console:

current state is: -> Object {2: Object, 34: Object}

current state is: -> Object {2: Object, 34: Object, object Object: undefined}

The second console has the object with the id of 34 and everything is updated and working correctly, but I am getting the undefind object Object at the end.

Here is my reducer:

```<code>const reducer = function(state={}, action) {
  switch(action.type) {
    case "POST_BOOK":
      return _.mapKeys(action.payload, 'id');
    break;
    case "DELETE_BOOK":
      return _.omit(state, action.payload);
    break;
    case "UPDATE_BOOK":
      let foundItem = _.get(state, action.payload.id);
      let updateItem = _.merge(state[action.payload.id],foundItem,action.payload);
      console.log(updateItem);
      return _.update(state, state[action.payload.id], updateItem);
    break;
  }
  return state
}
</code>```

Here are my actions:

```<code>store.dispatch({
  type: "POST_BOOK",
  payload: [
  {
    id: 34,
    title: 'this is the book title',
    description: 'this is the book description',
    price: 3
  },
  {
    id: 2,
    title: 'this is the book title 2',
    description: 'this is the book description 2',
    price: 3.2
  }
]
});

// store.dispatch({
//   type: "DELETE_BOOK",
//   payload: 2
// });

store.dispatch({
  type: "UPDATE_BOOK",
  payload: {
    id: 34,
    title: 'this is book edit title',
    description: 'this is book edit edit',
    price: 2341.23
  }
})
</code>```

答:
Well, you are very close to the solution here. The only thing wrong with your code is that _.update needs a function as third parameter while you are giving it an object.

Actually you can achieve what you want only with the _.merge method which recursively merges two objects.

So you just need to create an object that has the key of the item you want to update, and merge it with the previous state.

It'd look like this:

```<code>case "UPDATE_BOOK":
  let updates = {[action.payload.id]: action.payload};
  return _.merge(state, updates)
</code>```

And this should do the trick (I have to admit I haven't tested the code)

Body:
I am using lodash and redux/react to make a simple app. Right now I have it returning an object with multiple objects in it. So it looks something like this when I get the final object.

Object { 2: Object, 34: Object}

Each Object has a title , id, and description. I used lodash to mapKeys and make each object within the single object to be keyed with the ID. This way it is easier to find each object. For example Mainobject[34] will return that object even though it is second in the Object.

So this is all working well now and I want to be able to update the object or edit some code and replace one of the excising objects. I am using redux/react so understanding of that will be required to understand what I am trying to do.

As you can see I am trying to use the _.get to find the item out of the mainObject and then update that particular item with the _.merge, I then am trying to use _.update, but in my console.log of my current state I am getting this in the console:

current state is: -> Object {2: Object, 34: Object}

current state is: -> Object {2: Object, 34: Object, object Object: undefined}

The second console has the object with the id of 34 and everything is updated and working correctly, but I am getting the undefind object Object at the end.

Here is my reducer:

const reducer = function(state={}, action) {
  switch(action.type) {
    case "POST_BOOK":
      return _.mapKeys(action.payload, 'id');
    break;
    case "DELETE_BOOK":
      return _.omit(state, action.payload);
    break;
    case "UPDATE_BOOK":
      let foundItem = _.get(state, action.payload.id);
      let updateItem = _.merge(state[action.payload.id],foundItem,action.payload);
      console.log(updateItem);
      return _.update(state, state[action.payload.id], updateItem);
    break;
  }
  return state
}

Here are my actions:

store.dispatch({
  type: "POST_BOOK",
  payload: [
  {
    id: 34,
    title: 'this is the book title',
    description: 'this is the book description',
    price: 3
  },
  {
    id: 2,
    title: 'this is the book title 2',
    description: 'this is the book description 2',
    price: 3.2
  }
]
});

// store.dispatch({
//   type: "DELETE_BOOK",
//   payload: 2
// });

store.dispatch({
  type: "UPDATE_BOOK",
  payload: {
    id: 34,
    title: 'this is book edit title',
    description: 'this is book edit edit',
    price: 2341.23
  }
})

Body:
Well, you are very close to the solution here. The only thing wrong with your code is that _.update needs a function as third parameter while you are giving it an object.

Actually you can achieve what you want only with the _.merge method which recursively merges two objects.

So you just need to create an object that has the key of the item you want to update, and merge it with the previous state.

It'd look like this:

case "UPDATE_BOOK":
  let updates = {[action.payload.id]: action.payload};
  return _.merge(state, updates)

And this should do the trick (I have to admit I haven't tested the code)


问:
Reading requests body Nodejs
I'm running this simple http node.js server:

```<code>var http = require('http');

http.createServer(function (req, res) {

}).listen(6000);
</code>```

Can you explain me, how I can read the body of the incoming requests, in orderd to visualize it on the console?

答:
You could pipe the request stream to stdout:

```<code>var http = require('http');

http.createServer(function (req, res) {
  req.pipe(process.stdout);
}).listen(6000);
</code>```

Update: If the body contains JSON and you want to deserialize it then you could build up a string from the stream data chunks and use JSON.parse() on that (remembering to put it in a try/catch block or using tryjson) or you could use a tested solution for that - because if you want to parse the JSON body then I suspect that you may need to do more with that.

Example with Express and body-parser:

```<code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use((req, res) => {
  // req.body is deserialized body:
  console.log(req.body);
});
app.listen(6000);
</code>```

or with an older syntax:

```<code>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(function (req, res) {
  // req.body is deserialized body:
  console.log(req.body);
});
app.listen(6000);
</code>```

You can test it with curl like this:

```<code>curl -X POST -H 'Content-type: application/json' -d '{"a":1,"b":2}' localhost:6000
</code>```

It prints:

```<code>{ a: 1, b: 2 }
</code>```

and you can see it's parsed by the lack of quotes around the object keys.

Of course you can use things like req.body.someArray[3] etc. - it's fully parsed and usable.

Title: Reading requests body Nodejs

Body:
I'm running this simple http node.js server:

var http = require('http');

http.createServer(function (req, res) {

}).listen(6000);

Can you explain me, how I can read the body of the incoming requests, in orderd to visualize it on the console?

Body:
You could pipe the request stream to stdout:

var http = require('http');

http.createServer(function (req, res) {
  req.pipe(process.stdout);
}).listen(6000);

Update: If the body contains JSON and you want to deserialize it then you could build up a string from the stream data chunks and use JSON.parse() on that (remembering to put it in a try/catch block or using tryjson) or you could use a tested solution for that - because if you want to parse the JSON body then I suspect that you may need to do more with that.

Example with Express and body-parser:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use((req, res) => {
  // req.body is deserialized body:
  console.log(req.body);
});
app.listen(6000);

or with an older syntax:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(function (req, res) {
  // req.body is deserialized body:
  console.log(req.body);
});
app.listen(6000);

You can test it with curl like this:

curl -X POST -H 'Content-type: application/json' -d '{"a":1,"b":2}' localhost:6000

It prints:

{ a: 1, b: 2 }

and you can see it's parsed by the lack of quotes around the object keys.

Of course you can use things like req.body.someArray[3] etc. - it's fully parsed and usable.


问:
Laravel Mix Bootstrap Glyphicons not loading
I created a new laravel application and added the auth template.

I tried to add this button:

```<code><button type="button" class="btn btn-default btn-lg">
    <span class="glyphicon glyphicon-stop" aria-hidden="true"></span>
</button>
</code>```

But the glyphicons are not loading I get this error in my Chrome console:

```<code>GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff2?448c34a56d699c29117adc64c43affeb
GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff?fa2772327f55d8198301fdb8bcfc8158
GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.ttf?e18bbf611f2a2e43afc071aa2f4e1512
</code>```

npm watch is already running.

What else could cause this error?

答:
Run command npm run dev or npm run production in production

https://laravel.com/docs/5.4/mix#running-mix

Body:
I created a new laravel application and added the auth template.

I tried to add this button:

<button type="button" class="btn btn-default btn-lg">

</button>

But the glyphicons are not loading I get this error in my Chrome console:

GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff2?448c34a56d699c29117adc64c43affeb
GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff?fa2772327f55d8198301fdb8bcfc8158
GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.ttf?e18bbf611f2a2e43afc071aa2f4e1512

npm watch is already running.

What else could cause this error?


问:
Excel Time to SQL Time
I am having some trouble inserting time into SQLServer

The data type in SQLServer is time(0). I have the time in excel as 10:29:42. (It is in 24-hour format)When I insert it into SQL the actual value being inserted is 0.4372917

I get an error and the insert fails.Is there any way in VBA to have the actual value as `10:29:42'? This is my current code I use to copy from one sheet to another:

```<code>Test Time
Dim tt As String
tt = raw.Range("A7")
master.Range("F2") = tt
</code>```

My insert Code is such:

```<code>Insert into Date_t( Date) Values(ActiveSheet.Range("F2"))
</code>```

答:
Excel stores all dates internally as numbers.  What you're getting is that numeric representation.

If you want to use it in something like SQL, you will need to format it as a string.

```<code>Format(raw.Range("A7"), "HH:MM:SS")
</code>```

will give you a result of "10:29:42"

use this in your SQL statement.

```<code>Insert into Date_t( Date) Values(Format(raw.Range("A7"), "HH:MM:SS"))
</code>```

Some formatting of the string for single ticks around the date are probably necessary.  I'm not sure what kind of connection you're using though, so I can't give you that advise.

Title: Excel Time to SQL Time

Body:
I am having some trouble inserting time into SQLServer

The data type in SQLServer is time(0). I have the time in excel as 10:29:42. (It is in 24-hour format)When I insert it into SQL the actual value being inserted is 0.4372917

I get an error and the insert fails.Is there any way in VBA to have the actual value as `10:29:42'? This is my current code I use to copy from one sheet to another:

Test Time
Dim tt As String
tt = raw.Range("A7")
master.Range("F2") = tt

My insert Code is such:

Insert into Date_t( Date) Values(ActiveSheet.Range("F2"))

Body:
Excel stores all dates internally as numbers.  What you're getting is that numeric representation.

If you want to use it in something like SQL, you will need to format it as a string.

Format(raw.Range("A7"), "HH:MM:SS")

will give you a result of "10:29:42"

use this in your SQL statement.

Insert into Date_t( Date) Values(Format(raw.Range("A7"), "HH:MM:SS"))

Some formatting of the string for single ticks around the date are probably necessary.  I'm not sure what kind of connection you're using though, so I can't give you that advise.


问:
Grouping operation on a field and putting the list of the liked field in an array
I am working on a JHipster project with an AngularJS front-end and a Java back-end. I am using Spring data with the MongoDb database.

I did a grouping operation on the field budgetCode. So, for each budgetCode, I succeded to have the list of all the linked taskCodes.

Here, the method aggregateAllTaskCodes which does the grouping operation:

Repository layer

```<code>public class ClarityResourceAffectationRepositoryImpl implements ClarityResourceAffectationRepositoryCustom {
    @Override
        public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {

            Aggregation aggregation = newAggregation(
                    group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
                    sort(Sort.Direction.ASC, previousOperation(),"budgetCode"));

            AggregationResults groupResults = mongoTemplate.aggregate(aggregation, ClarityResourceAffectation.class,
                    ClarityResourceAffectationReport.class);
            List<ClarityResourceAffectationReport> clarityResourceAffectationReports = groupResults.getMappedResults();

            return clarityResourceAffectationReports;
        }
    }
</code>```

Service layer

```<code>public class ClarityResourceAffectationServiceImpl implements ClarityResourceAffectationService{
    @Override
    public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {
        log.debug("Request to aggregateByCodeBudgetForCodeTache : {}");
        List<ClarityResourceAffectationReport> result = clarityResourceAffectationRepository
                .aggregateAllTaskCodes();

        return result;
    }
}
</code>```

REST API layer

```<code>public class ClarityResourceAffectationResource {
    @GetMapping("/clarity-resource-affectations/list-task-codes")
    @Timed
    public ResponseEntity<List<ClarityResourceAffectationReport>> aggregateTabAllTaskCodes() {
        log.debug("REST request to get aggregateTabAllTaskCodes : {}");
        List<ClarityResourceAffectationReport> result = clarityResourceAffectationService.aggregateAllTaskCodes();
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
</code>```

ClarityResourceAffectation

```<code>@Document(collection = "clarity_resource_affectation")
public class ClarityResourceAffectation implements Serializable {

    @Id
    private String id;

    @Field("budget_code")
    private String budgetCode;

    @Field("task_code")
    private String taskCode;

    public String getBudgetCode() {
        return budgetCode;
    }

    public void setBudgetCode(String budgetCode) {
        this.budgetCode = budgetCode;
    }

    public String getTaskCode() {
        return taskCode;
    }

    public void setTaskCode(String taskCode) {
        this.taskCode = taskCode;
    }
}
</code>```

ClarityResourceAffectationReport

```<code>public class ClarityResourceAffectationReport implements Serializable {

    private static final long serialVersionUID = 1L;

    private String budgetCode;
    private String taskCode;
    private String listTaskCode;

    public String getBudgetCode() {
        return budgetCode;
    }

    public void setBudgetCode(String budgetCode) {
        this.budgetCode = budgetCode;
    }

    public String getTaskCode() {
        return taskCode;
    }

    public void setTaskCode(String taskCode) {
        this.taskCode = taskCode;
    }
    public String[] getListTaskCode() {
        return listTaskCode;
    }

    public void setListTaskCode(String[] listTaskCode) {
        this.listTaskCode = listTaskCode;
    }
}
</code>```

clarity-resource-affectation.service.js

```<code>(function() {
    'use strict';
    angular
        .module('dashboardApp')
        .factory('ClarityResourceAffectation', ClarityResourceAffectation);

    ClarityResourceAffectation.$inject = ['$resource'];

    function ClarityResourceAffectation ($resource) {
        var resourceUrl =  'clarity/' + 'api/clarity-resource-affectations/:id';

        return $resource(resourceUrl, {}, {
            'query': { method: 'GET', isArray: true},
            'aggregateAllTaskCodes': {
                method: 'GET',
                isArray: true,
                url: 'clarity/api/clarity-resource-affectations/list-task-codes'
            }
        });
    }
})();
</code>```

When I call the function in the AngularJS front-end and I display that on a table, for each budgetCode, I have the list of the taskCodes in an array of one element. For example, for the budgetCode [ "P231P00"] I can have this list of taskCodes: [ "61985" , "43606" , "60671" , "43602"]

Well, I would like to have the list of the linked taskCodes, not in an array of one element but in an array of several elements like that:
[ ["61985"] , ["43606"] , ["60671"] , ["43602"] ]

What do I have to change in my code in order to do that?

Just for information, my javascript code which create the array based on the aggregate function:

clarity-resource-affectation-list-task-codes.controller.js

```<code>(function() {
    'use strict';

    angular
        .module('dashboardApp')
        .controller('ClarityResourceAffectationTableauBordNbCollaborateursController', ClarityResourceAffectationTableauBordNbCollaborateursController);

    ClarityResourceAffectationTableauBordNbCollaborateursController.$inject = ['$timeout', '$scope', '$stateParams', 'DataUtils', 'ClarityResourceAffectation'];

    function ClarityResourceAffectationTableauBordNbCollaborateursController ($timeout, $scope, $stateParams, DataUtils, ClarityResourceAffectation) {
        var vm = this;

        //Call of the function
        allTaskCodes()

        function allTaskCodes()
        {
            ClarityResourceAffectation.aggregateAllTaskCodes(function(readings) {

                var dataAllTaskCodes;
                dataAllTaskCodes = [];

                alert(readings);

                readings.forEach(function (item) {
                    dataAllTaskCodes.push({
                        label: item.budgetCode,
                        value: item.taskCode,
                        listvalue: item.listTaskCode
                    });
                });

                vm.dataAllTaskCodes = dataAllTaskCodes;
            });
        }
    }
})();
</code>```

Temporary solution:
Actually, I found a temporary solution by completing the method I created in the Service Layer:

```<code>@Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {
    log.debug("Request to aggregateAllTaskCodes : {}");
    List<ClarityResourceAffectationReport> result = clarityResourceAffectationRepository
            .aggregateAllTaskCodes();

    Iterator<ClarityResourceAffectationReport> iterator = result.iterator();
    while (iterator.hasNext())
    {
        ClarityResourceAffectationReport resAffectationReport = iterator.next();

        String taskCodes = resAffectationReport.getTaskCode();

        //Delete all exept letters, numbers and comma
        taskCodes = taskCodes.replaceAll("[^a-zA-Z0-9,]","");

        String[] listTaskCodes = taskCodes.split(",");

        resAffectationReport.setListTaskCodes(listTaskCodes);
    }

    return result;
}
</code>```

Also, I added an additional field to ClarityResourceAffectationReport which is listTaskCode. I updated the report class above. Finally, when I do an alert:
alert(readings[1].listvalue[0]), I have a result like 2630. So, I succeeded to have the first taskCode of a particular budgetCode.

I understood that what is important here is not the fact that as I told above for a budgetCode like [ "P231P00"], I must have a list like: [ "61985" , "43606" , "60671" , "43602"] or [ ["61985"] , ["43606"] , ["60671"] , ["43602"] ]. I just must have an array, not a string.

When I display alert(readings[1].listvalue), I have["2630","61297","61296","61299"] which is clearly an array because I can access each of the elements by calling alert(readings[1].listvalue[0]), alert(readings[1].listvalue[1]], etc...

I tried what you advised me

But, it is still not working. Here, my repository code:

```<code>@Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCode() {

    AggregationOperation project = new AggregationOperation() {
        @Override
        public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
            return new BasicDBObject("$project", new BasicDBObject("budgetCode", "$budget_code").append("taskCode", Arrays.asList("$task_code")));
        }
    };

    Aggregation aggregation = newAggregation(project,
            group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
            sort(Sort.Direction.ASC, previousOperation(),"budgetCode"));

    AggregationResults groupResults = mongoTemplate.aggregate(aggregation, ClarityResourceAffectation.class,
            ClarityResourceAffectationReport.class);
    List<ClarityResourceAffectationReport> clarityResourceAffectationReports = groupResults.getMappedResults();

    log.debug("clarityResourceAffectationReports.size() => " + clarityResourceAffectationReports.size());
    log.debug("aggregation.toString() => " + aggregation.toString());

    return clarityResourceAffectationReports;
}
</code>```

Here, you can find the logs:

```<code>clarityResourceAffectationReports.size() => 1
aggregation.toString() => {"aggregate" : "__collection__" , "pipeline" : [ { "$project" : { "budgetCode" : "$budget_code" , "taskCode" : [ "$task_code"]}} , { "$group" : { "_id" : "$budgetCode" , "budgetCode" : { "$addToSet" : "$budgetCode"} , "taskCode" : { "$addToSet" : "$taskCode"}}} , { "$sort" : { "_id" : 1 , "budgetCode" : 1}}]}
</code>```

Thanks in advance

答:
You need to use $project to change the taskCodes value into array of single value before $group.

I don't see any hook in the api to address this.

You can use AggregationOperation to create $project stage using mongodb (BasicDBObject)  types.

```<code>AggregationOperation project = new AggregationOperation() {
       @Override
       public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
          return new BasicDBObject("$project", new BasicDBObject("budgetCode", 1).append("taskCode", Arrays.asList("$taskCode")));
    }
};
</code>```

Something like

```<code>Aggregation aggregation = newAggregation(project,
                    group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
                    sort(Sort.Direction.ASC, previousOperation(), "budgetCode"));
</code>```

Using lambda

```<code> Aggregation aggregation = newAggregation(
                aggregationOperationContext -> new BasicDBObject("$project", new BasicDBObject("budgetCode", 1).append("taskCode", Arrays.asList("$taskCode"))),
                group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
                sort(Sort.Direction.ASC, previousOperation(), "budgetCode"));
</code>```

Body:
I am working on a JHipster project with an AngularJS front-end and a Java back-end. I am using Spring data with the MongoDb database.

I did a grouping operation on the field budgetCode. So, for each budgetCode, I succeded to have the list of all the linked taskCodes.

Here, the method aggregateAllTaskCodes which does the grouping operation:

Repository layer

public class ClarityResourceAffectationRepositoryImpl implements ClarityResourceAffectationRepositoryCustom {
    @Override
        public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {

            Aggregation aggregation = newAggregation(
                    group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
                    sort(Sort.Direction.ASC, previousOperation(),"budgetCode"));

            AggregationResults groupResults = mongoTemplate.aggregate(aggregation, ClarityResourceAffectation.class,
                    ClarityResourceAffectationReport.class);
            List<ClarityResourceAffectationReport> clarityResourceAffectationReports = groupResults.getMappedResults();

            return clarityResourceAffectationReports;
        }
    }

Service layer

public class ClarityResourceAffectationServiceImpl implements ClarityResourceAffectationService{
    @Override
    public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {
        log.debug("Request to aggregateByCodeBudgetForCodeTache : {}");
        List<ClarityResourceAffectationReport> result = clarityResourceAffectationRepository
                .aggregateAllTaskCodes();

        return result;
    }
}

REST API layer

public class ClarityResourceAffectationResource {
    @GetMapping("/clarity-resource-affectations/list-task-codes")
    @Timed
    public ResponseEntity<List<ClarityResourceAffectationReport>> aggregateTabAllTaskCodes() {
        log.debug("REST request to get aggregateTabAllTaskCodes : {}");
        List<ClarityResourceAffectationReport> result = clarityResourceAffectationService.aggregateAllTaskCodes();
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}

ClarityResourceAffectation

@Document(collection = "clarity_resource_affectation")
public class ClarityResourceAffectation implements Serializable {

    @Id
    private String id;

    @Field("budget_code")
    private String budgetCode;

    @Field("task_code")
    private String taskCode;

    public String getBudgetCode() {
        return budgetCode;
    }

    public void setBudgetCode(String budgetCode) {
        this.budgetCode = budgetCode;
    }

    public String getTaskCode() {
        return taskCode;
    }

    public void setTaskCode(String taskCode) {
        this.taskCode = taskCode;
    }
}

ClarityResourceAffectationReport

public class ClarityResourceAffectationReport implements Serializable {

    private static final long serialVersionUID = 1L;

    private String budgetCode;
    private String taskCode;
    private String listTaskCode;

    public String getBudgetCode() {
        return budgetCode;
    }

    public void setBudgetCode(String budgetCode) {
        this.budgetCode = budgetCode;
    }

    public String getTaskCode() {
        return taskCode;
    }

    public void setTaskCode(String taskCode) {
        this.taskCode = taskCode;
    }
    public String[] getListTaskCode() {
        return listTaskCode;
    }

    public void setListTaskCode(String[] listTaskCode) {
        this.listTaskCode = listTaskCode;
    }
}

clarity-resource-affectation.service.js

(function() {
    'use strict';
    angular
        .module('dashboardApp')
        .factory('ClarityResourceAffectation', ClarityResourceAffectation);

    ClarityResourceAffectation.$inject = ['$resource'];

    function ClarityResourceAffectation ($resource) {
        var resourceUrl =  'clarity/' + 'api/clarity-resource-affectations/:id';

        return $resource(resourceUrl, {}, {
            'query': { method: 'GET', isArray: true},
            'aggregateAllTaskCodes': {
                method: 'GET',
                isArray: true,
                url: 'clarity/api/clarity-resource-affectations/list-task-codes'
            }
        });
    }
})();

When I call the function in the AngularJS front-end and I display that on a table, for each budgetCode, I have the list of the taskCodes in an array of one element. For example, for the budgetCode [ "P231P00"] I can have this list of taskCodes: [ "61985" , "43606" , "60671" , "43602"]

Well, I would like to have the list of the linked taskCodes, not in an array of one element but in an array of several elements like that:
[ ["61985"] , ["43606"] , ["60671"] , ["43602"] ]

What do I have to change in my code in order to do that?

Just for information, my javascript code which create the array based on the aggregate function:

clarity-resource-affectation-list-task-codes.controller.js

(function() {
    'use strict';

    angular
        .module('dashboardApp')
        .controller('ClarityResourceAffectationTableauBordNbCollaborateursController', ClarityResourceAffectationTableauBordNbCollaborateursController);

    ClarityResourceAffectationTableauBordNbCollaborateursController.$inject = ['$timeout', '$scope', '$stateParams', 'DataUtils', 'ClarityResourceAffectation'];

    function ClarityResourceAffectationTableauBordNbCollaborateursController ($timeout, $scope, $stateParams, DataUtils, ClarityResourceAffectation) {
        var vm = this;

        //Call of the function
        allTaskCodes()

        function allTaskCodes()
        {
            ClarityResourceAffectation.aggregateAllTaskCodes(function(readings) {

                var dataAllTaskCodes;
                dataAllTaskCodes = [];

                alert(readings);

                readings.forEach(function (item) {
                    dataAllTaskCodes.push({
                        label: item.budgetCode,
                        value: item.taskCode,
                        listvalue: item.listTaskCode
                    });
                });

                vm.dataAllTaskCodes = dataAllTaskCodes;
            });
        }
    }
})();

Temporary solution:
Actually, I found a temporary solution by completing the method I created in the Service Layer:

@Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {
    log.debug("Request to aggregateAllTaskCodes : {}");
    List<ClarityResourceAffectationReport> result = clarityResourceAffectationRepository
            .aggregateAllTaskCodes();

    Iterator<ClarityResourceAffectationReport> iterator = result.iterator();
    while (iterator.hasNext())
    {
        ClarityResourceAffectationReport resAffectationReport = iterator.next();

        String taskCodes = resAffectationReport.getTaskCode();

        //Delete all exept letters, numbers and comma
        taskCodes = taskCodes.replaceAll("[^a-zA-Z0-9,]","");

        String[] listTaskCodes = taskCodes.split(",");

        resAffectationReport.setListTaskCodes(listTaskCodes);
    }

    return result;
}

Also, I added an additional field to ClarityResourceAffectationReport which is listTaskCode. I updated the report class above. Finally, when I do an alert:
alert(readings[1].listvalue[0]), I have a result like 2630. So, I succeeded to have the first taskCode of a particular budgetCode.

I understood that what is important here is not the fact that as I told above for a budgetCode like [ "P231P00"], I must have a list like: [ "61985" , "43606" , "60671" , "43602"] or [ ["61985"] , ["43606"] , ["60671"] , ["43602"] ]. I just must have an array, not a string.

When I display alert(readings[1].listvalue), I have["2630","61297","61296","61299"] which is clearly an array because I can access each of the elements by calling alert(readings[1].listvalue[0]), alert(readings[1].listvalue[1]], etc...

I tried what you advised me

But, it is still not working. Here, my repository code:

@Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCode() {

    AggregationOperation project = new AggregationOperation() {
        @Override
        public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
            return new BasicDBObject("$project", new BasicDBObject("budgetCode", "$budget_code").append("taskCode", Arrays.asList("$task_code")));
        }
    };

    Aggregation aggregation = newAggregation(project,
            group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
            sort(Sort.Direction.ASC, previousOperation(),"budgetCode"));

    AggregationResults groupResults = mongoTemplate.aggregate(aggregation, ClarityResourceAffectation.class,
            ClarityResourceAffectationReport.class);
    List<ClarityResourceAffectationReport> clarityResourceAffectationReports = groupResults.getMappedResults();

    log.debug("clarityResourceAffectationReports.size() => " + clarityResourceAffectationReports.size());
    log.debug("aggregation.toString() => " + aggregation.toString());

    return clarityResourceAffectationReports;
}

Here, you can find the logs:

clarityResourceAffectationReports.size() => 1
aggregation.toString() => {"aggregate" : "__collection__" , "pipeline" : [ { "$project" : { "budgetCode" : "$budget_code" , "taskCode" : [ "$task_code"]}} , { "$group" : { "_id" : "$budgetCode" , "budgetCode" : { "$addToSet" : "$budgetCode"} , "taskCode" : { "$addToSet" : "$taskCode"}}} , { "$sort" : { "_id" : 1 , "budgetCode" : 1}}]}

Thanks in advance

Body:
You need to use $project to change the taskCodes value into array of single value before $group.

I don't see any hook in the api to address this.

You can use AggregationOperation to create $project stage using mongodb (BasicDBObject)  types.

AggregationOperation project = new AggregationOperation() {
       @Override
       public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
          return new BasicDBObject("$project", new BasicDBObject("budgetCode", 1).append("taskCode", Arrays.asList("$taskCode")));
    }
};

Something like

Aggregation aggregation = newAggregation(project,
                    group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
                    sort(Sort.Direction.ASC, previousOperation(), "budgetCode"));

Using lambda

 Aggregation aggregation = newAggregation(
                aggregationOperationContext -> new BasicDBObject("$project", new BasicDBObject("budgetCode", 1).append("taskCode", Arrays.asList("$taskCode"))),
                group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
                sort(Sort.Direction.ASC, previousOperation(), "budgetCode"));


问:
How to include JBOSS modules in compile path
After applying patches to JBOSS 6.4 to bring it to 6.4.14, my build breaks.
I am using the various modules in the build path using **/*.jar. (See below for code)

RedHat disables old versions of jars when applying patches red hat doc

This is by design.

When applying a patch to EAP 6.2.0 to build EAP 6.2.x , the Patch tool does not replace the existing files. It will place new files under the folder $JBOSS_HOME/modules/system/layers/base/.overlays/_ and cripple the original files by flipping a bit in the end of central directory record to prevent them from being used.

How can I include all the jars in the modules directory except for the disabled ones?

Relevant portion of my build.xml file.

```<code><property name="jbossmodules" value="${env.JBOSS_HOME}/modules" />
<path id="class.path">
    <pathelement path="${class.lib}" />
    <pathelement path="${java.class.path}" />
    [...]
    <fileset dir="${jbossmodules}">
        <include name="**/*.jar" />
    </fileset>
</code>```

答: I worked with Redhat support. If one has the appropriate user type, one can download a directory of jars to compile against. In short Redhat seems to discourage compiling against a live patched version of JBOSS. But neither do they make it easy to get a set of jars one can compile against.</p>

Body:
After applying patches to JBOSS 6.4 to bring it to 6.4.14, my build breaks.
I am using the various modules in the build path using **/*.jar. (See below for code)

RedHat disables old versions of jars when applying patches red hat doc

This is by design.

When applying a patch to EAP 6.2.0 to build EAP 6.2.x , the Patch tool does not replace the existing files. It will place new files under the folder $JBOSS_HOME/modules/system/layers/base/.overlays/_ and cripple the original files by flipping a bit in the end of central directory record to prevent them from being used.

How can I include all the jars in the modules directory except for the disabled ones?

Relevant portion of my build.xml file.

<property name="jbossmodules" value="${env.JBOSS_HOME}/modules" />
<path id="class.path">
    <pathelement path="${class.lib}" />
    <pathelement path="${java.class.path}" />
    [...]
    <fileset dir="${jbossmodules}">
        <include name="**/*.jar" />
    </fileset>


问:
C++ date parsing with single digits
I am trying to parse a date which contains a single digit for each of the month and the day. The following parses correctly:

```<code>std::istringstream ss("2015/05/01");
std::tm tmb = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

ss >> std::get_time(&tmb, "%Y/%m/%d");
</code>```

But when I try to parse

```<code>std::istringstream ss("2015/5/1");
</code>```

I get a failed state in the stream and the time has not been read into the struct properly. Is there a clean (and efficient) way I can parse this?

EDIT: I am developing on Ubuntu 12.04 and the compiler g++ 5.4.1.

答:
You could use Howard Hinnant's portable, free, open-source date/time library.  Here is how the program would look:

```<code>#include "date.h"
#include <cassert>
#include <sstream>

int
main()
{
    date::year_month_day ymd;
    std::istringstream ss{"2015/5/1"};
    ss >> date::parse("%Y/%m/%d", ymd);
    assert(!ss.fail());
    using namespace date::literals;
    assert(ymd == may/1/2015);
}
</code>```

You can convert year_month_day into a std:tm if you really want to (here is how), but unless you need to communicate with some client that really needs a tm, there is no reason to.

"date.h" is header only, so it is easy to install, fully documented, easy to use, and builds on the C++11 <chrono>, so it is very type-safe.

Here is a wandbox link showing it running the above program with gcc 5.4.0.

Title: C++ date parsing with single digits

Body:
I am trying to parse a date which contains a single digit for each of the month and the day. The following parses correctly:

std::istringstream ss("2015/05/01");
std::tm tmb = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

ss >> std::get_time(&tmb, "%Y/%m/%d");

But when I try to parse

std::istringstream ss("2015/5/1");

I get a failed state in the stream and the time has not been read into the struct properly. Is there a clean (and efficient) way I can parse this?

EDIT: I am developing on Ubuntu 12.04 and the compiler g++ 5.4.1.

Body:
You could use Howard Hinnant's portable, free, open-source date/time library.  Here is how the program would look:

#include "date.h"
#include <cassert>
#include <sstream>

int
main()
{
    date::year_month_day ymd;
    std::istringstream ss{"2015/5/1"};
    ss >> date::parse("%Y/%m/%d", ymd);
    assert(!ss.fail());
    using namespace date::literals;
    assert(ymd == may/1/2015);
}

You can convert year_month_day into a std:tm if you really want to (here is how), but unless you need to communicate with some client that really needs a tm, there is no reason to.

"date.h" is header only, so it is easy to install, fully documented, easy to use, and builds on the C++11 <chrono>, so it is very type-safe.

Here is a wandbox link showing it running the above program with gcc 5.4.0.


问:
Installing Canopy on Windows 8
I am trying to install Canopy and I got this message throw the instalation process:

```<code>Acces is denied. Please change the permisions and restart Canopy.
</code>```

When I click OK, I see another message:

```<code>Canopy was not able to install User Python Enviroment at 'C:\...'. Please submit a bug report.
</code>```

When I finally open Editor in Canopy, I can see that "Python kernel has crashed", and I cant type anything.

What should I do? I tried three time everything from this page:

https://support.enthought.com/hc/en-us/articles/115001433803-Uninstalling-and-resetting-Canopy%20v2

But still nothing.

Can somebody help me please?

答: Submit a report from the Canopy help menu => Feedback / bugs. The report will include some detail about your setup and will allow Enthought Support to make specific suggestions.</p>

Title: Installing Canopy on Windows 8

Body:
I am trying to install Canopy and I got this message throw the instalation process:

Acces is denied. Please change the permisions and restart Canopy.

When I click OK, I see another message:

Canopy was not able to install User Python Enviroment at 'C:\...'. Please submit a bug report.

When I finally open Editor in Canopy, I can see that "Python kernel has crashed", and I cant type anything.

What should I do? I tried three time everything from this page:

https://support.enthought.com/hc/en-us/articles/115001433803-Uninstalling-and-resetting-Canopy%20v2

But still nothing.

Can somebody help me please?


问:
Apply utility method to externalizing text - Thymeleaf
I can't apply utility method to externalizing text, this is my code:

```<code>th:text="${#strings.escapeXml(config.companyname)}"
</code>```

What is the error? Thanks!

答:
I answer:</p>

```<code>th:utext="${#strings.escapeXml(#messages.msg('config.companyname'))}"
</code>```

Body:
I can't apply utility method to externalizing text, this is my code:

th:text="${#strings.escapeXml(config.companyname)}"

What is the error? Thanks!

Body:
I answer:

th:utext="${#strings.escapeXml(#messages.msg('config.companyname'))}"


问:
How to get Stings from Fragment to Activity
I have an app that works with Stings but I doesn*t know how to send String from a Fragment to an Activity. Somebody help me but I dont understand the code well.So If somebody have questions he could ask me and I could anserd it

Please help me

Fragment:

```<code>public class Fragment_1 extends Fragment {

    String text;
    int zähler = 0;
    String teile[];
    String in = "", in2 = "", in3 = "";
    ListView listView;
    public String [] liste;
    String value = "MIT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle bundle = new Bundle();
        bundle.putString("Key",value);

        Intent intent = getActivity().getIntent();
        intent.putExtras(bundle);

        View view = inflater.inflate(R.layout.fragment_1, container, false);

        listView = (ListView) view.findViewById(R.id.listView);
       // final Button but = (Button) view.findViewById(R.id.but1) ;

        new doit().execute();

        return view;
    }
</code>```

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
    String mesg = "MIT";

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        Bundle data = getIntent().getExtras();
        if (data != null) {

            String receivedString = data.getString("Key");

            Log.d("MainActivity", receivedString);
        }

        Log.d("MainActivity", "Bitte nicht" );

    }
</code>```

答:
Here you are, simply use a bundle to transfer data from your fragment back to your activity:</p>

```<code>//sending data from your fragment
Bundle bundle = new Bundle();
bundle.putString("KEY",value);

Intent intent = getActivity().getIntent();
intent.putExtras(bundle);

//Receving data inside your Activity
Bundle data = getIntent().getExtras();
if (data != null)
        {
            String receivedString= data.getString("KEY");

        }
</code>```

Body:
I have an app that works with Stings but I doesn*t know how to send String from a Fragment to an Activity. Somebody help me but I dont understand the code well.So If somebody have questions he could ask me and I could anserd it

Please help me

Fragment:

public class Fragment_1 extends Fragment {

    String text;
    int zähler = 0;
    String teile[];
    String in = "", in2 = "", in3 = "";
    ListView listView;
    public String [] liste;
    String value = "MIT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle bundle = new Bundle();
        bundle.putString("Key",value);

        Intent intent = getActivity().getIntent();
        intent.putExtras(bundle);

        View view = inflater.inflate(R.layout.fragment_1, container, false);

        listView = (ListView) view.findViewById(R.id.listView);
       // final Button but = (Button) view.findViewById(R.id.but1) ;

        new doit().execute();

        return view;
    }

MainActivity:

public class MainActivity extends AppCompatActivity {
    String mesg = "MIT";

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        Bundle data = getIntent().getExtras();
        if (data != null) {

            String receivedString = data.getString("Key");

            Log.d("MainActivity", receivedString);
        }

        Log.d("MainActivity", "Bitte nicht" );

    }

Body:
Here you are, simply use a bundle to transfer data from your fragment back to your activity:

//sending data from your fragment
Bundle bundle = new Bundle();
bundle.putString("KEY",value);

Intent intent = getActivity().getIntent();
intent.putExtras(bundle);

//Receving data inside your Activity
Bundle data = getIntent().getExtras();
if (data != null)
        {
            String receivedString= data.getString("KEY");

        }


问:
R Function to write 3 calculated columns to a data.table
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

```<code>  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]
</code>```

答:
The OP has tagged the question with data.table. docendo discimus' comment is showing the direction to follow.

Create sample data

```<code>library(data.table)   # CRAN version 1.10.4 used

n <- 10L
DT <- data.table(
  a = 1:n, b = (n:1)^2, c = -(1:n), d = 2 * (1:n) - n/2,
  e = rep(LETTERS[1:2], length.out = n),
  f = rep(LETTERS[3:4], each = n/2, length.out = n))
DT
#     a   b   c  d e f
# 1:  1 100  -1 -3 A C
# 2:  2  81  -2 -1 B C
# 3:  3  64  -3  1 A C
# 4:  4  49  -4  3 B C
# 5:  5  36  -5  5 A C
# 6:  6  25  -6  7 B D
# 7:  7  16  -7  9 A D
# 8:  8   9  -8 11 B D
# 9:  9   4  -9 13 A D
#10: 10   1 -10 15 B D
</code>```

Define function

```<code>fn <- function(p, q, r, s) {
  list(X1 = p + mean(q) + r + s,
       Y2 = p * q + r * s,
       Z3 = p * q - r * s)
}
</code>```

The function takes 4 parameters and returns a list of 3 named vectors. Note that the computations inside the function don't need to use for loops in contrast to OP's approach.

Apply function to data.table

Note that the OP wants to group on columns e and f when the function is applied.

The first variant creates a new data.table. By default, the names of the list elements as defined in fn are used:

```<code>DT[, fn(a, b, c, d), .(e, f)]
#    e f       X1   Y2  Z3
# 1: A C 63.66667  103  97
# 2: A C 67.66667  189 195
# 3: A C 71.66667  155 205
# 4: B C 64.00000  164 160
# 5: B C 68.00000  184 208
# 6: B D 18.66667  108 192
# 7: B D 22.66667  -16 160
# 8: B D 26.66667 -140 160
# 9: A D 19.00000   49 175
#10: A D 23.00000  -81 153
</code>```

The second variant updates DT by reference. The names of the new columns are explicitely stated.

```<code>DT[, c("x", "y", "z") := fn(a, b, c, d), .(e, f)]

DT
#     a   b   c  d e f        x    y   z
# 1:  1 100  -1 -3 A C 63.66667  103  97
# 2:  2  81  -2 -1 B C 64.00000  164 160
# 3:  3  64  -3  1 A C 67.66667  189 195
# 4:  4  49  -4  3 B C 68.00000  184 208
# 5:  5  36  -5  5 A C 71.66667  155 205
# 6:  6  25  -6  7 B D 18.66667  108 192
# 7:  7  16  -7  9 A D 19.00000   49 175
# 8:  8   9  -8 11 B D 22.66667  -16 160
# 9:  9   4  -9 13 A D 23.00000  -81 153
#10: 10   1 -10 15 B D 26.66667 -140 160
</code>```

Body:
This may have already been answered, but couldn't quite find the answer I am looking for. I am trying to write the output of a function that calculates 3 variables to a data.table.

Currently I am copying the function three times (with three different names), each time returning a different variable. This is taking a lot more time as it runs thrice. I understand
there may be a better way to do it, using list or some unique data.table command.

I would greatly appreciate any input you can provide to simplify this. Below is the example of how I am calling it one variable at a time.

Example

  fn_1 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_1)
  }

  data[ ,column_1 := fn_1(a,b,c,d) ,by= .(e,f) ]

  fn_2 <- function(a, b, c, d){

    for (i in 1:b) { col_1[i] = calculation }
    for (i in 1:c) { col_2[i] = calculation }
    for (i in 1:d) { col_3[i] = calculation }

    return(col_2)
  }

  data[ ,column_2 := fn_2(a,b,c,d) ,by= .(e,f) ]

Body:
The OP has tagged the question with data.table. docendo discimus' comment is showing the direction to follow.

Create sample data

library(data.table)   # CRAN version 1.10.4 used

n <- 10L
DT <- data.table(
  a = 1:n, b = (n:1)^2, c = -(1:n), d = 2 * (1:n) - n/2,
  e = rep(LETTERS[1:2], length.out = n),
  f = rep(LETTERS[3:4], each = n/2, length.out = n))
DT
#     a   b   c  d e f
# 1:  1 100  -1 -3 A C
# 2:  2  81  -2 -1 B C
# 3:  3  64  -3  1 A C
# 4:  4  49  -4  3 B C
# 5:  5  36  -5  5 A C
# 6:  6  25  -6  7 B D
# 7:  7  16  -7  9 A D
# 8:  8   9  -8 11 B D
# 9:  9   4  -9 13 A D
#10: 10   1 -10 15 B D

Define function

fn <- function(p, q, r, s) {
  list(X1 = p + mean(q) + r + s,
       Y2 = p * q + r * s,
       Z3 = p * q - r * s)
}

The function takes 4 parameters and returns a list of 3 named vectors. Note that the computations inside the function don't need to use for loops in contrast to OP's approach.

Apply function to data.table

Note that the OP wants to group on columns e and f when the function is applied.

The first variant creates a new data.table. By default, the names of the list elements as defined in fn are used:

DT[, fn(a, b, c, d), .(e, f)]
#    e f       X1   Y2  Z3
# 1: A C 63.66667  103  97
# 2: A C 67.66667  189 195
# 3: A C 71.66667  155 205
# 4: B C 64.00000  164 160
# 5: B C 68.00000  184 208
# 6: B D 18.66667  108 192
# 7: B D 22.66667  -16 160
# 8: B D 26.66667 -140 160
# 9: A D 19.00000   49 175
#10: A D 23.00000  -81 153

The second variant updates DT by reference. The names of the new columns are explicitely stated.

DT[, c("x", "y", "z") := fn(a, b, c, d), .(e, f)]

DT
#     a   b   c  d e f        x    y   z
# 1:  1 100  -1 -3 A C 63.66667  103  97
# 2:  2  81  -2 -1 B C 64.00000  164 160
# 3:  3  64  -3  1 A C 67.66667  189 195
# 4:  4  49  -4  3 B C 68.00000  184 208
# 5:  5  36  -5  5 A C 71.66667  155 205
# 6:  6  25  -6  7 B D 18.66667  108 192
# 7:  7  16  -7  9 A D 19.00000   49 175
# 8:  8   9  -8 11 B D 22.66667  -16 160
# 9:  9   4  -9 13 A D 23.00000  -81 153
#10: 10   1 -10 15 B D 26.66667 -140 160


问:
C# project builds OK , but no binaries produced
Using VS 2012, I build a C# project for a Debug build.  The build succeeds, but the directory ..\bin\debug is empty.

What can cause that and what can cure it?

Update:  This project builds a DLL

答: Check the "Build" tab in the project properties dialog and see what the "Output path" is set to for the "Debug" configuration. It probably builds in a location that's different than the default.</p>


问:
Integrating react-redux into an existing Angularjs application
I'm considering integrating react-redux into a 3 years old codebase of Angularjs. I don't wish to refactor the all codebase at once, rather incrementally introducing react-redux through new features which my team will develop.

Is there any best practices doing so? (any resources will be appreciated)

Can an old feature (written in ng) contain react-redux parts or I'll have to rewrite it?

How can I avoid doing the same API calls? (if both need the same resource)

Should I avoid the change all together?

答:
I've successfully migrated the application under the brown-field limitations I pointed out at the original question.

The solution is based on two approaches:

Small Components - are components that are pretty much contained. For example, notifications dropdown.

Entire part of the App that I can't migrate yet - basically some routes/views that are still written in Angular.

Both approached use a similar technique to the one which suggested here:
http://softeng.oicr.on.ca/chang_wang/2017/04/17/Using-AngularJS-components-directives-in-React/?utm_source=reactnl&utm_medium=email

TIP: It's much more easier if your Angular dependencies are managed properly.


问:
Testing on iOS 3.x using XCode 3.2.5
I am using XCode 3.2.5. Due to a problem in Flurry I would realy like to test my apps on iOS 3.x, and since I updated all my test devices to 4.x I don't have any 3.x handsets left.

I have tried to follow this guide on how to install extra SDKs into newer xcodes, but when installing previouse SDKs and launcing them the simulation doesn't work. It notifies that the SDK failed to launch and lets me choose either to Quit, switch SDK or Relaunch the simulator.

Is there anything that I am forgetting or missing? Did someone managed to install earlier SDK's into 3.2.5?

Br,
Paul Peelen

答:
i think its important to know that the simulator is a "forgiver" a lot more then the device.
i have released an app that worked great when tested on simulator for 3.1 but crashed on lunching when downloaded...you defiantly don't want that to happen.

i have mailed apple about that and the official answer i got was to test it on real devices.
thats a problem if you cant afford buying the devices. but try to get them second hand.

just don't trust the simulator alone.

ContentLicense: CC BY-SA 2.5

Title: Testing on iOS 3.x using XCode 3.2.5


问:
JS/Lodash - Group values which occur more than once?
I have an array something like:

```<code>const arr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456] },
  { id: 987, parent: [876] },
  { id: 811, parent: [137] },
  { id: 811, parent: [825] }
]
</code>```

An object with id 811 occurs 3 times.

I need to transform it into:

```<code>const newArr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456, 137, 825] },
  { id: 987, parent: [876] }
]
</code>```

That is, I need to find the objects that have an id which occurs more than once, then merge those objects into one object which has a parent array of the parent values from all the objects.

What's the best way to do this using lodash methods..?

答:
You can use reduce() method in plain js to do this, you just need to keep track of object id's and you can use another object for that.

const arr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456] },
  { id: 987, parent: [876] },
  { id: 811, parent: [137] },
  { id: 811, parent: [825] }
]

var o = {}
var result = arr.reduce(function(r, e) {
  if(!o[e.id]) o[e.id] = e, r.push(o[e.id])
  else o[e.id].parent.push(...e.parent)
  return r;
}, [])

console.log(result)```

Body:
I have an array something like:

const arr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456] },
  { id: 987, parent: [876] },
  { id: 811, parent: [137] },
  { id: 811, parent: [825] }
]

An object with id 811 occurs 3 times.

I need to transform it into:

const newArr = [
  { id: 123, parent: [345] },
  { id: 811, parent: [456, 137, 825] },
  { id: 987, parent: [876] }
]

That is, I need to find the objects that have an id which occurs more than once, then merge those objects into one object which has a parent array of the parent values from all the objects.

What's the best way to do this using lodash methods..?


问:
ng-repeat over array containing data with inner array having key-value similar will group together?
I have an array of data containing another array of data with key(TypeOfServiceAssigned:Array(2)) common in both inner array, I want to apply ng-repeat in such a way that similar key-value will group together and differnt one group seperatly.

for better explaination see below:

```<code>Array = [
  {
    Quotation:1200,
    TypeOfServiceAssigned:["Primary", "Partial Services"],
    VendorEmail:"A@gmail.com"
  },{
    Quotation:1350,
    TypeOfServiceAssigned:["Partial Services"],
    VendorEmail:"Add@gmail.com"
  }
];
</code>```

I want to apply ng repeat over Array so that it will show me two group depending upon TypeOfServiceAssigned value , one for Primary and second for Partial Sevicers. And for   Partial Sevicers, it will show me two list.

答:
Most efficient method is to handcraft function to return exact what you want..
example here , then bind it to your nested ng-repeat as you would do normally  :)

However normally we should do this on server side/service but anyway...

```<code>function doGroupBy() {
    var result = {};
    for (var i = 0; i < input.length; ++i) {
        var current = input[i].TypeOfServiceAssigned;
        for (var j = 0; j < current.length; ++j)
            if (result[current[j]])
                result[current[j]].push(input[i]); // result[current[j]] = [...result[current[j]], input[i]];
            else
                result[current[j]] = [input[i]];
    }

    return result;
}

var input = [{ Quotation: 1200, TypeOfServiceAssigned: ["Primary", "Partial Services"], VendorEmail: "A@gmail.com" },
             { Quotation: 1350, TypeOfServiceAssigned: ["Partial Services"], VendorEmail: "Add@gmail.com" }];

var testResult = doGroupBy(input);

for (var key in testResult) {
    console.log('-----------');
    console.log(key);
    console.log(testResult[key]);
}
</code>```

Body:
I have an array of data containing another array of data with key(TypeOfServiceAssigned:Array(2)) common in both inner array, I want to apply ng-repeat in such a way that similar key-value will group together and differnt one group seperatly.

for better explaination see below:

Array = [
  {
    Quotation:1200,
    TypeOfServiceAssigned:["Primary", "Partial Services"],
    VendorEmail:"A@gmail.com"
  },{
    Quotation:1350,
    TypeOfServiceAssigned:["Partial Services"],
    VendorEmail:"Add@gmail.com"
  }
];

I want to apply ng repeat over Array so that it will show me two group depending upon TypeOfServiceAssigned value , one for Primary and second for Partial Sevicers. And for   Partial Sevicers, it will show me two list.

Body:
Most efficient method is to handcraft function to return exact what you want..
example here , then bind it to your nested ng-repeat as you would do normally  :)

However normally we should do this on server side/service but anyway...

function doGroupBy() {
    var result = {};
    for (var i = 0; i < input.length; ++i) {
        var current = input[i].TypeOfServiceAssigned;
        for (var j = 0; j < current.length; ++j)
            if (result[current[j]])
                result[current[j]].push(input[i]); // result[current[j]] = [...result[current[j]], input[i]];
            else
                result[current[j]] = [input[i]];
    }

    return result;
}

var input = [{ Quotation: 1200, TypeOfServiceAssigned: ["Primary", "Partial Services"], VendorEmail: "A@gmail.com" },
             { Quotation: 1350, TypeOfServiceAssigned: ["Partial Services"], VendorEmail: "Add@gmail.com" }];

var testResult = doGroupBy(input);

for (var key in testResult) {
    console.log('-----------');
    console.log(key);
    console.log(testResult[key]);
}


问:
What happens if I don't cancel a Context?
I have the following code:

```<code>func Call(ctx context.Context, payload Payload) (Response, error) {
    req, err := http.NewRequest(...) // Some code that creates request from payload
    ctx, cancel = context.withTimeout(ctx, time.Duration(3) * time.Second)
    defer cancel()
    return http.DefaultClient.Do(req)
}
</code>```

What would happen if I didn't put defer cancel() in there?  go vet warned this

the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

How will the context be leaked and what impact will this have?  Thanks

答: If you fail to cancel the context, the goroutine that WithCancel or WithTimeout created will be retained in memory indefinitely (until the program shuts down), causing a memory leak.  If you do this a lot, your memory will balloon significantly.  It's best practice to use a defer cancel() immediately after calling WithCancel() or WithTimeout()

Body:
I have the following code:

func Call(ctx context.Context, payload Payload) (Response, error) {
    req, err := http.NewRequest(...) // Some code that creates request from payload
    ctx, cancel = context.withTimeout(ctx, time.Duration(3) * time.Second)
    defer cancel()
    return http.DefaultClient.Do(req)
}

What would happen if I didn't put defer cancel() in there?  go vet warned this

the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

How will the context be leaked and what impact will this have?  Thanks