问:
In cocos2d how do you implement a touch hash code and reference it later?
How do you implement a touch hash code and reference it later?  I have read about a "hash" code, but I don't understand how to use it.  I want to know when two of my Sprites are touched at the same time, like as if pressing a chord on two keys of a piano.

Here is an example of what I have for my ccTouchesBegan:

```<code>- (void) ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

  NSSet *allTouches = [event allTouches];
  int validTouchCount = 0;
  for (UITouch* touch in allTouches) {

    BOOL touchIsValid = FALSE;

    CGPoint location = [touch locationInView: [touch view]];
    CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

    if (CGRectContainsPoint(_fourButtonsRect, convertedLocation)) {
        NSLog(@"Touch is within four buttons");
        touchIsValid = TRUE;
    }

    _playerDidAction = 0;
    NSLog(@"before the loop");
    if (touchIsValid) {

        validTouchCount++;
        NSLog(@"Within ValidTouches loop");
        CGPoint validLocation = [touch locationInView: [touch view]];
        CGPoint convertedValidLocation = [[CCDirector sharedDirector] convertToGL:validLocation];

        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedValidLocation)) {
            _redButtonStatus = TRUE;
            [_redButtonSprite setTexture:_redButtonLit];
            if (validTouchCount == 1) {
                _playerDidAction = 1;
            }
        }
            else if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedValidLocation)) {
                _blueButtonStatus = TRUE;
                [_blueButtonSprite setTexture:_blueButtonLit];
                if (validTouchCount == 1) {
                    _playerDidAction = 2;
                }
            }
                else if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedValidLocation)) {
                    _greenButtonStatus = TRUE;
                    [_greenButtonSprite setTexture:_greenButtonLit];
                    if (validTouchCount == 1) {
                        _playerDidAction = 3;
                    }
                }
                    else if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedValidLocation)) {
                        _yellowButtonStatus = TRUE;
                        [_yellowButtonSprite setTexture:_yellowButtonLit];
                        if (validTouchCount == 1) {
                            _playerDidAction = 4;
                        }
                    }

        if (validTouchCount > 1) {

            if (_redButtonStatus && _blueButtonStatus) {
                _comboRB = TRUE;
                _playerDidAction = 5;
            }
                else if (_redButtonStatus && _greenButtonStatus) {
                    _comboRG = TRUE;
                    _playerDidAction = 6;
                }
                    else if (_redButtonStatus && _yellowButtonStatus) {
                        _comboRY = TRUE;
                        _playerDidAction = 7;
                    }
                        else if (_blueButtonStatus && _greenButtonStatus) {
                            _comboBG = TRUE;
                            _playerDidAction = 8;
                        }
                            else if (_blueButtonStatus && _yellowButtonStatus) {
                                _comboBY = TRUE;
                                _playerDidAction = 9;
                            }
                                else if (_greenButtonStatus && _yellowButtonStatus) {
                                    _comboGY = TRUE;
                                    _playerDidAction = 10;
                                }

        }
    }
  }
}
</code>```

And here is the beginning of my ccTouchesEnded:

```<code>- (void)ccTouchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {

    for (UITouch *touch in touches) {

        CGPoint location = [touch locationInView: [touch view]];
        CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedLocation)) {
            _redButtonStatus = FALSE;
            [_redButtonSprite setTexture:_redButtonNormal];
        }
        if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedLocation)) {
            _blueButtonStatus = FALSE;
            [_blueButtonSprite setTexture:_blueButtonNormal];
        }
        if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedLocation)) {
            _greenButtonStatus = FALSE;
            [_greenButtonSprite setTexture:_greenButtonNormal];
        }
        if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedLocation)) {
            _yellowButtonStatus = FALSE;
            [_yellowButtonSprite setTexture:_yellowButtonNormal];
        }

    }
}
</code>```

Could you maybe give me an example of how you would capture touches that began on a sprite and ended on a sprite? I have been struggling and can't get the hash code to work - just not understanding how the hash code can be used to reference a touch later. I guess what I'm trying to make would be called a hash tracker?

I am sure there is a much less convoluted way to do it using the hash codes and less state variables. I haven't fleshed out the ccTouchesEnded method with the other state variable effects because I was hoping to find a simpler way (I know I still need to make the ccTouchesMoved and Canceled methods too).

Any advise would be very appreciated!

答:
Here is how I implemented this [I DID NOT USE A HASH CODE because I could not get it to work] in case anyone else is trying to do this (I have limited it to 2-button combos but I could easily extend the logic to 3 & 4-button combos as well).  I chose to handle each touch individually using the ccTouchBegan/Ended/Moved instead of using the ccTouchesBegan/Ended/Moved because I just couldn't get it to work with the hash code.  Any alternative ideas would be welcome.

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:
How do you implement a touch hash code and reference it later?  I have read about a "hash" code, but I don't understand how to use it.  I want to know when two of my Sprites are touched at the same time, like as if pressing a chord on two keys of a piano.

Here is an example of what I have for my ccTouchesBegan:

- (void) ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

  NSSet *allTouches = [event allTouches];
  int validTouchCount = 0;
  for (UITouch* touch in allTouches) {

    BOOL touchIsValid = FALSE;

    CGPoint location = [touch locationInView: [touch view]];
    CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

    if (CGRectContainsPoint(_fourButtonsRect, convertedLocation)) {
        NSLog(@"Touch is within four buttons");
        touchIsValid = TRUE;
    }

    _playerDidAction = 0;
    NSLog(@"before the loop");
    if (touchIsValid) {

        validTouchCount++;
        NSLog(@"Within ValidTouches loop");
        CGPoint validLocation = [touch locationInView: [touch view]];
        CGPoint convertedValidLocation = [[CCDirector sharedDirector] convertToGL:validLocation];

        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedValidLocation)) {
            _redButtonStatus = TRUE;
            [_redButtonSprite setTexture:_redButtonLit];
            if (validTouchCount == 1) {
                _playerDidAction = 1;
            }
        }
            else if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedValidLocation)) {
                _blueButtonStatus = TRUE;
                [_blueButtonSprite setTexture:_blueButtonLit];
                if (validTouchCount == 1) {
                    _playerDidAction = 2;
                }
            }
                else if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedValidLocation)) {
                    _greenButtonStatus = TRUE;
                    [_greenButtonSprite setTexture:_greenButtonLit];
                    if (validTouchCount == 1) {
                        _playerDidAction = 3;
                    }
                }
                    else if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedValidLocation)) {
                        _yellowButtonStatus = TRUE;
                        [_yellowButtonSprite setTexture:_yellowButtonLit];
                        if (validTouchCount == 1) {
                            _playerDidAction = 4;
                        }
                    }

        if (validTouchCount > 1) {

            if (_redButtonStatus && _blueButtonStatus) {
                _comboRB = TRUE;
                _playerDidAction = 5;
            }
                else if (_redButtonStatus && _greenButtonStatus) {
                    _comboRG = TRUE;
                    _playerDidAction = 6;
                }
                    else if (_redButtonStatus && _yellowButtonStatus) {
                        _comboRY = TRUE;
                        _playerDidAction = 7;
                    }
                        else if (_blueButtonStatus && _greenButtonStatus) {
                            _comboBG = TRUE;
                            _playerDidAction = 8;
                        }
                            else if (_blueButtonStatus && _yellowButtonStatus) {
                                _comboBY = TRUE;
                                _playerDidAction = 9;
                            }
                                else if (_greenButtonStatus && _yellowButtonStatus) {
                                    _comboGY = TRUE;
                                    _playerDidAction = 10;
                                }

        }
    }
  }
}

And here is the beginning of my ccTouchesEnded:

- (void)ccTouchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {

    for (UITouch *touch in touches) {

        CGPoint location = [touch locationInView: [touch view]];
        CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedLocation)) {
            _redButtonStatus = FALSE;
            [_redButtonSprite setTexture:_redButtonNormal];
        }
        if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedLocation)) {
            _blueButtonStatus = FALSE;
            [_blueButtonSprite setTexture:_blueButtonNormal];
        }
        if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedLocation)) {
            _greenButtonStatus = FALSE;
            [_greenButtonSprite setTexture:_greenButtonNormal];
        }
        if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedLocation)) {
            _yellowButtonStatus = FALSE;
            [_yellowButtonSprite setTexture:_yellowButtonNormal];
        }

    }
}

Could you maybe give me an example of how you would capture touches that began on a sprite and ended on a sprite? I have been struggling and can't get the hash code to work - just not understanding how the hash code can be used to reference a touch later. I guess what I'm trying to make would be called a hash tracker?

I am sure there is a much less convoluted way to do it using the hash codes and less state variables. I haven't fleshed out the ccTouchesEnded method with the other state variable effects because I was hoping to find a simpler way (I know I still need to make the ccTouchesMoved and Canceled methods too).

Any advise would be very appreciated!

Body:
Here is how I implemented this [I DID NOT USE A HASH CODE because I could not get it to work] in case anyone else is trying to do this (I have limited it to 2-button combos but I could easily extend the logic to 3 & 4-button combos as well).  I chose to handle each touch individually using the ccTouchBegan/Ended/Moved instead of using the ccTouchesBegan/Ended/Moved because I just couldn't get it to work with the hash code.  Any alternative ideas would be welcome.

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

问:
Query to get username from child table with specific condition
I have a table Admin and a child table AdminOfArea. I want to get the user name from Table2 where username only have one Region not multiple which is Liverpool. in this case only A and B are according to this scenario.

Table 1 looks like

```<code>|Username |  UserType  |
|  abc    |  Admin     |
|   A     |  Admin     |
|  xyz    |  Admin     |
|   B     |  Admin     |
</code>```

Table 2 looks like

```<code>|UserName  Region    |
| abc     Wales      |
| abc     Liverpool  |
| abc     Westsussex |
| A       Liverpool  |
| xyz     Wales      |
| xyz     Liverpool  |
| xyz     Westsussex |
| B       Liverpool  |
</code>```

答:
If you want to fetch the data only from the second table based on region='Liverpool' by excluding those username which have multiple region, you can go with following query.

```<code>SELECT username FROM adminofarea WHERE region='Liverpool' GROUP BY adminofarea.username HAVING COUNT(1) = 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table Admin and a child table AdminOfArea. I want to get the user name from Table2 where username only have one Region not multiple which is Liverpool. in this case only A and B are according to this scenario.

Table 1 looks like

|Username |  UserType  |
|  abc    |  Admin     |
|   A     |  Admin     |
|  xyz    |  Admin     |
|   B     |  Admin     |

Table 2 looks like

|UserName  Region    |
| abc     Wales      |
| abc     Liverpool  |
| abc     Westsussex |
| A       Liverpool  |
| xyz     Wales      |
| xyz     Liverpool  |
| xyz     Westsussex |
| B       Liverpool  |

Body:
If you want to fetch the data only from the second table based on region='Liverpool' by excluding those username which have multiple region, you can go with following query.

SELECT username FROM adminofarea WHERE region='Liverpool' GROUP BY adminofarea.username HAVING COUNT(1) = 1


问:
Can I define a common interface for two classes with same property name?
Let's say I have following class hierarchy:

```<code>class A { }
class B : A { }
class C : A { }
</code>```

And I have two container classes:

```<code>class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }
</code>```

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

```<code>void ProcessValue(IEnumerable<A> as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}
</code>```

答:
I'm not sure these generic answers would work for your serialization requirements.

What about some overloads?

```<code>void ExtractValue(BContainer container)
{
    ProcessValue(container.Value);
}

void ExtractValue(CContainer container)
{
    ProcessValue(container.Value);
}
</code>```

Body:
Let's say I have following class hierarchy:

class A { }
class B : A { }
class C : A { }

And I have two container classes:

class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

void ProcessValue(IEnumerable as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}

Body:
I'm not sure these generic answers would work for your serialization requirements.

What about some overloads?

void ExtractValue(BContainer container)
{
    ProcessValue(container.Value);
}

void ExtractValue(CContainer container)
{
    ProcessValue(container.Value);
}


问:
ngStyle with 'checked' state in ngFor loop
I have a list of checkboxes that are asign to different departments(every department has it's own color) when box is unchecked only a border is in the color of department when checked backgroud is changed to the asign color

box-shadow works how it should but can not make background to change (stayes blue-ish),
this is my code at the moment:

```<code>  <label class="custom-control custom-checkbox" *ngFor="let department of departments">
        <input type="checkbox" class="custom-control-input" [ngStyle]="{'background-color':checked===true? department.color:'white'}">
        <span class="custom-control-indicator" [ngStyle]="{'box-shadow': '0 0 1px 1px' + department.color}" >  </span>
        <span class="custom-control-description text-capitalize">{{department.id}}</span>
      </label>
</code>```

答:
It has nothing to do with angular.
You can't change the background color of checkboxes natively
you should use a custom class with pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons

You have an example here

Body:
I have a list of checkboxes that are asign to different departments(every department has it's own color) when box is unchecked only a border is in the color of department when checked backgroud is changed to the asign color

box-shadow works how it should but can not make background to change (stayes blue-ish),
this is my code at the moment:

        <input type="checkbox" class="custom-control-input" [ngStyle]="{'background-color':checked===true? department.color:'white'}">

        {{department.id}}


问:
How can I refer an object pragmatically in R
```<code>a_1 <- 1:100;
a_2 <- 10:1000;
a_3 <- 100:10000
</code>```

I want to Print each series in programmatic way using a for loop.

```<code>for (i in 1:3)
{
print(paste("a_", i, sep = "")
}
</code>```

Kindly Advise.

答:
```<code>print_val <- function(id)
{
  print(id)
  #eval.parent(substitute(as.name(paste("a_", id, sep = ""))))
  eval.parent(as.name(paste("a_", id, sep = "")))*2
  }
</code>```

I have used as.name to resolve the variable and eval.parent to get it from environment. Sorry for bothering you guys.

Body:
a_1 <- 1:100;
a_2 <- 10:1000;
a_3 <- 100:10000

I want to Print each series in programmatic way using a for loop.

for (i in 1:3)
{
print(paste("a_", i, sep = "")
}

Kindly Advise.

Body:
print_val <- function(id)
{
  print(id)
  #eval.parent(substitute(as.name(paste("a_", id, sep = ""))))
  eval.parent(as.name(paste("a_", id, sep = "")))*2
  }

I have used as.name to resolve the variable and eval.parent to get it from environment. Sorry for bothering you guys.


问:
Selecting First Tab - Laravel
i want to have my first tab selected when page loads or refreshes. In my code, the content of the first tab shows alright but the tab doesn't show it is selected although its content is showing.

Why is this happening please?

```<code><input type="hidden" name="currentTab" value="0"/>

<div class="row">
        <div class="col-md-9">

          <div  class="nav-tabs-custom"  id="tabs">

            <ul class="nav nav-tabs">
            @foreach($students as $student)

               <li ><a href="#tab_{{ $student->id }}" data-toggle="tab" >{!!$student->name!!}</a></li>
               @endforeach

            </ul>
            <div class="tab-content">
            @foreach($stduents as $key => $student)

            <div class="tab-pane" id="tab_{{ $student->id }}">
                 //content
             </div>
            @endforeach
              </div>

            </div>

          </div>

        </div>

<script>

$( document ).ready(function() {

    $("#tabs").tabs({active: document.tabTest.currentTab.value});

            $('#tabs a').click(function(e) {
                var curTab = $('.ui-tabs-active');
                curTabIndex = curTab.index();
                document.tabTest.currentTab.value = curTabIndex;
            });
})
</script>
</code>```

答:
I see that an active class is not being set on page load to the first nav
list element.

This should set the active class to first list element.

```<code>  @foreach($students as $key => $student)
     <li {{ $key == 0 ? 'class="active"' : '' }}><a href="#tab_{{ $student->id }}" data-toggle="tab" >
        {!!$student->name!!}</a></li>
  @endforeach
</code>```

Title: Selecting First Tab - Laravel

Body:
i want to have my first tab selected when page loads or refreshes. In my code, the content of the first tab shows alright but the tab doesn't show it is selected although its content is showing.

Why is this happening please?

<input type="hidden" name="currentTab" value="0"/>

            @foreach($students as $student)

id }}" data-toggle="tab" >{!!$student->name!!}

               @endforeach

            @foreach($stduents as $key => $student)

id }}">
                 //content

            @endforeach

Body:
I see that an active class is not being set on page load to the first nav
list element.

This should set the active class to first list element.

  @foreach($students as $key => $student)
     <li {{ $key == 0 ? 'class="active"' : '' }}><a href="#tab_{{ $student->id }}" data-toggle="tab" >
        {!!$student->name!!}</a></li>
  @endforeach


问:
username and password verification vb.net
My program below checks if the userName and the password is in the database( written in visual basic and uses Access database). The program works however, when I type in the userName or password in a different case it still works. For example, if my database has the userName as "john" and the password as "johnspassword", my program accepts the username as "JOHN" and password as "JOHNSPASSWORD".

how do i resolve this problem?

```<code>Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
    Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblUsers WHERE UserID = '" & txtUserName_Field.Text & "' AND userPassword = '" & txtUserPassword_Field.Text & "' ", con)
    con.Open()
    Dim sdr As OleDbDataReader = cmd.ExecuteReader()
    'If the record can be queried, it means passing verification, then open another form.
    Dim empty =
    Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
    If empty.Any Then
        MessageBox.Show(String.Format("Please fill in all the fields required"))
    Else
        If (sdr.Read() = True) Then
            MessageBox.Show("The is valid!")
            Form4.Show()
            Me.Hide()
        Else
            MessageBox.Show("Invalid name or password!")
        End If
    End If
    con.Close()
End Sub
</code>```

答:
If you use a hash of the password instead then you solve two problems you have:

You should not store passwords as plain text

A hash will make the password case-sensitive

The Rfc2898DeriveBytes Class is suitable for creating the hash; you'll need a randomly-generated salt stored in the database for each user too.

There are many sites, e.g., Salted Password Hashing - Doing it Right, with explanations of why salting and hashing are desirable.

You will still have to decide if you need the username to be case-sensitive.

EDIT

It appears that Access doesn't have an efficient (i.e. sargable) way to do a case-sensitive comparison, so you can simply get the username from the database and check it in your program, something like this:

```<code>Option Infer On
Option Strict On

Imports System.Data.OleDb
Imports System.Security.Cryptography

Public Class SomeClass

    'TODO: decide on the sizes for the salt and hash
    'TODO: create binary fields in the database of appropriate sizes
    'TODO: consider storing the number of iterations in the database
    Const SALTLENGTH As Integer = 8
    Const HASHLENGTH As Integer = 16
    Const PBKDF2ITERATIONS As Integer = 20000

    Friend Function PBKDF2Hash(password As String, salt As Byte(), iterations As Integer, hashSize As Integer) As Byte()
        Dim hasher As New Rfc2898DeriveBytes(password, salt, iterations)
        Return hasher.GetBytes(hashSize)

    End Function

    Function IsLoginValid(username As String, password As String) As Boolean

        Dim salt(SALTLENGTH - 1) As Byte
        Dim hashedPassword(HASHLENGTH - 1) As Byte
        Dim usernameIsValid = False

        Dim csb As New OleDbConnectionStringBuilder With {
            .Provider = "Microsoft.jet.oledb.4.0",
            .DataSource = "C:\Users\jacob\Desktop\MS Office\project.mdb"
        }

        Using conn As New OleDbConnection(csb.ConnectionString)
            'TODO: use the actual column names
            Using cmd As New OleDbCommand("SELECT UserID, salt, password FROM tblUsers WHERE UserID = ?", conn)
                'TODO: use type of column as specified in the database
                cmd.Parameters.Add(New OleDbParameter With {.OleDbType = OleDbType.VarWChar, .Value = username})
                conn.Open()
                Dim rdr = cmd.ExecuteReader()
                If rdr.HasRows Then
                    rdr.Read()
                    If String.Compare(rdr.GetString(0), username, StringComparison.Ordinal) = 0 Then
                        rdr.GetBytes(1, 0, salt, 0, SALTLENGTH)
                        rdr.GetBytes(2, 0, hashedPassword, 0, HASHLENGTH)
                        usernameIsValid = True
                    End If
                End If

                conn.Close()
            End Using
        End Using

        Dim expectedHash = PBKDF2Hash(password, salt, PBKDF2ITERATIONS, HASHLENGTH)

        If usernameIsValid AndAlso hashedPassword.SequenceEqual(expectedHash) Then
            Return True
        End If

        Return False

    End Function

    Private Sub bnLogin_Click(sender As Object, e As EventArgs) Handles bnLogin.Click
        Dim username = txtUserName_Field.Text
        Dim password = txtUserPassword_Field.Text

        If username.Length = 0 OrElse password.Length = 0 Then
            MessageBox.Show("Please fill in all the fields required.")
            Exit Sub
        End If

        If IsLoginValid(username, password) Then
            ' user has supplied valid credentials
        Else
            MessageBox.Show("Invalid username or password.")
        End If

    End Sub

End Class
</code>```

Of course, you still have to create the code to put the appropriate data in the database when the user is registered.

Body:
My program below checks if the userName and the password is in the database( written in visual basic and uses Access database). The program works however, when I type in the userName or password in a different case it still works. For example, if my database has the userName as "john" and the password as "johnspassword", my program accepts the username as "JOHN" and password as "JOHNSPASSWORD".

how do i resolve this problem?

Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
    Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblUsers WHERE UserID = '" & txtUserName_Field.Text & "' AND userPassword = '" & txtUserPassword_Field.Text & "' ", con)
    con.Open()
    Dim sdr As OleDbDataReader = cmd.ExecuteReader()
    'If the record can be queried, it means passing verification, then open another form.
    Dim empty =
    Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
    If empty.Any Then
        MessageBox.Show(String.Format("Please fill in all the fields required"))
    Else
        If (sdr.Read() = True) Then
            MessageBox.Show("The is valid!")
            Form4.Show()
            Me.Hide()
        Else
            MessageBox.Show("Invalid name or password!")
        End If
    End If
    con.Close()
End Sub

Body:
If you use a hash of the password instead then you solve two problems you have:

You should not store passwords as plain text

A hash will make the password case-sensitive

The Rfc2898DeriveBytes Class is suitable for creating the hash; you'll need a randomly-generated salt stored in the database for each user too.

There are many sites, e.g., Salted Password Hashing - Doing it Right, with explanations of why salting and hashing are desirable.

You will still have to decide if you need the username to be case-sensitive.

EDIT

It appears that Access doesn't have an efficient (i.e. sargable) way to do a case-sensitive comparison, so you can simply get the username from the database and check it in your program, something like this:

Option Infer On
Option Strict On

Imports System.Data.OleDb
Imports System.Security.Cryptography

Public Class SomeClass

    'TODO: decide on the sizes for the salt and hash
    'TODO: create binary fields in the database of appropriate sizes
    'TODO: consider storing the number of iterations in the database
    Const SALTLENGTH As Integer = 8
    Const HASHLENGTH As Integer = 16
    Const PBKDF2ITERATIONS As Integer = 20000

    Friend Function PBKDF2Hash(password As String, salt As Byte(), iterations As Integer, hashSize As Integer) As Byte()
        Dim hasher As New Rfc2898DeriveBytes(password, salt, iterations)
        Return hasher.GetBytes(hashSize)

    End Function

    Function IsLoginValid(username As String, password As String) As Boolean

        Dim salt(SALTLENGTH - 1) As Byte
        Dim hashedPassword(HASHLENGTH - 1) As Byte
        Dim usernameIsValid = False

        Dim csb As New OleDbConnectionStringBuilder With {
            .Provider = "Microsoft.jet.oledb.4.0",
            .DataSource = "C:\Users\jacob\Desktop\MS Office\project.mdb"
        }

        Using conn As New OleDbConnection(csb.ConnectionString)
            'TODO: use the actual column names
            Using cmd As New OleDbCommand("SELECT UserID, salt, password FROM tblUsers WHERE UserID = ?", conn)
                'TODO: use type of column as specified in the database
                cmd.Parameters.Add(New OleDbParameter With {.OleDbType = OleDbType.VarWChar, .Value = username})
                conn.Open()
                Dim rdr = cmd.ExecuteReader()
                If rdr.HasRows Then
                    rdr.Read()
                    If String.Compare(rdr.GetString(0), username, StringComparison.Ordinal) = 0 Then
                        rdr.GetBytes(1, 0, salt, 0, SALTLENGTH)
                        rdr.GetBytes(2, 0, hashedPassword, 0, HASHLENGTH)
                        usernameIsValid = True
                    End If
                End If

                conn.Close()
            End Using
        End Using

        Dim expectedHash = PBKDF2Hash(password, salt, PBKDF2ITERATIONS, HASHLENGTH)

        If usernameIsValid AndAlso hashedPassword.SequenceEqual(expectedHash) Then
            Return True
        End If

        Return False

    End Function

    Private Sub bnLogin_Click(sender As Object, e As EventArgs) Handles bnLogin.Click
        Dim username = txtUserName_Field.Text
        Dim password = txtUserPassword_Field.Text

        If username.Length = 0 OrElse password.Length = 0 Then
            MessageBox.Show("Please fill in all the fields required.")
            Exit Sub
        End If

        If IsLoginValid(username, password) Then
            ' user has supplied valid credentials
        Else
            MessageBox.Show("Invalid username or password.")
        End If

    End Sub

End Class

Of course, you still have to create the code to put the appropriate data in the database when the user is registered.


问:
Unable to manually set the intervals for Y axis
I have a HTML5 column chart in my jasper report. I need to configure the y axis and be able to set the intervals manually

I have used,

```<code><property name="net.sf.jasperreports.chart.range.axis.tick.count" value="false"/>
<property name="net.sf.jasperreports.chart.range.axis.tick.interval" value="2"/>
</code>```

It has no effect on the chart

The source code is as follows

```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="customizechart" pageWidth="1000" pageHeight="1000" columnWidth="960" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="23a00417-b19d-4f98-aa59-dc6422d51386">
    <property name="net.sf.jasperreports.chart.range.axis.tick.count" value="false"/>
    <property name="net.sf.jasperreports.chart.range.axis.tick.interval" value="2"/>
    <queryString>
        <![CDATA[Select * from some_table]]>
    </queryString>
    <field name="Name" class="java.lang.String"/>
    <field name="AppliedQuantity" class="java.lang.Float"/>
    <summary>
        <band height="959" splitType="Stretch">
            <componentElement>
                <reportElement x="0" y="0" width="960" height="500" uuid="774dd6b9-b5b9-4d3c-b518-6f7c7ca40043"/>
                <hc:chart xmlns:hc="http://jaspersoft.com/highcharts" xsi:schemaLocation="http://jaspersoft.com/highcharts http://jaspersoft.com/schema/highcharts.xsd" type="Column">
                    <hc:chartSetting name="default">
                        <hc:chartProperty name="chart.zoomType">
                            <hc:propertyExpression><![CDATA["xy"]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.enabled">
                            <hc:propertyExpression><![CDATA[false]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.href">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="title.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="yAxis.title.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                    </hc:chartSetting>
                    <multiAxisData>
                        <multiAxisDataset/>
                        <dataAxis axis="Rows">
                            <axisLevel name="Name">
                                <labelExpression><![CDATA["Level Label expression"]]></labelExpression>
                                <axisLevelBucket class="java.lang.String">
                                    <bucketExpression><![CDATA[$F{Name}]]></bucketExpression>
                                </axisLevelBucket>
                            </axisLevel>
                        </dataAxis>
                        <dataAxis axis="Columns"/>
                        <multiAxisMeasure name="Measure1" class="java.lang.Integer" calculation="Nothing">
                            <labelExpression><![CDATA["f"]]></labelExpression>
                            <valueExpression><![CDATA[$F{AppliedQuantity}]]></valueExpression>
                        </multiAxisMeasure>
                    </multiAxisData>
                    <hc:series name="Measure1"/>
                </hc:chart>
            </componentElement>
        </band>
    </summary>
</jasperReport>
</code>```

Any ideas on this?

答:
net.sf.jasperreports.chart.* properties apply to the charts built into the community/open source JasperReports library (which are based on JFreeChart).

For HTML5 charts - part of JasperReports Professional - what you have to do is set the yAxis.tickInterval property in the chart:

```<code><hc:chartProperty name="yAxis.tickInterval">
    <hc:propertyExpression><![CDATA[500]]></hc:propertyExpression>
</hc:chartProperty>
</code>```

Body:
I have a HTML5 column chart in my jasper report. I need to configure the y axis and be able to set the intervals manually

I have used,

<property name="net.sf.jasperreports.chart.range.axis.tick.count" value="false"/>
<property name="net.sf.jasperreports.chart.range.axis.tick.interval" value="2"/>

It has no effect on the chart

The source code is as follows

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="customizechart" pageWidth="1000" pageHeight="1000" columnWidth="960" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="23a00417-b19d-4f98-aa59-dc6422d51386">
    <property name="net.sf.jasperreports.chart.range.axis.tick.count" value="false"/>
    <property name="net.sf.jasperreports.chart.range.axis.tick.interval" value="2"/>
    <queryString>
        <![CDATA[Select * from some_table]]>
    </queryString>
    <field name="Name" class="java.lang.String"/>
    <field name="AppliedQuantity" class="java.lang.Float"/>

        <band height="959" splitType="Stretch">
            <componentElement>
                <reportElement x="0" y="0" width="960" height="500" uuid="774dd6b9-b5b9-4d3c-b518-6f7c7ca40043"/>
                <hc:chart xmlns:hc="http://jaspersoft.com/highcharts" xsi:schemaLocation="http://jaspersoft.com/highcharts http://jaspersoft.com/schema/highcharts.xsd" type="Column">
                    <hc:chartSetting name="default">
                        <hc:chartProperty name="chart.zoomType">
                            <hc:propertyExpression><![CDATA["xy"]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.enabled">
                            <hc:propertyExpression><![CDATA[false]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.href">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="title.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="yAxis.title.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                    </hc:chartSetting>
                    <multiAxisData>
                        <multiAxisDataset/>
                        <dataAxis axis="Rows">
                            <axisLevel name="Name">
                                <labelExpression><![CDATA["Level Label expression"]]></labelExpression>
                                <axisLevelBucket class="java.lang.String">
                                    <bucketExpression><![CDATA[$F{Name}]]></bucketExpression>
                                </axisLevelBucket>
                            </axisLevel>
                        </dataAxis>
                        <dataAxis axis="Columns"/>
                        <multiAxisMeasure name="Measure1" class="java.lang.Integer" calculation="Nothing">
                            <labelExpression><![CDATA["f"]]></labelExpression>
                            <valueExpression><![CDATA[$F{AppliedQuantity}]]></valueExpression>
                        </multiAxisMeasure>
                    </multiAxisData>
                    <hc:series name="Measure1"/>
                </hc:chart>
            </componentElement>
        </band>

</jasperReport>

Any ideas on this?

Body:
net.sf.jasperreports.chart.* properties apply to the charts built into the community/open source JasperReports library (which are based on JFreeChart).

For HTML5 charts - part of JasperReports Professional - what you have to do is set the yAxis.tickInterval property in the chart:

<hc:chartProperty name="yAxis.tickInterval">
    <hc:propertyExpression><![CDATA[500]]></hc:propertyExpression>
</hc:chartProperty>


问:
How to Deserialize this JSON data in C# (asp.net)
How to Deserialize this Json Data in asp.net C#.

```<code>{"USD_PHP":{"2016-12-31":49.560001},"PHP_USD":{"2016-12-31":0.020178}}
</code>```

Here the USD_PHP and PHP_USD is going to be always unique, the Date 2016-12-31 is also unique for every date value. All i want to get the Currency Conversion Rate (49.560001, and 0.020178) in my application. How can i Build the program which is having no Common Key Field?

Source

答:
```<code>var req = new RestRequest("api url"); // RestSharp.dll
var client = new RestClient("host url");
var response = client.ExecuteTaskAsync(req).Result.Content;
var json =((dynamic)JsonConvert.DeserializeObject(response))
 //Newtonsoft.Json.dll
var dic = new Dictionary<string, List<Tuple<string, string>>>();
foreach (var item in json)
{
  var items = new List<Tuple<string, string>>();
  foreach (var value in item.Value)
  {
       var newItem = new Tuple<string, string>(value.Name, value.Value.ToString());
       items.Add(newItem);
  }
  if (items.Any())
  {
       dic.Add(item.Name, items);
  }
}
</code>```

I hope this example will help you.

Body:
How to Deserialize this Json Data in asp.net C#.

{"USD_PHP":{"2016-12-31":49.560001},"PHP_USD":{"2016-12-31":0.020178}}

Here the USD_PHP and PHP_USD is going to be always unique, the Date 2016-12-31 is also unique for every date value. All i want to get the Currency Conversion Rate (49.560001, and 0.020178) in my application. How can i Build the program which is having no Common Key Field?

Source

Body:
var req = new RestRequest("api url"); // RestSharp.dll
var client = new RestClient("host url");
var response = client.ExecuteTaskAsync(req).Result.Content;
var json =((dynamic)JsonConvert.DeserializeObject(response))
 //Newtonsoft.Json.dll
var dic = new Dictionary<string, List<Tuple<string, string>>>();
foreach (var item in json)
{
  var items = new List<Tuple<string, string>>();
  foreach (var value in item.Value)
  {
       var newItem = new Tuple<string, string>(value.Name, value.Value.ToString());
       items.Add(newItem);
  }
  if (items.Any())
  {
       dic.Add(item.Name, items);
  }
}

I hope this example will help you.


问:
Change default MSSQL datasource for connection string
When executing integration tests, I'm using a connection string to connect to the database. I know there is a default notation for connecting to the default server instance in a connection string:

data source=.;initial catalog=[database name];integrated security=SSPI;

Unfortunately the database is currently not installed on the default server and due to compatibility issues I am unable to change to the default server. Now for all my tests, I will have to assign the sever name like so:

data source=[My Server name] ;initial catalog=[database name];integrated security=SSPI;

Since the solution is shared, I can't check this configuration in, and I'll have to do a lot of manual maintenance for this.

Is there any way I can change the default SQL Server for my PC, so that I can use the connection string as shown in the first example?

EDIT:

I was able to successfully use the following connection string:

data source=.\SQLEXPRESS;initial catalog=[database name];integrated security=SSPI;

EDIT 2:

I was able to resolve my issue by this awnser

答:
you can try this :

```<code>  sp_dropserver 'your server name'>;
  GO
  sp_addserver '.', local;
  GO
</code>```

You can change your connection string to :

```<code>data source=.;initial catalog=[database name];integrated security=True;
</code>```

This will not disturb other developpers.

Body:
you can try this :

  sp_dropserver 'your server name'>;
  GO
  sp_addserver '.', local;
  GO

You can change your connection string to :

data source=.;initial catalog=[database name];integrated security=True;

This will not disturb other developpers.


问:
pull access denied for oracle/serverjre
I have been trying to build a docker image for oracle/weblogic 12.2.1.

I followed all the instructions carefully as given in the official repo.

https://github.com/oracle/docker-images/tree/master/OracleWebLogic/dockerfiles/12.2.1.1

but when i run:

```<code>docker build -t oracle/weblogic:12.2.1.1-developer .
</code>```

it gives me a permission denied error.

```<code>sudo docker build -t oracle/weblogic:12.2.1.1-developer .

Sending build context to Docker daemon  54.79MB

Step 1/13 : FROM oracle/serverjre:8

pull access denied for oracle/serverjre, repository does not exist or may require 'docker login'
</code>```

can anyone please help me??

Thankyou

答:
I worked around the problem by having a docker image built for oracle/serverjre:8 in my machine.

I downloaded the oracle/Serverjre8 binaries and built a docker image then built the weblogic.And it worked !!

Alternately,you can pull the image for Oracle/ServerJre8 directly from Oracle container registry or Docker store by logging in first.

```<code>docker login container-registry.oracle.com
Username: <oracle sso="" username="">
Password: <oracle sso="" password="">
Login successful.
docker pull container-registry.oracle.com/java/serverjre:8
</code>```

Title: pull access denied for oracle/serverjre

Body:
I have been trying to build a docker image for oracle/weblogic 12.2.1.

I followed all the instructions carefully as given in the official repo.

https://github.com/oracle/docker-images/tree/master/OracleWebLogic/dockerfiles/12.2.1.1

but when i run:

docker build -t oracle/weblogic:12.2.1.1-developer .

it gives me a permission denied error.

sudo docker build -t oracle/weblogic:12.2.1.1-developer .

Sending build context to Docker daemon  54.79MB

Step 1/13 : FROM oracle/serverjre:8

pull access denied for oracle/serverjre, repository does not exist or may require 'docker login'

can anyone please help me??

Thankyou

Body:
I worked around the problem by having a docker image built for oracle/serverjre:8 in my machine.

I downloaded the oracle/Serverjre8 binaries and built a docker image then built the weblogic.And it worked !!

Alternately,you can pull the image for Oracle/ServerJre8 directly from Oracle container registry or Docker store by logging in first.

docker login container-registry.oracle.com
Username: <oracle sso="" username="">
Password: <oracle sso="" password="">
Login successful.
docker pull container-registry.oracle.com/java/serverjre:8


问:
React - Each child in an array or iterator should have a unique "key" prop
I have a problem with the key props in a React JS component.

I'm getting

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of Login. It was passed a child from App.

warning in console log. App component is as follows :

```<code>import React from 'react';
import Header from '../common/header';
import HeaderCompact from '../common/headerCompact';
import Footer from '../common/footer';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      lang: 1
    };
  }

  changeLang(name, event) {
    event.preventDefault();
    switch (name) {
      case "fra" :
        this.setState({lang: 2});
        break;
      case "ger" :
        this.setState({lang: 3});
        break;
      case "ned" :
        this.setState({lang: 4});
        break;
      default:
        this.setState({lang: 1});
    }
  }

  render() {
    let currentRoute = this.props.location.pathname.slice(1);
    let header = currentRoute === "" ? <Header onClick={this.changeLang} lang={this.state.lang}/> :
      <HeaderCompact currentRoute={currentRoute} onClick={this.changeLang} lang={this.state.lang}/>;
    return (
      <div>
        {header}
        {React.cloneElement(this.props.children, {lang: this.state.lang})}
        <Footer lang={this.state.lang}/>
      </div>

    );
  }
}

export default App;
</code>```

And my login component is as follows :

```<code>import React from 'react';
import LoginForm from './loginForm';

const Login = ({currentLanguage}) => {

    const language = currentLanguage;

    return (
        <div className="container">
            <div className="row">
                <p className="col-lg-4 col-xs-12 col-md-4 loginTitle noPadding">{language.loginTitle}</p>
                <div className="col-lg-8 col-xs-12 col-md-8 loginForm noPadding">
                    <LoginForm currentLanguage={language}/>
                </div>
            </div>
        </div>
    );
};

export default Login;
</code>```

I'm still new in React and I'm not sure what should I pass like a key and where?

UPDATE

LoginForm component :

```<code>import React from 'react';
import {Link} from 'react-router';

import TextInput from '../../common/formElements/textInput';
import LoginButton from '../../common/formElements/button';

class LoginForm extends React.Component {

    constructor(props, context) {
        super(props, context);

        this.state = {
            loginData: {
                username: '',
                password: ''
            },
            errors: {}
        };

        this.buttonClickHandle = this.buttonClickHandle.bind(this);
        this.loginHandle = this.loginHandle.bind(this);
    }

    loginHandle(event) {
        let field = event.target.name;
        let value = event.target.value;
        this.state.loginData[field] = value;
        return this.setState({loginData: this.state.loginData});
    }

    buttonClickHandle(event) {
        event.preventDefault();
        alert("It's clicked/n");
    }

    render() {
        const language = this.props.currentLanguage;

        return (
            <div className="contact_form">
                <form role="form" action="" method="post" id="contact_form">
                    <div className="col-lg-4 col-md-4 col-sm-4 col-xs-12 smScrPdLeft" style={{marginTop: 5}}>
                        <TextInput
                            type="text"
                            name="username"
                            label=""
                            placeholder={language.loginUsername}
                            className="templateInput loginUsername col-lg-12 col-md-12 col-sm-12 col-xs-12"
                            id="name"
                            sizeClass=""
                            onChange={this.loginHandle}
                            value={this.state.username}
                            errors={this.state.errors.username}
                        />
                    </div>
                    <div className="col-lg-4 col-md-4 col-sm-4 col-xs-12 smPadding" style={{marginTop: 5}}>
                        <TextInput
                            type="password"
                            name="password"
                            label=""
                            placeholder={language.loginPassword}
                            className="templateInput loginPassword col-lg-12 col-md-12 col-sm-12 col-xs-12"
                            id="password"
                            sizeClass=""
                            onChange={this.loginHandle}
                            value={this.state.password}
                            errors={this.state.errors.password}
                        />
                        <Link to="/" className="forgotPassLabel">{language.forgotPassword}</Link>
                    </div>
                    <div className="col-lg-4 col-md-4 col-sm-4 col-xs-12 btnLogin noPadding smScrPdRight" style={{marginTop: 4}}>
                        <LoginButton onClick={() => this.buttonClickHandle(event)} name="registration" value={language.loginBtnText} className="rightFloat" icon="user"/>
                    </div>
                </form>
            </div>
        );
    }
}

export default LoginForm;
</code>```

Routes file :

```<code>import React from 'react';
import { IndexRoute, Route } from 'react-router';

import App from './components/App';
import HomePage from './components/HomePage';

const routes = (
    <Route path="/" component={App}>
        <IndexRoute component={HomePage}/>
    </Route>
);

export default routes;
</code>```

HomePage Component

```<code>return (
    <div>
        <div className="sidebar-menu-container" id="sidebar-menu-container">

            <div className="sidebar-menu-push">

                <div className="sidebar-menu-overlay"></div>

                <div className="sidebar-menu-inner">

                    <section className="marginOnXs" style={{width: '100%', padding: 0}}>
                        <div className="container">
                            <div className="row hideOnXS">
                                <MainSlider />
                            </div>
                        </div>

                    </section>

                    <div id="cta-1" className="onlyOnDesktop">
                        <Login currentLanguage={languageHome}/>
                    </div>

                    <section className="why-us" style={{paddingTop: 0}}>
                        <Info currentLanguage={languageHome}/>
                    </section>
                    <div className="clearfix"></div>

                    <section className="featured-listing">
                        <CarsList allCars={carsList()} currentLanguage={languageHome}/>
                    </section>

                    <section className="contactSection">
                        <ContactForm currentLanguage={languageHome}/>
                    </section>
                </div>
            </div>
        </div>
    </div>
);
</code>```

答:
The reason behind this warning is that you have not passed 'key' property. React uses this property for optimizing the rendering process as in when something changes in React, a re-render will occur only for what all has changed.

If our children are dynamic and in case they get shuffled with random functions or new components are introduced in the beginning of an array, the re-render is likely to get messed up. So, assigning this 'key' property helps us make sure that the state and identity of our components is maintained through multiple renders.
Please find below a sample code snippet demonstrating how to pass a key.

```<code><MyComponent key={{item.key}}/>
</code>```

The importance of key is beautifully explained here.

Body:
I have a problem with the key props in a React JS component.

I'm getting

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of Login. It was passed a child from App.

warning in console log. App component is as follows :

import React from 'react';
import Header from '../common/header';
import HeaderCompact from '../common/headerCompact';
import Footer from '../common/footer';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      lang: 1
    };
  }

  changeLang(name, event) {
    event.preventDefault();
    switch (name) {
      case "fra" :
        this.setState({lang: 2});
        break;
      case "ger" :
        this.setState({lang: 3});
        break;
      case "ned" :
        this.setState({lang: 4});
        break;
      default:
        this.setState({lang: 1});
    }
  }

  render() {
    let currentRoute = this.props.location.pathname.slice(1);
    let header = currentRoute === "" ?  :
      <HeaderCompact currentRoute={currentRoute} onClick={this.changeLang} lang={this.state.lang}/>;
    return (

        {header}
        {React.cloneElement(this.props.children, {lang: this.state.lang})}

    );
  }
}

export default App;

And my login component is as follows :

import React from 'react';
import LoginForm from './loginForm';

const Login = ({currentLanguage}) => {

    const language = currentLanguage;

    return (

{language.loginTitle}

                    <LoginForm currentLanguage={language}/>

    );
};

export default Login;

I'm still new in React and I'm not sure what should I pass like a key and where?

UPDATE

LoginForm component :

import React from 'react';
import {Link} from 'react-router';

import TextInput from '../../common/formElements/textInput';
import LoginButton from '../../common/formElements/button';

class LoginForm extends React.Component {

    constructor(props, context) {
        super(props, context);

        this.state = {
            loginData: {
                username: '',
                password: ''
            },
            errors: {}
        };

        this.buttonClickHandle = this.buttonClickHandle.bind(this);
        this.loginHandle = this.loginHandle.bind(this);
    }

    loginHandle(event) {
        let field = event.target.name;
        let value = event.target.value;
        this.state.loginData[field] = value;
        return this.setState({loginData: this.state.loginData});
    }

    buttonClickHandle(event) {
        event.preventDefault();
        alert("It's clicked/n");
    }

    render() {
        const language = this.props.currentLanguage;

        return (

                <form role="form" action="" method="post" id="contact_form">

                        <TextInput
                            type="text"
                            name="username"
                            label=""
                            placeholder={language.loginUsername}
                            className="templateInput loginUsername col-lg-12 col-md-12 col-sm-12 col-xs-12"
                            id="name"
                            sizeClass=""
                            onChange={this.loginHandle}
                            value={this.state.username}
                            errors={this.state.errors.username}
                        />

                        <TextInput
                            type="password"
                            name="password"
                            label=""
                            placeholder={language.loginPassword}
                            className="templateInput loginPassword col-lg-12 col-md-12 col-sm-12 col-xs-12"
                            id="password"
                            sizeClass=""
                            onChange={this.loginHandle}
                            value={this.state.password}
                            errors={this.state.errors.password}
                        />
                        <Link to="/" className="forgotPassLabel">{language.forgotPassword}</Link>

                        <LoginButton onClick={() => this.buttonClickHandle(event)} name="registration" value={language.loginBtnText} className="rightFloat" icon="user"/>

                </form>

        );
    }
}

export default LoginForm;

Routes file :

import React from 'react';
import { IndexRoute, Route } from 'react-router';

import App from './components/App';
import HomePage from './components/HomePage';

const routes = (
    <Route path="/" component={App}>
        <IndexRoute component={HomePage}/>
    </Route>
);

export default routes;

HomePage Component

return (

                                <MainSlider />

                        <Login currentLanguage={languageHome}/>

                        <Info currentLanguage={languageHome}/>

                        <CarsList allCars={carsList()} currentLanguage={languageHome}/>

                        <ContactForm currentLanguage={languageHome}/>

);

Body:
The reason behind this warning is that you have not passed 'key' property. React uses this property for optimizing the rendering process as in when something changes in React, a re-render will occur only for what all has changed.

If our children are dynamic and in case they get shuffled with random functions or new components are introduced in the beginning of an array, the re-render is likely to get messed up. So, assigning this 'key' property helps us make sure that the state and identity of our components is maintained through multiple renders.
Please find below a sample code snippet demonstrating how to pass a key.

<MyComponent key={{item.key}}/>

The importance of key is beautifully explained here.

ContentLicense: CC BY-SA 4.0


问:
Msg 33299, Level 16 when using Always Encrypted Column in WHERE Clause
I have a table named Product which has a field named Code varchar(50).

I used Always Encrypted on this field. Insert and normal select is working fine.

But when I am trying create a stored procedure to select with WHERE clause on Code field it is showing an error and not allowing me to create the procedure. My procedure code is as follows:

```<code>CREATE PROCEDURE [dbo].[GetProductByCode]
@productCode VARCHAR (50)
AS
BEGIN
    SET NOCOUNT ON;
    SELECT  id,
        [Name],
        Code,
        Price
    FROM   Product
    WHERE Code = @productCode;
END
</code>```

The error it is showing is as follows:

Msg 33299, Level 16, State 2, Procedure GetProductByCode, Line 11 [Batch Start Line 0]
  Encryption scheme mismatch for columns/variables '@productCode', 'Code'. The encryption scheme for the columns/variables is (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto2', column_encryption_key_database_name = 'xxxx') and the expression near line '11' expects it to be (encryption_type = 'DETERMINISTIC') (or weaker).

Why it is not allowing me to create the procedure?

I tried by setting Column Encryption Setting=Enabled in the Connection.

Enable Parameterization For Always Encryption is checked.

答:
Refer this document

Columns using randomized encryption are not supported in clauses at
  all

The column code in this case is having Randomised encryption.
This encryption type should only be used for columns that are just for display, not for querying.

So if you want to query using the column code change its encryption type to Deterministic.

Columns using deterministic encryption support WHERE equality comparisons, as well as DISTINCT, JOIN, and GROUP BY.

You cannot perform inequality, range, or LIKE queries, or any other operations against encrypted columns.

Have a look at this too.

Body:
I have a table named Product which has a field named Code varchar(50).

I used Always Encrypted on this field. Insert and normal select is working fine.

But when I am trying create a stored procedure to select with WHERE clause on Code field it is showing an error and not allowing me to create the procedure. My procedure code is as follows:

CREATE PROCEDURE [dbo].[GetProductByCode]
@productCode VARCHAR (50)
AS
BEGIN
    SET NOCOUNT ON;
    SELECT  id,
        [Name],
        Code,
        Price
    FROM   Product
    WHERE Code = @productCode;
END

The error it is showing is as follows:

Msg 33299, Level 16, State 2, Procedure GetProductByCode, Line 11 [Batch Start Line 0]
  Encryption scheme mismatch for columns/variables '@productCode', 'Code'. The encryption scheme for the columns/variables is (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto2', column_encryption_key_database_name = 'xxxx') and the expression near line '11' expects it to be (encryption_type = 'DETERMINISTIC') (or weaker).

Why it is not allowing me to create the procedure?

I tried by setting Column Encryption Setting=Enabled in the Connection.

Enable Parameterization For Always Encryption is checked.


问:
Storing an SQLite database file in TFS and the -journal file
I have a pre-populated, read only SQLite database file I am shipping as an Asset with my Android App. Changes to the read only data constitute a version release/update in the app store. Thus, the DB file (and currently the journal file) are being stored in version control (TFS).

The question:

Is there any advantage to storing the -journal file in version control? After everything I read about SQLite, my understanding is it is basically just a simple transaction log for a file and there's no database engine in play (like with MSSQL Server). In effect, TFS is keeping my read only data Versioned, so I see no reason to check-in the journal file or have it be part of my project / assets at all. Am I missing anything?

答:
As long as there is not a transaction that has not yet been committed or rolled back, the journal file is empty.
So it should never be required to have it in version control.

(The default journal mode is DELETE, so unless you have changed this setting, you should investigate how this file ended up in TFS in the first place.)


问:
Download an image from Firebase to Flutter
There are many examples of uploading a file to firebase and getting a downloadUrl but there's no example that I found to get the DownloadURL for an image and using it in a Flutter widget.

This is the one which is related to uploading a file

```<code>final StorageReference ref =
    FirebaseStorage.instance.ref().child("foo$rand.txt");
final StorageUploadTask uploadTask = ref.put(file);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
final http.Response downloadData = await http.get(downloadUrl);
</code>```

Can anyone give an example of one where the file already exists in firebase and how to get a download link?

答:
You can just use the Storage API to download, like with upload</p>

```<code>someMethod() async {
  var data = await FirebaseStorage.instance.ref().child("foo$rand.txt").getData();
  var text = new String.fromCharCodes(data);
  print(data);
}
</code>```

Body:
There are many examples of uploading a file to firebase and getting a downloadUrl but there's no example that I found to get the DownloadURL for an image and using it in a Flutter widget.

This is the one which is related to uploading a file

final StorageReference ref =
    FirebaseStorage.instance.ref().child("foo$rand.txt");
final StorageUploadTask uploadTask = ref.put(file);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
final http.Response downloadData = await http.get(downloadUrl);

Can anyone give an example of one where the file already exists in firebase and how to get a download link?

Body:
You can just use the Storage API to download, like with upload

someMethod() async {
  var data = await FirebaseStorage.instance.ref().child("foo$rand.txt").getData();
  var text = new String.fromCharCodes(data);
  print(data);
}


问:
In what way is the DGML graphic coordinate oriented?
Context

I am trying to convert a DGML graph into an SVG. I am using Javascript to read and parse the DGML Nodes and Links using Jquery. I created a DGML graph using Visual Studio 2017 (it has an interactive inbuilt editor). Essentially I need to create a mapping between the position of nodes on the DGML graph and a generated SVG. I have managed to make a conversion of every property of the nodes and links, except for a property called Bounds

```<code><?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="Node1" Background="#FF000000" Bounds="289.142857142857,-914.285714285714,56.9200000000001,25.96" Label="node 1" UseManualLocation="True" />
<Node Id="Node2" Bounds="-99.1466388157435,-813.468571428572,56.9200000000001,25.96" Label="node 2" UseManualLocation="True" />
<Node Id="Node3" Bounds="165.353095238095,-821.948571428572,56.9200000000001,25.96" Label="node 3" UseManualLocation="True" />
<Node Id="Node4" Bounds="231.884895804269,-672.637129778181,56.92,25.96" Label="node 4" UseManualLocation="True" />
<Node Id="Node5" Bounds="126.293653230212,-514.368957318116,56.9200000000001,25.96" Label="node 5" UseManualLocation="True" />
<Node Id="Node6" Bounds="513.21231765747,-699.551714460973,56.9200000000001,25.96" Label="node 6" UseManualLocation="True" />
</Nodes>
<Links>
<Link Source="Node1" Target="Node2" Bounds="-33.5154810441621,-893.916239433358,322.658338187019,83.7763765262094" />
<Link Source="Node1" Target="Node3" Bounds="218.428553771979,-888.325714285714,81.7729515442388,60.9960031621974" />
<Link Source="Node2" Target="Node4" Bounds="-42.8686314368827,-788.653915128306,267.113829712029,113.638782142621" />
<Link Source="Node2" Target="Node5" Bounds="-60.9032254171191,-787.508586425781,200.456326731834,265.952512098603" />
<Link Source="Node3" Target="Node4" Bounds="199.596870550233,-795.988597412109,51.3011424145167,115.130629087374" />
<Link Source="Node4" Target="Node5" Bounds="168.40836594804,-646.677165527344,83.2767077301747,124.821483021298" />
<Link Source="Node4" Target="Node6" Bounds="288.80489440918,-682.991837277453,215.448314485295,20.6119078319973" />
<Link Source="Node6" Target="Node1" Bounds="337.645038336076,-882.098554229514,190.482965266866,182.54683792092" />
</Links>
<Properties>
<Property Id="Background" Label="Background" Description="The background color" DataType="System.Windows.Media.Brush" />
<Property Id="Bounds" DataType="System.Windows.Rect" />
<Property Id="Label" Label="Label" Description="Displayable label of an Annotatable object" DataType="System.String" />
<Property Id="UseManualLocation" DataType="System.Boolean" />
</Properties>
</DirectedGraph>
</code>```

I saw in the Property tag for "Bounds" the datatype is System.Windows.Rect which has a constructor Rect(Double, Double, Double, Double)
- Initializes a new instance of the Rect structure that has the specified x-coordinate, y-coordinate, width, and height.

https://msdn.microsoft.com/en-us/library/system.windows.rect(v=vs.110).aspx

Since all the nodes have the same size, it is not wrong to assume that the final two parameters are width and height.

Question

How is the graphics coordinate system of the DGML oriented? For instance, an SVG graphic starts like most CG coordinates, left top corner origin; positive X towards right, positive Y towards bottom. I could not find any information on this on the DGML reference

https://learn.microsoft.com/en-us/visualstudio/modeling/directed-graph-markup-language-dgml-reference

答: Looking at your diagram i think the Y axis is inverted (top-down) and X axis is classical (left-right). Start of coordinates is between Node2 and Node5 somewhere behind the bottom of diagram view.</p>

Body:
Context

I am trying to convert a DGML graph into an SVG. I am using Javascript to read and parse the DGML Nodes and Links using Jquery. I created a DGML graph using Visual Studio 2017 (it has an interactive inbuilt editor). Essentially I need to create a mapping between the position of nodes on the DGML graph and a generated SVG. I have managed to make a conversion of every property of the nodes and links, except for a property called Bounds

<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="Node1" Background="#FF000000" Bounds="289.142857142857,-914.285714285714,56.9200000000001,25.96" Label="node 1" UseManualLocation="True" />
<Node Id="Node2" Bounds="-99.1466388157435,-813.468571428572,56.9200000000001,25.96" Label="node 2" UseManualLocation="True" />
<Node Id="Node3" Bounds="165.353095238095,-821.948571428572,56.9200000000001,25.96" Label="node 3" UseManualLocation="True" />
<Node Id="Node4" Bounds="231.884895804269,-672.637129778181,56.92,25.96" Label="node 4" UseManualLocation="True" />
<Node Id="Node5" Bounds="126.293653230212,-514.368957318116,56.9200000000001,25.96" Label="node 5" UseManualLocation="True" />
<Node Id="Node6" Bounds="513.21231765747,-699.551714460973,56.9200000000001,25.96" Label="node 6" UseManualLocation="True" />
</Nodes>
<Links>
<Link Source="Node1" Target="Node2" Bounds="-33.5154810441621,-893.916239433358,322.658338187019,83.7763765262094" />
<Link Source="Node1" Target="Node3" Bounds="218.428553771979,-888.325714285714,81.7729515442388,60.9960031621974" />
<Link Source="Node2" Target="Node4" Bounds="-42.8686314368827,-788.653915128306,267.113829712029,113.638782142621" />
<Link Source="Node2" Target="Node5" Bounds="-60.9032254171191,-787.508586425781,200.456326731834,265.952512098603" />
<Link Source="Node3" Target="Node4" Bounds="199.596870550233,-795.988597412109,51.3011424145167,115.130629087374" />
<Link Source="Node4" Target="Node5" Bounds="168.40836594804,-646.677165527344,83.2767077301747,124.821483021298" />
<Link Source="Node4" Target="Node6" Bounds="288.80489440918,-682.991837277453,215.448314485295,20.6119078319973" />
<Link Source="Node6" Target="Node1" Bounds="337.645038336076,-882.098554229514,190.482965266866,182.54683792092" />
</Links>
<Properties>
<Property Id="Background" Label="Background" Description="The background color" DataType="System.Windows.Media.Brush" />
<Property Id="Bounds" DataType="System.Windows.Rect" />
<Property Id="Label" Label="Label" Description="Displayable label of an Annotatable object" DataType="System.String" />
<Property Id="UseManualLocation" DataType="System.Boolean" />
</Properties>
</DirectedGraph>

I saw in the Property tag for "Bounds" the datatype is System.Windows.Rect which has a constructor Rect(Double, Double, Double, Double)
- Initializes a new instance of the Rect structure that has the specified x-coordinate, y-coordinate, width, and height.

https://msdn.microsoft.com/en-us/library/system.windows.rect(v=vs.110).aspx

Since all the nodes have the same size, it is not wrong to assume that the final two parameters are width and height.

Question

How is the graphics coordinate system of the DGML oriented? For instance, an SVG graphic starts like most CG coordinates, left top corner origin; positive X towards right, positive Y towards bottom. I could not find any information on this on the DGML reference

https://learn.microsoft.com/en-us/visualstudio/modeling/directed-graph-markup-language-dgml-reference