问:
Simultaneous Sprite Touch Detection - iPhone & cocos2d
I am writing an app for the iPhone using cocos2d where I have 4 Sprites that are buttons.  I figured I would implement the button functionality by using 2 sprites with different .png files representing the pressed/unpressed states.  I thought this would be better than using an animation.  In addition to detecting when the buttons are pressed and released I need to detect when a two-button combination press/release occurs (like a chord).  I might even carry this forward to 3 and 4 button combos.  And one more feature I would like to implement would be detecting if a flick originated from within a button and respond with another action sequence.

What would be an optimal approach for this?  Would I use a bounding rect/or sprite for the four buttons (they are in a square formation) and swallow touches?  Then would I use the smaller sprite rects to determine which one(s) the touch(es) happened on?  Or would I have the individual sprite rects do the detection and then have them check to see if the other buttons are also pressed and then released at the same time?  Would I use a Bool state variable for either of these ways?

I had it all working great using CCMenu and CCMenuitem, by making one Menu/Menu-item for each button sprite; however, I could not figure out how to detect if a menu-item from one menu was pressed and released at the same time a menu-item from a different menu was pressed and released.  I used separate menus because if I used the same menu with multiple menu-items then only one could be pressed at a time.  I say it was working fine meaning it worked with single and multiple presses but it would treat multiples as two successive presses instead of a simultaneous press.  IE: a single press resulted in running a single action sequence(as intended), and a simultaneous press combination resulted in running  individual button action sequences for each button as if I had pressed them each separately(I want it to run one action sequence specific to that button combination).  This is why I decided it might be better to try to implement my own button system instead of using the CCMenu system.  Am I right in moving away from CCMenu?

Sorry for the long description, but it did say to be specific.  B)

Any insight as to how anyone else implemented or would implement this would be greatly appreciated!

答:
Here is how I implemented this in case anyone else is trying to do this.

spuButton.h (a CCSprite Subclass)

```<code>#import <Foundation/Foundation.h>
#import "cocos2d.h"

typedef enum tagButtonState {
    kButtonStatePressed,
    kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
    kButtonStatusEnabled,
    kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
    ButtonState buttonState;
    CCTexture2D *buttonNormal;
    CCTexture2D *buttonLit;
    ButtonStatus buttonStatus;
}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;
- (void)makeDisabled;
- (void)makeEnabled;
- (BOOL)isEnabled;
- (BOOL)isDisabled;
- (void)makeLit;
- (void)makeNormal;
- (void)dealloc;

@end
</code>```

spuButton.m

```<code>#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect {
    CGSize s = [self.texture contentSize];
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture {
    return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
    buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
    buttonLit = litTexture;
}

- (BOOL)isPressed {
    if (buttonState== kButtonStateNotPressed) return NO;
    if (buttonState== kButtonStatePressed) return YES;
    return NO;
}

- (BOOL)isNotPressed {
    if (buttonState== kButtonStateNotPressed) return YES;
    if (buttonState== kButtonStatePressed) return NO;
    return YES;
}

- (void)makeDisabled {
    buttonStatus = kButtonStatusDisabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}
- (void)makeEnabled {
    buttonStatus = kButtonStatusEnabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (BOOL)isEnabled {
    if (buttonStatus== kButtonStatusDisabled) return NO;
    if (buttonStatus== kButtonStatusEnabled) return YES;
    return NO;
}

- (BOOL)isDisabled {
    if (buttonStatus== kButtonStatusEnabled) return NO;
    if (buttonStatus== kButtonStatusDisabled) return YES;
    return YES;
}

- (void)makeLit {
    [self setTexture:buttonLit];
}

- (void)makeNormal {
    [self setTexture:buttonNormal];
}

- (id)initWithTexture:(CCTexture2D *)aTexture {
    if ((self = [super initWithTexture:aTexture]) ) {
        buttonState = kButtonStateNotPressed;
        buttonStatus = kButtonStatusEnabled;
    }
    return self;
}

- (void)onEnter {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
    [super onEnter];
}

- (void)onExit {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}

- (BOOL)containsTouchLocation:(UITouch *)touch {
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return NO;
    if (buttonState== kButtonStatePressed) return NO;
    if ( ![self containsTouchLocation:touch] ) return NO;

    buttonState= kButtonStatePressed;
    [self makeLit];

    return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.

    if (buttonStatus == kButtonStatusDisabled) return;
    if ([self containsTouchLocation:touch]) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)dealloc {
    [buttonNormal release];
    [buttonLit release];
    [super dealloc];
}

@end
</code>```

HelloWorldScene.m (Just my tick: method to keep my other functions from confusing the example)

```<code>-(void)tick:(ccTime)dt {
    if ([[_otherControlsArray objectAtIndex:0] wasPressed]) {
        [[_otherControlsArray objectAtIndex:0] setWasPressed:NO];
        [self removeChild:[_otherControlsArray objectAtIndex:0] cleanup:YES];
        [self addChild:[_otherControlsArray objectAtIndex:1]];
        NSLog(@"Play");

        _gameHasNotBeenPlayedYet = NO;
        Snarfle_s_PowerUPAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate makeNotPaused];
        [self gameLogic];
    }

    if (_gameHasNotBeenPlayedYet) {
        return;
    }

    if (_buttonsPressedAndReleased > 0) {  //respond to button(s) released and reset
        NSLog(@"Buttons Pressed and Released-->%d",_buttonsPressedAndReleased);
        if ([self checkButtons:_buttonsPressedAndReleased]);
        _buttonsPressed = 0;
        _buttonsPressedAndReleased = 0;

        return;
    }
    if (_buttonsPressed <= 4) { // two buttons have not already been pressed
        for (spuButton *aButton in _fourButtonsArray) {
            if ([aButton isNotPressed]) continue; //this button is not pressed
            if (_buttonsPressed == 0) { //this button is pressed and no other buttons have been pressed
                _buttonsPressed = aButton.tag;
                continue;
            }
            //this button is pressed while another has been pressed
            //figure out which two buttons have been pressed
            if (_buttonsPressed == 1) {  //red plus another
                switch (aButton.tag) {
                    case 2:   //blue
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 1;
                        break;
                }
            }
            if (_buttonsPressed == 2) {  //blue plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 2;
                        break;
                }
            }
            if (_buttonsPressed == 3) {  //green plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 3;
                        break;
                }
            }
            if (_buttonsPressed == 4) {  //yellow plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 4;
                        break;
                }
            }
            if (_buttonsPressed > 4) break;  //more than one has been pressed and identified
        }
    }
    //now we know what buttons have been pressed now check to see if they have been released
    //if more than one has been pressed disable the other two
    //also if more than one has been pressed and one of them gets released disable the released one but keep it lit
    switch (_buttonsPressed) {
        case 1:  //red
            if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) _buttonsPressedAndReleased = 1;
            break;
        case 2:  //blue
            if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) _buttonsPressedAndReleased = 2;
            break;
        case 3:  //green
            if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) _buttonsPressedAndReleased = 3;
            break;
        case 4:  //yellow
            if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) _buttonsPressedAndReleased = 4;
            break;
        case 5:  //red & blue
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:1] isNotPressed])) _buttonsPressedAndReleased = 5;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
            }
            break;
        case 6:  //red & green
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 6;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 7:  //red & yellow
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 7;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 8:  //blue & green
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 8;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 9:  //blue & yellow
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 9;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 10:  //green & yellow
            if (([[_fourButtonsArray objectAtIndex:2] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 10;
            else {
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        default:
            _buttonsPressedAndReleased = 0;
            break;
    }
}
</code>```

Body:
Here is how I implemented this in case anyone else is trying to do this.

spuButton.h (a CCSprite Subclass)

#import <Foundation/Foundation.h>
#import "cocos2d.h"

typedef enum tagButtonState {
    kButtonStatePressed,
    kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
    kButtonStatusEnabled,
    kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
    ButtonState buttonState;
    CCTexture2D *buttonNormal;
    CCTexture2D *buttonLit;
    ButtonStatus buttonStatus;
}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;
- (void)makeDisabled;
- (void)makeEnabled;
- (BOOL)isEnabled;
- (BOOL)isDisabled;
- (void)makeLit;
- (void)makeNormal;
- (void)dealloc;

@end

spuButton.m

#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect {
    CGSize s = [self.texture contentSize];
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture {
    return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
    buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
    buttonLit = litTexture;
}

- (BOOL)isPressed {
    if (buttonState== kButtonStateNotPressed) return NO;
    if (buttonState== kButtonStatePressed) return YES;
    return NO;
}

- (BOOL)isNotPressed {
    if (buttonState== kButtonStateNotPressed) return YES;
    if (buttonState== kButtonStatePressed) return NO;
    return YES;
}

- (void)makeDisabled {
    buttonStatus = kButtonStatusDisabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}
- (void)makeEnabled {
    buttonStatus = kButtonStatusEnabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (BOOL)isEnabled {
    if (buttonStatus== kButtonStatusDisabled) return NO;
    if (buttonStatus== kButtonStatusEnabled) return YES;
    return NO;
}

- (BOOL)isDisabled {
    if (buttonStatus== kButtonStatusEnabled) return NO;
    if (buttonStatus== kButtonStatusDisabled) return YES;
    return YES;
}

- (void)makeLit {
    [self setTexture:buttonLit];
}

- (void)makeNormal {
    [self setTexture:buttonNormal];
}

- (id)initWithTexture:(CCTexture2D *)aTexture {
    if ((self = [super initWithTexture:aTexture]) ) {
        buttonState = kButtonStateNotPressed;
        buttonStatus = kButtonStatusEnabled;
    }
    return self;
}

- (void)onEnter {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
    [super onEnter];
}

- (void)onExit {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}

- (BOOL)containsTouchLocation:(UITouch *)touch {
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return NO;
    if (buttonState== kButtonStatePressed) return NO;
    if ( ![self containsTouchLocation:touch] ) return NO;

    buttonState= kButtonStatePressed;
    [self makeLit];

    return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.

    if (buttonStatus == kButtonStatusDisabled) return;
    if ([self containsTouchLocation:touch]) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)dealloc {
    [buttonNormal release];
    [buttonLit release];
    [super dealloc];
}

@end

HelloWorldScene.m (Just my tick: method to keep my other functions from confusing the example)

-(void)tick:(ccTime)dt {
    if ([[_otherControlsArray objectAtIndex:0] wasPressed]) {
        [[_otherControlsArray objectAtIndex:0] setWasPressed:NO];
        [self removeChild:[_otherControlsArray objectAtIndex:0] cleanup:YES];
        [self addChild:[_otherControlsArray objectAtIndex:1]];
        NSLog(@"Play");

        _gameHasNotBeenPlayedYet = NO;
        Snarfle_s_PowerUPAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate makeNotPaused];
        [self gameLogic];
    }

    if (_gameHasNotBeenPlayedYet) {
        return;
    }

    if (_buttonsPressedAndReleased > 0) {  //respond to button(s) released and reset
        NSLog(@"Buttons Pressed and Released-->%d",_buttonsPressedAndReleased);
        if ([self checkButtons:_buttonsPressedAndReleased]);
        _buttonsPressed = 0;
        _buttonsPressedAndReleased = 0;

        return;
    }
    if (_buttonsPressed <= 4) { // two buttons have not already been pressed
        for (spuButton *aButton in _fourButtonsArray) {
            if ([aButton isNotPressed]) continue; //this button is not pressed
            if (_buttonsPressed == 0) { //this button is pressed and no other buttons have been pressed
                _buttonsPressed = aButton.tag;
                continue;
            }
            //this button is pressed while another has been pressed
            //figure out which two buttons have been pressed
            if (_buttonsPressed == 1) {  //red plus another
                switch (aButton.tag) {
                    case 2:   //blue
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 1;
                        break;
                }
            }
            if (_buttonsPressed == 2) {  //blue plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 2;
                        break;
                }
            }
            if (_buttonsPressed == 3) {  //green plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 3;
                        break;
                }
            }
            if (_buttonsPressed == 4) {  //yellow plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 4;
                        break;
                }
            }
            if (_buttonsPressed > 4) break;  //more than one has been pressed and identified
        }
    }
    //now we know what buttons have been pressed now check to see if they have been released
    //if more than one has been pressed disable the other two
    //also if more than one has been pressed and one of them gets released disable the released one but keep it lit
    switch (_buttonsPressed) {
        case 1:  //red
            if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) _buttonsPressedAndReleased = 1;
            break;
        case 2:  //blue
            if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) _buttonsPressedAndReleased = 2;
            break;
        case 3:  //green
            if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) _buttonsPressedAndReleased = 3;
            break;
        case 4:  //yellow
            if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) _buttonsPressedAndReleased = 4;
            break;
        case 5:  //red & blue
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:1] isNotPressed])) _buttonsPressedAndReleased = 5;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
            }
            break;
        case 6:  //red & green
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 6;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 7:  //red & yellow
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 7;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 8:  //blue & green
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 8;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 9:  //blue & yellow
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 9;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 10:  //green & yellow
            if (([[_fourButtonsArray objectAtIndex:2] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 10;
            else {
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        default:
            _buttonsPressedAndReleased = 0;
            break;
    }
}


来源: stackexchange

问:
Video Compression using ffpmeg
I am using ffmeg for video compression. I have used ffpmeg library

Use command "ffmpeg -i " + filein.trim() + " -vcodec h264 -acodec mp2 " + fileout.trim() but i doesn't respond anything.

I have used any ndk library for first time.

答:
Use this command will work for you. This works for me .</p>

```<code>String cmd = "-y -i " + currentInputVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " + "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 320x240 -aspect 4:3 " + currentOutputVideoPath;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Video Compression using ffpmeg

Body:
Use this command will work for you. This works for me .

String cmd = "-y -i " + currentInputVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " + "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 320x240 -aspect 4:3 " + currentOutputVideoPath;


问:
pass int data via bundle
I am currently working on a quiz application whereby i need to review answered questions after each quiz session. So, am passing the number of questions attempted as an int value with a bundle to the next activity.

So, am looping forward and backwards against my array of questions in which the index limit is the int which was passed from previous activity. However, am having some trouble as it isn't looping correctly. How do i get round this?

Question Class

```<code>class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}
</code>```

MainActivity.java

```<code>Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
                    intent.putExtra("quizNumber", mquizNumber);
startActivity(intent);
</code>```

ResultsActivity.java

```<code>Intent intent = new Intent(ResultsActivity.this, ReviewActivity.class);
                Bundle exBundle= getIntent().getExtras();
                int intValue= 0;
                if (exBundle != null) {
                    intValue = exBundle.getInt("quizNumber");
                }
               intent.putExtra("quizNumber", intValue);
                startActivity(intent);
</code>```

ReviewActivity.java

```<code>public class ReviewActivity extends AppCompatActivity {
    private Question mQuestionLibrary = new Question();
private TextView mQuestionText;
 private int intValue; // int value from quiz activity to be passed here
    private int mQuestionNumber = 1; // current question number
//navigation buttons for looping through array
    private Button mPrevious;
    private Button mNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        }
        setContentView(R.layout.activity_beginner_review);
        mQuestionText = (TextView) findViewById(R.id.txtQuestion);
        //setting buttons
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        // retrieve the number of attempted questions int value from quizActivity in Bundle
        Bundle exBundle= getIntent().getExtras();
       intValue = 0;
        if (exBundle != null) {
            intValue = exBundle.getInt("quizNumber");
        }
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(true);
            }
        });
        mPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(false);
            }
        });
    }
// logic for looping through array.
    private void updateQuestion(boolean forward) {
        animateAnswerButton();
        if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
            mQuestionNumber++;
        else if (mQuestionNumber>0)
            mQuestionNumber--;
        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    }

}
</code>```

答:
I think you should do this.

```<code>class DataStore{/*New class DataStore*/

public static int quizNumber=0;

}
</code>```

/Mainactivity/

```<code>DataStore.quizNumber=mquizNumber;
startActivity(MainActivity.this, ResultsActivity.class);
</code>```

/ReviewActivity/

```<code>intValue=DataStore.quizNumber;
</code>```

Title: pass int data via bundle

Body:
I am currently working on a quiz application whereby i need to review answered questions after each quiz session. So, am passing the number of questions attempted as an int value with a bundle to the next activity.

So, am looping forward and backwards against my array of questions in which the index limit is the int which was passed from previous activity. However, am having some trouble as it isn't looping correctly. How do i get round this?

Question Class

class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}

MainActivity.java

Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
                    intent.putExtra("quizNumber", mquizNumber);
startActivity(intent);

ResultsActivity.java

Intent intent = new Intent(ResultsActivity.this, ReviewActivity.class);
                Bundle exBundle= getIntent().getExtras();
                int intValue= 0;
                if (exBundle != null) {
                    intValue = exBundle.getInt("quizNumber");
                }
               intent.putExtra("quizNumber", intValue);
                startActivity(intent);

ReviewActivity.java

public class ReviewActivity extends AppCompatActivity {
    private Question mQuestionLibrary = new Question();
private TextView mQuestionText;
 private int intValue; // int value from quiz activity to be passed here
    private int mQuestionNumber = 1; // current question number
//navigation buttons for looping through array
    private Button mPrevious;
    private Button mNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        }
        setContentView(R.layout.activity_beginner_review);
        mQuestionText = (TextView) findViewById(R.id.txtQuestion);
        //setting buttons
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        // retrieve the number of attempted questions int value from quizActivity in Bundle
        Bundle exBundle= getIntent().getExtras();
       intValue = 0;
        if (exBundle != null) {
            intValue = exBundle.getInt("quizNumber");
        }
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(true);
            }
        });
        mPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(false);
            }
        });
    }
// logic for looping through array.
    private void updateQuestion(boolean forward) {
        animateAnswerButton();
        if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
            mQuestionNumber++;
        else if (mQuestionNumber>0)
            mQuestionNumber--;
        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    }

}

Body:
I think you should do this.

class DataStore{/*New class DataStore*/

public static int quizNumber=0;

}

/Mainactivity/

DataStore.quizNumber=mquizNumber;
startActivity(MainActivity.this, ResultsActivity.class);

/ReviewActivity/

intValue=DataStore.quizNumber;


问:
regex replace not working in HIVE
I want to replace the ; in data to : in HIVE
tried the following but not working

```<code>hive> select REGEXP_REPLACE('Mozilla/5.0 (Macintosh; Intel',';',':');
</code>```

How to achieve this in HIVE. I am getting issues while transforming this.

答:
Just use replace():

```<code>select replace('Mozilla/5.0 (Macintosh; Intel', ';', ':')
</code>```

replace() is described in the documentation.

Title: regex replace not working in HIVE

Body:
I want to replace the ; in data to : in HIVE
tried the following but not working

hive> select REGEXP_REPLACE('Mozilla/5.0 (Macintosh; Intel',';',':');

How to achieve this in HIVE. I am getting issues while transforming this.

Body:
Just use replace():

select replace('Mozilla/5.0 (Macintosh; Intel', ';', ':')

replace() is described in the documentation.


问:
Conditional If Statement: If value in row contains string ... set another column equal to string
EDIT MADE:

I have the 'Activity' column filled with strings and I want to derive the values in the 'Activity_2' column using an if statement.

So Activity_2 shows the desired result.  Essentially I want to call out what type of activity is occurring.

I tried to do this using my code below but it won't run (please see screen shot below for error). Any help is greatly appreciated!

```<code>    for i in df2['Activity']:
        if i contains 'email':
            df2['Activity_2'] = 'email'
        elif i contains 'conference'
            df2['Activity_2'] = 'conference'
        elif i contains 'call'
            df2['Activity_2'] = 'call'
        else:
            df2['Activity_2'] = 'task'

Error: if i contains 'email':
                ^
SyntaxError: invalid syntax
</code>```

答:
This also works:</p>

```<code>df.loc[df['Activity'].str.contains('email'), 'Activity_2'] = 'email'
df.loc[df['Activity'].str.contains('conference'), 'Activity_2'] = 'conference'
df.loc[df['Activity'].str.contains('call'), 'Activity_2'] = 'call'
</code>```

Body:
EDIT MADE:

I have the 'Activity' column filled with strings and I want to derive the values in the 'Activity_2' column using an if statement.

So Activity_2 shows the desired result.  Essentially I want to call out what type of activity is occurring.

I tried to do this using my code below but it won't run (please see screen shot below for error). Any help is greatly appreciated!

    for i in df2['Activity']:
        if i contains 'email':
            df2['Activity_2'] = 'email'
        elif i contains 'conference'
            df2['Activity_2'] = 'conference'
        elif i contains 'call'
            df2['Activity_2'] = 'call'
        else:
            df2['Activity_2'] = 'task'

Error: if i contains 'email':
                ^
SyntaxError: invalid syntax

Body:
This also works:

df.loc[df['Activity'].str.contains('email'), 'Activity_2'] = 'email'
df.loc[df['Activity'].str.contains('conference'), 'Activity_2'] = 'conference'
df.loc[df['Activity'].str.contains('call'), 'Activity_2'] = 'call'


问:
MAVEN_HOME, MVN_HOME or M2_HOME
What's the correct Maven environment variable name: MAVEN_HOME, MVN_HOME or M2_HOME?

I've found some details about MAVEN_HOME and M2_HOME here. But I also have seen MVN_HOME around.

答: M2_HOME (and the like) is not to be used as of Maven 3.5.0. See MNG-5607 and Release Notes for details.

Title: MAVEN_HOME, MVN_HOME or M2_HOME

ContentLicense: CC BY-SA 4.0


问:
Polymorphic Association other than model name
I have two models:

Payment.rb

```<code>belongs_to :payer, polymorphic: true, required: true
belongs_to :payable, polymorphic: true
belongs_to :sponsor, -> { where(payments: { payable_type: 'Sponsor' }) },
                          foreign_key: 'payable_id'`
</code>```

Sponsor.rb

```<code>has_many :payments, as: :payable, dependent: :destroy
</code>```

I am able to create payment using payable_type "sponsor" and payable_id  "sponsor_id".

I can access @payment.payable

Result for this is payable_type is sponsor.

I want to store payable type as sponsorship and model for it obviously Sponsor. If I will access @payment.payable.

Result for this should be payable_type is Sponsorship.

Any suggestions welcome as soon as possible.

答:
No other way I could think of for this.</p>

```<code>class Sponsor < ActiveRecord::Base
end

class Sponsorship < Sponsor
end
</code>```

Body:
I have two models:

Payment.rb

belongs_to :payer, polymorphic: true, required: true
belongs_to :payable, polymorphic: true
belongs_to :sponsor, -> { where(payments: { payable_type: 'Sponsor' }) },
                          foreign_key: 'payable_id'`

Sponsor.rb

has_many :payments, as: :payable, dependent: :destroy

I am able to create payment using payable_type "sponsor" and payable_id  "sponsor_id".

I can access @payment.payable

Result for this is payable_type is sponsor.

I want to store payable type as sponsorship and model for it obviously Sponsor. If I will access @payment.payable.

Result for this should be payable_type is Sponsorship.

Any suggestions welcome as soon as possible.

Body:
No other way I could think of for this.

class Sponsor < ActiveRecord::Base
end

class Sponsorship < Sponsor
end


问:
Placing methods in foreach loop c#
not sure if the title is really correct, but this is the issue...

I have a foreach loop populating a pushpin collection. I need to do some 'work' on one of the XML elements (Latitude). the 'work' is commented out. The problem is I cant see where to put these tasks/variables anywhere. wherever I place it I get a varity of errors. I can go into more detail of that if needed, but wondering if there is a better way of doing this. Its preey self explanitory below what im trying to do but let me know if you need more explanation. Any suggestions welcome.

```<code>  public void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        var document = XDocument.Load(e.Result);
        if (document.Root == null)
            return;
         var events = from ev in document.Descendants("item")

                      .Where(ev => ev.Element("category") != null)

                     select new
                     {

                         Title = (ev.Element("title").Value),
                         Description = (ev.Element("description").Value),
                         Category = (ev.Element("category").Value),
                         Latitude = (ev.Element("link").Value),

                      };

         ObservableCollection<Eng> pushPinCollection = new ObservableCollection<Eng>();

        foreach (var ev in events)
         {

             Eng PushPin = new Eng
               (ev.Title, ev.Description, ev.Category)

           // Lat1 = (ev.Latitude),
            //  var items = Lat1.Split('?')[1].Split('&').Select(i => i.Split  ('=')).ToDictionary(o => o[0], o => o[1]);
            //  var lon = items["lon"];
            //  var lat = items["lat"];
            //  var lat1 = Convert.ToDouble(lat);
            //  var lon1 = Convert.ToDouble(lon);
             {

        //Location value below is System.Device.location.Geocoordinate Eng Location
                  Location = new GeoCoordinate(lat1, lon1),
                  Title = ev.Title,
                  Description = ev.Description,
                  Category = ev.Category

             };
            pushPinCollection.Add(PushPin);
         }
         pushPins = pushPinCollection;
         mapItems.ItemsSource = PushPins;

       }
</code>```

答: Generally speaking...you should declare variables in the "narrowest" scope possible.  However, if you'll be accessing the variables outside of the For Loop, you'll need to declare them outside the For Loop.  Probably just above the "foreach (var ev in events)" line should be Ok.</p>

ContentLicense: CC BY-SA 2.5

Title: Placing methods in foreach loop c#

Body:
not sure if the title is really correct, but this is the issue...

I have a foreach loop populating a pushpin collection. I need to do some 'work' on one of the XML elements (Latitude). the 'work' is commented out. The problem is I cant see where to put these tasks/variables anywhere. wherever I place it I get a varity of errors. I can go into more detail of that if needed, but wondering if there is a better way of doing this. Its preey self explanitory below what im trying to do but let me know if you need more explanation. Any suggestions welcome.

  public void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        var document = XDocument.Load(e.Result);
        if (document.Root == null)
            return;
         var events = from ev in document.Descendants("item")

                      .Where(ev => ev.Element("category") != null)

                     select new
                     {

                         Title = (ev.Element("title").Value),
                         Description = (ev.Element("description").Value),
                         Category = (ev.Element("category").Value),
                         Latitude = (ev.Element("link").Value),

                      };

         ObservableCollection<Eng> pushPinCollection = new ObservableCollection<Eng>();

        foreach (var ev in events)
         {

             Eng PushPin = new Eng
               (ev.Title, ev.Description, ev.Category)

           // Lat1 = (ev.Latitude),
            //  var items = Lat1.Split('?')[1].Split('&').Select(i => i.Split  ('=')).ToDictionary(o => o[0], o => o[1]);
            //  var lon = items["lon"];
            //  var lat = items["lat"];
            //  var lat1 = Convert.ToDouble(lat);
            //  var lon1 = Convert.ToDouble(lon);
             {

        //Location value below is System.Device.location.Geocoordinate Eng Location
                  Location = new GeoCoordinate(lat1, lon1),
                  Title = ev.Title,
                  Description = ev.Description,
                  Category = ev.Category

             };
            pushPinCollection.Add(PushPin);
         }
         pushPins = pushPinCollection;
         mapItems.ItemsSource = PushPins;

       }


问:
Set hover on the link inside a class
I'm trying to set a :hover for a link inside a class. At first I tried

```<code>.link{
color: #e62739;
}
</code>```

I saw past discusssion and try the solution proposed

```<code>.opener a.link:hover {
    color: #e62739;
}
</code>```

but it didn't work. Im'not sure to know where is my mistake.

.link{text-decoration:none; color:white;}

.opener a.link:hover {
    color: #e62739;
}

.row {
  display: flex; /* equal height of the children */
}

.col {
  flex: 1; /* additionally, equal width */

  padding: 1em;
  border: solid;
}

div {font-family:'Varela Round';
}

  .opener {
  background-color: #07183d;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  border: 1px white solid;
}

.benefits {
  background-color: #07183d;
  border: none;
  color: white;
  padding: 15px 32px;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  width:300px;
}

a {
  text-decoration: none;
}

#upbutton {
  border: 1px dotted white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
<div class="opener col" style="padding-left: 10px;padding-right: 10px;">SOCIETES: 400
<div class="benefits" id="b1" style="display: none; color: white; font-size: 14px;">Part SBF 120 : 120<br />
Part Filiales +100M€: 280
<div id="upbutton">fermer</div>
</div>
</div></code>```

答:
The issue is the inline styling you've got on the link: color: white;.

This is taking priority over any styling you're adding in your CSS file. Removing that from the inline styling allows the hover color to work.

If you need the white color by default add it to the stylesheet rather than inline. For example:

```<code>.link {
color: white;
}
</code>```

Title: Set hover on the link inside a class

Body:
I'm trying to set a :hover for a link inside a class. At first I tried

.link{
color: #e62739;
}

I saw past discusssion and try the solution proposed

.opener a.link:hover {
    color: #e62739;
}

but it didn't work. Im'not sure to know where is my mistake.

.link{text-decoration:none; color:white;}

.opener a.link:hover {
    color: #e62739;
}

.row {
  display: flex; /* equal height of the children */
}

.col {
  flex: 1; /* additionally, equal width */

  padding: 1em;
  border: solid;
}

div {font-family:'Varela Round';
}

  .opener {
  background-color: #07183d;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  border: 1px white solid;
}

.benefits {
  background-color: #07183d;
  border: none;
  color: white;
  padding: 15px 32px;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  width:300px;
}

a {
  text-decoration: none;
}

#upbutton {
  border: 1px dotted white;
}

SOCIETES: 400

Part SBF 120 : 120

Part Filiales +100M€: 280

fermer

Body:
The issue is the inline styling you've got on the link: color: white;.

This is taking priority over any styling you're adding in your CSS file. Removing that from the inline styling allows the hover color to work.

If you need the white color by default add it to the stylesheet rather than inline. For example:

.link {
color: white;
}


问:
handleSubmit triggered with invalid field
So i'm using this example to try and build a simple form that validates synchronously.

This is my form:

```<code>const DatasetForm: React.StatelessComponent = (props: any) => {
    const { handleSubmit, pristine, reset, submitting } = props;
    console.log(props);

    return (<form onSubmit= { handleSubmit }>
            <div>
                <div>
                    <Field
                        name="firstName"
                        component= {renderField}
                        type="text"
                        label="First Name"
                    />
                </div>
                <div>
                    <button type="submit" disabled={submitting}>Submit</button>
                </div>
            </div>
        </form>)
}
</code>```

I'm using exactly the same renderField function and this is my validate function:

```<code>const validate = (values: IValues) => {
    let errors: IValues = {
        firstName: ''
    };
    if (!values.firstName) {
        errors.firstName = 'Required';
    }
    else if (values.firstName !== 'aaaaa') {
        errors.firstName = 'Must be aaaaa';
    }
    return errors;
}
</code>```

The handleSubmit function is a simple console.log and is passed as a prop.

Now in the example the handleSubmit function doesn't seem to be called if a field is not valid. But in my code, it is definitely called every time i click the submit button. I've stared at both my and the example code for a long time without finding what may cause this difference. Any help is appreciated.

EDIT: Adding the export function:

```<code>export default reduxForm({
    form: 'simpleForm',
    validate
})(DatasetForm);
</code>```

答:
You need to pass in your custom validate function to your wrapped custom form DatasetForm. Like this:

```<code>const validate2 = (values) => {
  let errors = {};
  if (!values.firstName) {
    errors.firstName = 'Required';
  }
  else if (values.firstName !== 'aaaaa') {
    errors.firstName = 'Must be aaaaa';
  }
  console.log(errors);
  return errors;
}
</code>```

```<code>const DatasetForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props;

  return (<form onSubmit={handleSubmit}>
    <div>
      <div>
        <Field
          name="firstName"
          component={renderField}
          type="text"
          label="First Name"
        />
      </div>
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
      </div>
    </div>
  </form>)
}

export default reduxForm({
  form: 'syncValidation',
  validate: validate2,
  warn
})(DatasetForm)
</code>```

Check out this working sample.

Body:
So i'm using this example to try and build a simple form that validates synchronously.

This is my form:

const DatasetForm: React.StatelessComponent = (props: any) => {
    const { handleSubmit, pristine, reset, submitting } = props;
    console.log(props);

    return (<form onSubmit= { handleSubmit }>

                    <Field
                        name="firstName"
                        component= {renderField}
                        type="text"
                        label="First Name"
                    />

                    <button type="submit" disabled={submitting}>Submit</button>

        </form>)
}

I'm using exactly the same renderField function and this is my validate function:

const validate = (values: IValues) => {
    let errors: IValues = {
        firstName: ''
    };
    if (!values.firstName) {
        errors.firstName = 'Required';
    }
    else if (values.firstName !== 'aaaaa') {
        errors.firstName = 'Must be aaaaa';
    }
    return errors;
}

The handleSubmit function is a simple console.log and is passed as a prop.

Now in the example the handleSubmit function doesn't seem to be called if a field is not valid. But in my code, it is definitely called every time i click the submit button. I've stared at both my and the example code for a long time without finding what may cause this difference. Any help is appreciated.

EDIT: Adding the export function:

export default reduxForm({
    form: 'simpleForm',
    validate
})(DatasetForm);

Body:
You need to pass in your custom validate function to your wrapped custom form DatasetForm. Like this:

const validate2 = (values) => {
  let errors = {};
  if (!values.firstName) {
    errors.firstName = 'Required';
  }
  else if (values.firstName !== 'aaaaa') {
    errors.firstName = 'Must be aaaaa';
  }
  console.log(errors);
  return errors;
}

const DatasetForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props;

  return (<form onSubmit={handleSubmit}>
    <div>
      <div>
        <Field
          name="firstName"
          component={renderField}
          type="text"
          label="First Name"
        />
      </div>
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
      </div>
    </div>
  </form>)
}

export default reduxForm({
  form: 'syncValidation',
  validate: validate2,
  warn
})(DatasetForm)

Check out this working sample.


问:
Unexpected Transaction Isolation Level in .NET with multiple connections
I've put together a sample application to mimic some of our main application code functionality.  Whilst working on this, I've been thrown a bit of a curve ball into my understanding of TransactionScope and SqlConnection.

The problem I see is explicitly "see" an IsolationLevel of READ COMMITTED where I would expect SERIALIZABLE.  Unless my methods are diagnosis are flawed.

Currently my database has Read Snapshot enabled so the screenshots show the READ COMMITTED SNAPSHOT.  When this is not enabled, then the screenshots will show READ COMMITTED.

Code

The code is running locally on my machine connecting to a local instance of SQL Server 2014.  This is the minimal code required.

So to replicate this scenario from a Console application:

```<code>using System;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using IsolationLevel = System.Transactions.IsolationLevel;

namespace IsolationLevelConsoleProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var tran = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions
            {
                IsolationLevel = IsolationLevel.Serializable,
                Timeout = TimeSpan.FromMinutes(3)
            }))
            {
                using (var connectionForRead = new SqlConnection(GetConnectionString("For Read")))
                {
                    connectionForRead.Open();

                    using (var commandRead = new SqlCommand("usp_GetAllSimpleTable", connectionForRead))
                    {
                        commandRead.CommandType = CommandType.StoredProcedure;
                        commandRead.CommandTimeout = 120;

                        DataSet dataSet = new DataSet();
                        SqlDataAdapter adapter = new SqlDataAdapter
                        {
                            SelectCommand = commandRead
                        };

                        adapter.Fill(dataSet);
                    }
                }

                using (var connectionForUpdate = new SqlConnection(GetConnectionString("For Update")))
                {
                    connectionForUpdate.Open();

                    using (var commandUpdate = new SqlCommand("usp_UpdateSimpleTable", connectionForUpdate))
                    {
                        commandUpdate.CommandTimeout = 120;
                        commandUpdate.CommandType = CommandType.StoredProcedure;
                        commandUpdate.Parameters.AddWithValue("@Guid", Guid.Parse("{74B3155E-138E-4881-BEE2-67FD141E29DA}"));
                        commandUpdate.Parameters.AddWithValue("@Name", $"Name {DateTime.UtcNow}");
                        commandUpdate.ExecuteNonQuery();
                    }
                }

                tran.Complete();
            }
        }

        private static string GetConnectionString(string name)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = ".\\SQL2014";
            builder.InitialCatalog = "AcmeTransactions";
            builder.IntegratedSecurity = true;
            builder.MaxPoolSize = 200;
            builder.ConnectTimeout = 120;
            builder.ApplicationName = name;

            return builder.ToString();
        }
    }
}
</code>```

Database

NOTE: I've manually added a row in the table for the GUID specified above in code.  I've also added a wait delay in the update stored procedure to view the isolation level in the sessions.

Create Table

```<code>CREATE TABLE [dbo].[SimpleTable](
    [Guid] [uniqueidentifier] NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_SimpleTable] PRIMARY KEY CLUSTERED
(
    [Guid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

Stored Procedure to read

```<code>CREATE PROCEDURE [dbo].[usp_GetAllSimpleTable]
AS
BEGIN
    SELECT [Guid]
          ,[Name]
      FROM [dbo].[SimpleTable]

END
</code>```

Stored Procedure to update

```<code>create PROCEDURE [dbo].[usp_UpdateSimpleTable]
(
    @Guid UNIQUEIDENTIFIER,
    @Name NVARCHAR(50)
)
AS
BEGIN
    UPDATE [dbo].[SimpleTable]
       SET [Name] = @Name
     WHERE [Guid] = @Guid

     waitfor delay '00:00:40'
END
</code>```

Diagnosis

I am using some SQL to list the sessions which includes the isolation level and the SQL being executed.  This I believe is correct.  I have also tried returning an explicit isolation level check in the stored procedure itself which returns READ COMMITTED.

```<code>SELECT
          d.name
        , s.session_id
        , CASE
              WHEN s.transaction_isolation_level = 1
                 THEN 'READ UNCOMMITTED'
              WHEN s.transaction_isolation_level = 2
                   AND is_read_committed_snapshot_on = 1
                 THEN 'READ COMMITTED SNAPSHOT'
              WHEN s.transaction_isolation_level = 2
                   AND is_read_committed_snapshot_on = 0 THEN 'READ COMMITTED'
              WHEN s.transaction_isolation_level = 3
                 THEN 'REPEATABLE READ'
              WHEN s.transaction_isolation_level = 4
                 THEN 'SERIALIZABLE'
              WHEN s.transaction_isolation_level = 5
                 THEN 'SNAPSHOT'
              ELSE NULL
           END
        , sqltext.TEXT

FROM   sys.dm_exec_sessions AS s
CROSS JOIN sys.databases AS d

join sys.dm_exec_requests er on s.session_id = er.session_id
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS sqltext

where d.name ='AcmeTransactions'
and s.program_name not in ('Microsoft SQL Server Management Studio - Query' , 'Microsoft SQL Server Management Studio')
</code>```

So when the above is executed whilst the delay is in progress, I see the following:

Further Investigation

If the connectionForRead using code block is moved outside of the Transaction, then I see the following session isolation information from SSMS:

This is how I would perceive the unmodified code to be.

Questions

Is my diagnosis correct?  The both SQL connections are running as READ COMMITTED?

Is this the best way to determine the transaction level of running queries?

答:
You will see this behaviour if you are running an early version of SQL Server 2014.  Easiest fix is to apply SP2 (or greater)

See https://support.microsoft.com/en-us/help/3025845/fix-the-transaction-isolation-level-is-reset-incorrectly-when-the-sql for details.

Body:
I've put together a sample application to mimic some of our main application code functionality.  Whilst working on this, I've been thrown a bit of a curve ball into my understanding of TransactionScope and SqlConnection.

The problem I see is explicitly "see" an IsolationLevel of READ COMMITTED where I would expect SERIALIZABLE.  Unless my methods are diagnosis are flawed.

Currently my database has Read Snapshot enabled so the screenshots show the READ COMMITTED SNAPSHOT.  When this is not enabled, then the screenshots will show READ COMMITTED.

Code

The code is running locally on my machine connecting to a local instance of SQL Server 2014.  This is the minimal code required.

So to replicate this scenario from a Console application:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
using IsolationLevel = System.Transactions.IsolationLevel;

namespace IsolationLevelConsoleProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var tran = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions
            {
                IsolationLevel = IsolationLevel.Serializable,
                Timeout = TimeSpan.FromMinutes(3)
            }))
            {
                using (var connectionForRead = new SqlConnection(GetConnectionString("For Read")))
                {
                    connectionForRead.Open();

                    using (var commandRead = new SqlCommand("usp_GetAllSimpleTable", connectionForRead))
                    {
                        commandRead.CommandType = CommandType.StoredProcedure;
                        commandRead.CommandTimeout = 120;

                        DataSet dataSet = new DataSet();
                        SqlDataAdapter adapter = new SqlDataAdapter
                        {
                            SelectCommand = commandRead
                        };

                        adapter.Fill(dataSet);
                    }
                }

                using (var connectionForUpdate = new SqlConnection(GetConnectionString("For Update")))
                {
                    connectionForUpdate.Open();

                    using (var commandUpdate = new SqlCommand("usp_UpdateSimpleTable", connectionForUpdate))
                    {
                        commandUpdate.CommandTimeout = 120;
                        commandUpdate.CommandType = CommandType.StoredProcedure;
                        commandUpdate.Parameters.AddWithValue("@Guid", Guid.Parse("{74B3155E-138E-4881-BEE2-67FD141E29DA}"));
                        commandUpdate.Parameters.AddWithValue("@Name", $"Name {DateTime.UtcNow}");
                        commandUpdate.ExecuteNonQuery();
                    }
                }

                tran.Complete();
            }
        }

        private static string GetConnectionString(string name)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = ".\\SQL2014";
            builder.InitialCatalog = "AcmeTransactions";
            builder.IntegratedSecurity = true;
            builder.MaxPoolSize = 200;
            builder.ConnectTimeout = 120;
            builder.ApplicationName = name;

            return builder.ToString();
        }
    }
}

Database

NOTE: I've manually added a row in the table for the GUID specified above in code.  I've also added a wait delay in the update stored procedure to view the isolation level in the sessions.

Create Table

CREATE TABLE [dbo].[SimpleTable](
    [Guid] [uniqueidentifier] NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_SimpleTable] PRIMARY KEY CLUSTERED
(
    [Guid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Stored Procedure to read

CREATE PROCEDURE [dbo].[usp_GetAllSimpleTable]
AS
BEGIN
    SELECT [Guid]
          ,[Name]
      FROM [dbo].[SimpleTable]

END

Stored Procedure to update

create PROCEDURE [dbo].[usp_UpdateSimpleTable]
(
    @Guid UNIQUEIDENTIFIER,
    @Name NVARCHAR(50)
)
AS
BEGIN
    UPDATE [dbo].[SimpleTable]
       SET [Name] = @Name
     WHERE [Guid] = @Guid

     waitfor delay '00:00:40'
END

Diagnosis

I am using some SQL to list the sessions which includes the isolation level and the SQL being executed.  This I believe is correct.  I have also tried returning an explicit isolation level check in the stored procedure itself which returns READ COMMITTED.

SELECT
          d.name
        , s.session_id
        , CASE
              WHEN s.transaction_isolation_level = 1
                 THEN 'READ UNCOMMITTED'
              WHEN s.transaction_isolation_level = 2
                   AND is_read_committed_snapshot_on = 1
                 THEN 'READ COMMITTED SNAPSHOT'
              WHEN s.transaction_isolation_level = 2
                   AND is_read_committed_snapshot_on = 0 THEN 'READ COMMITTED'
              WHEN s.transaction_isolation_level = 3
                 THEN 'REPEATABLE READ'
              WHEN s.transaction_isolation_level = 4
                 THEN 'SERIALIZABLE'
              WHEN s.transaction_isolation_level = 5
                 THEN 'SNAPSHOT'
              ELSE NULL
           END
        , sqltext.TEXT

FROM   sys.dm_exec_sessions AS s
CROSS JOIN sys.databases AS d

join sys.dm_exec_requests er on s.session_id = er.session_id
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS sqltext

where d.name ='AcmeTransactions'
and s.program_name not in ('Microsoft SQL Server Management Studio - Query' , 'Microsoft SQL Server Management Studio')

So when the above is executed whilst the delay is in progress, I see the following:

Further Investigation

If the connectionForRead using code block is moved outside of the Transaction, then I see the following session isolation information from SSMS:

This is how I would perceive the unmodified code to be.

Questions

Is my diagnosis correct?  The both SQL connections are running as READ COMMITTED?

Is this the best way to determine the transaction level of running queries?


问:
Aggregation in Cassandra across partitions
I have a Data model like below,

```<code>CREATE TABLE appstat.nodedata (
    nodeip text,
    timestamp timestamp,
    flashmode text,
    physicalusage int,
    readbw int,
    readiops int,
    totalcapacity int,
    writebw int,
    writeiops int,
    writelatency int,
    PRIMARY KEY (nodeip, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)
</code>```

where, nodeip - primary key and timestamp - clustering key (Sorted by descinding oder to get the latest),

Sample data in this table,

```<code>SELECT * from nodedata WHERE nodeip = '172.30.56.60' LIMIT 2;

 nodeip       | timestamp                       | flashmode | physicalusage | readbw | readiops | totalcapacity | writebw | writeiops | writelatency
--------------+---------------------------------+-----------+---------------+--------+----------+---------------+---------+-----------+--------------
 172.30.56.60 | 2017-12-08 06:13:07.161000+0000 |       yes |            34 |     57 |       19 |            27 |       8 |        89 |           57
 172.30.56.60 | 2017-12-08 06:12:07.161000+0000 |       yes |            70 |      6 |       43 |            88 |      79 |        83 |           89
</code>```

This is properly available and whenever I need to get the statistics I am able to get the data using the partition key like below,

```<code>SELECT nodeip,readbw,timestamp FROM nodedata WHERE nodeip = '172.30.56.60' AND timestamp < 1512652272989 AND timestamp > 1512537899000;
</code>```

Also successfully aggregate the data like below,

```<code>SELECT sum(readbw) FROM nodedata WHERE nodeip = '172.30.56.60' AND timestamp < 1512652272989 AND timestamp > 1512537899000;
</code>```

Now comes the next use case, Where I need to get the cluster data (All the data's of the four nodes),

Like below,

```<code>SELECT nodeip,readbw,timestamp FROM nodedata WHERE nodeip IN ('172.30.56.60','172.30.56.61','172.30.56.62','172.30.56.63') AND timestamp < 1512652272989 AND timestamp > 1512537899000;
</code>```

But It clearly mentioned in number of sites that, 'IN query' has lots of performance hiccups, So what is your suggestion in this Data Model of 'nodedata' table mentioned above? (NOTE: Doing Multiple queries in different partitions are okay which I feel like a last option)

Do you have a better approach (or) re-designing this data model in a better way (or) Any better solution to retrieve the data from multiple partitions?

Any help would be really appreciable.

Thanks,

Harry

答:
Yes, the use of IN on the partition key is discouraged as it put more load on coordinating node, especially if many partitions will be specified in IN clause.  Multiple separate requests done async, for example, could even be more performant, and make less load on coordinating nodes.

Also, you need into account the size of your partitions - from quick look to schema, I see that every partition will grow to ~55Mb in one year if you're doing sampling every minute. Having too wide partitions could also lead to some performance problems (although not always, depends on the use case).  Maybe you'll need to change partition key to include year, or year+month to make smaller partitions. But in this case, some additional logic should be added to your code when you retrieve data that span several years/months.

P.S. Maybe this is not a fully answering to your question, but commentary field is too small for it :-)

Body:
I have a Data model like below,

CREATE TABLE appstat.nodedata (
    nodeip text,
    timestamp timestamp,
    flashmode text,
    physicalusage int,
    readbw int,
    readiops int,
    totalcapacity int,
    writebw int,
    writeiops int,
    writelatency int,
    PRIMARY KEY (nodeip, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)

where, nodeip - primary key and timestamp - clustering key (Sorted by descinding oder to get the latest),

Sample data in this table,

SELECT * from nodedata WHERE nodeip = '172.30.56.60' LIMIT 2;

 nodeip       | timestamp                       | flashmode | physicalusage | readbw | readiops | totalcapacity | writebw | writeiops | writelatency
--------------+---------------------------------+-----------+---------------+--------+----------+---------------+---------+-----------+--------------
 172.30.56.60 | 2017-12-08 06:13:07.161000+0000 |       yes |            34 |     57 |       19 |            27 |       8 |        89 |           57
 172.30.56.60 | 2017-12-08 06:12:07.161000+0000 |       yes |            70 |      6 |       43 |            88 |      79 |        83 |           89

This is properly available and whenever I need to get the statistics I am able to get the data using the partition key like below,

SELECT nodeip,readbw,timestamp FROM nodedata WHERE nodeip = '172.30.56.60' AND timestamp < 1512652272989 AND timestamp > 1512537899000;

Also successfully aggregate the data like below,

SELECT sum(readbw) FROM nodedata WHERE nodeip = '172.30.56.60' AND timestamp < 1512652272989 AND timestamp > 1512537899000;

Now comes the next use case, Where I need to get the cluster data (All the data's of the four nodes),

Like below,

SELECT nodeip,readbw,timestamp FROM nodedata WHERE nodeip IN ('172.30.56.60','172.30.56.61','172.30.56.62','172.30.56.63') AND timestamp < 1512652272989 AND timestamp > 1512537899000;

But It clearly mentioned in number of sites that, 'IN query' has lots of performance hiccups, So what is your suggestion in this Data Model of 'nodedata' table mentioned above? (NOTE: Doing Multiple queries in different partitions are okay which I feel like a last option)

Do you have a better approach (or) re-designing this data model in a better way (or) Any better solution to retrieve the data from multiple partitions?

Any help would be really appreciable.

Thanks,

Harry


问:
convert array of array of objects into single array of objects in lodash
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

```<code>const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];
</code>```

I wanted as below intended result;

```<code>[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];
</code>```

I have tried reduce function to generate such intended result as below:

```<code>let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);
</code>```

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks

答:
Why dont you just use lodash flatten
https://lodash.com/docs/4.17.4#flatten</p>

Body:
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];

I wanted as below intended result;

[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];

I have tried reduce function to generate such intended result as below:

let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks


问:
Node.js: curl: (52) Empty reply from server with space in request not encoded
```<code>var http = require('http');

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
</code>```

I executed following curl commands:

```<code>curl "http://127.0.0.1:8000/"
Hello World

// space is not encoded
curl "http://127.0.0.1:8000/x y"
curl: (52) Empty reply from server

curl "http://127.0.0.1:8000/x"
Hello World

// space is encoded
curl "http://127.0.0.1:8000/x%20y"
Hello World
</code>```

Can you please explain the why I get curl 52???

In this case, I want to send 500 back. Can I do that?

答:
I'm having this question in mind as well.
I guess curl expects already-encoded url if quoted by double quotes. If it finds whitespace in url, it will consider it an invalid url.

And this is quite different from wget command. If you run this:

```<code>wget "http://127.0.0.1:8000/x y"
</code>```

actually wget encodes the url for you and the request actually will be sent as:

```<code>http://127.0.0.1:8000/x%20y
</code>```

These kind of facts really tease our brains.

Body:
var http = require('http');

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");

I executed following curl commands:

curl "http://127.0.0.1:8000/"
Hello World

// space is not encoded
curl "http://127.0.0.1:8000/x y"
curl: (52) Empty reply from server

curl "http://127.0.0.1:8000/x"
Hello World

// space is encoded
curl "http://127.0.0.1:8000/x%20y"
Hello World

Can you please explain the why I get curl 52???

In this case, I want to send 500 back. Can I do that?

Body:
I'm having this question in mind as well.
I guess curl expects already-encoded url if quoted by double quotes. If it finds whitespace in url, it will consider it an invalid url.

And this is quite different from wget command. If you run this:

wget "http://127.0.0.1:8000/x y"

actually wget encodes the url for you and the request actually will be sent as:

http://127.0.0.1:8000/x%20y

These kind of facts really tease our brains.


问:
How to delete json files in a folder using php
I need to delete only json files which existing in a particular folder using php. am trying this code

```<code>$path = "uploads/File Name/";
$files = scandir($path);
foreach ($files as $csv_file) {
  $filepath = str_replace(" ", "\ ", $csv_file);
  echo $filepath . '<br/>';
  unlink($csv_file);
}
</code>```

but when am using this its deleting all the file. I need to delete only json files

答:
```<code>$path = "uploads/File Name/";
$files = glob("$path/*.json");
foreach ($files as $csv_file) {
$filepath = str_replace(" ", "\ ", $csv_file);
echo $filepath . '<br/>';
unlink($csv_file);
</code>```

}

You can try this code.

Body:
I need to delete only json files which existing in a particular folder using php. am trying this code

$path = "uploads/File Name/";
$files = scandir($path);
foreach ($files as $csv_file) {
  $filepath = str_replace(" ", "\ ", $csv_file);
  echo $filepath . '
';
  unlink($csv_file);
}

but when am using this its deleting all the file. I need to delete only json files

Body:
$path = "uploads/File Name/";
$files = glob("$path/*.json");
foreach ($files as $csv_file) {
$filepath = str_replace(" ", "\ ", $csv_file);
echo $filepath . '<br/>';
unlink($csv_file);

}

You can try this code.


问:
Why do + and ~ affect Perl 6 junctions differently?
Add one to a junction of Ints:

```<code>put any( 1, 3, 7 ) + 1;
</code>```

Now you have a junction of those Ints increased by one:

```<code>any(2, 4, 8)
</code>```

So, 2 == any(2, 4, 8) is true.

Make a junction of strings and append to those strings:

```<code>put any( <h H> ) ~ 'amadryas';
</code>```

You get a different result that doesn't equal 'hamadryas' or 'Hamadryas':

```<code>any("h", "H")amadryas
</code>```

I expected something like:

```<code>any( 'hamadryas', 'Hamadryas' );
</code>```

What's the difference in these operations that gives them different behavior even though they should be similar?

答:
on the High Sierra 10.13, put fails with:

```<code>put any( 1, 3, 7 ) + 1
</code>```

This type cannot unbox to a native string: P6opaque, Junction
  in block  at  line 1

```<code>perl6 -v
</code>```

This is Rakudo Star version 2017.10 built on MoarVM version 2017.10
implementing Perl 6.c.

Body:
Add one to a junction of Ints:

put any( 1, 3, 7 ) + 1;

Now you have a junction of those Ints increased by one:

any(2, 4, 8)

So, 2 == any(2, 4, 8) is true.

Make a junction of strings and append to those strings:

put any( <h H> ) ~ 'amadryas';

You get a different result that doesn't equal 'hamadryas' or 'Hamadryas':

any("h", "H")amadryas

I expected something like:

any( 'hamadryas', 'Hamadryas' );

What's the difference in these operations that gives them different behavior even though they should be similar?

Body:
on the High Sierra 10.13, put fails with:

put any( 1, 3, 7 ) + 1

This type cannot unbox to a native string: P6opaque, Junction
  in block  at  line 1

perl6 -v

This is Rakudo Star version 2017.10 built on MoarVM version 2017.10
implementing Perl 6.c.