text:
Q: Few Errors, Couldn't Find the Bugs I have a few errors in my code. It says:

moveDelay() does not exist in touchesBegan()

and it is saying that I should delete override from the last two override functions. I read that it could be because of a missing }, but I could not find any errors. Sorry it's so long.
All vars have been declared, I deleted them to get under the word limit.
class GameScene: SKScene, SKPhysicsContactDelegate {
    func playBackgroundMusic(filename: String){
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
        guard let newURL = url else {
            print("Could not find music")
            return
        }
        do {
            backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
            backgroundMusicPlayer.numberOfLoops = 0
            backgroundMusicPlayer.prepareToPlay()
            backgroundMusicPlayer.play()
        } catch let error as NSError {
            print(error.description)
        }
    }
    override func didMoveToView(view: SKView) {
        self.physicsWorld.contactDelegate = self

        scene?.backgroundColor = UIColor.blackColor()

        begin.text = "Tap to Begin"
        begin.fontSize = 20
        begin.position = CGPoint(x: scene!.frame.width/2, y: scene!.frame.height/2)
        begin.fontColor = UIColor.blackColor()
        begin.zPosition = 2.0
        self.addChild(begin)
        Fading = SKAction.sequence([SKAction.fadeInWithDuration(0.2), SKAction.fadeOutWithDuration(0.2)])
        begin.runAction(SKAction.repeatActionForever(Fading))

        HighScoreLabel.text = "Highscore: \(highscore)"
        HighScoreLabel.position = CGPoint(x: scene!.frame.width/2, y: 120)
        HighScoreLabel.fontColor = UIColor.whiteColor()
        self.addChild(HighScoreLabel)
        var defaults = NSUserDefaults()
        highscore = defaults.integerForKey("highscore")
        if (score > highscore){
            defaults.setInteger(score, forKey: "highscore")
        }
        var HighScoreShow = defaults.integerForKey("highscore")
        HighScoreLabel.text = "Highscore: \(HighScoreShow)"

        ScoreLabel.alpha = 0
        ScoreLabel.fontSize = 35
        ScoreLabel.position = CGPoint(x: scene!.frame.width/2, y: 150)
        ScoreLabel.fontColor = UIColor.whiteColor()
        ScoreLabel.text = "\(score)"
        self.addChild(ScoreLabel)

        instruct.frame = CGRect(x: 270, y: 0, width: 150, height: 20)
        instruct.backgroundColor = UIColor.blackColor()
        instruct.font = UIFont(name: "Copperplate", size: 20)
        instruct.text = "Tap to Shoot"
        instruct.textColor = UIColor.whiteColor()
        self.view?.addSubview(instruct)

        let delay = 3.0 * Double(NSEC_PER_SEC)
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
        dispatch_after(time, dispatch_get_main_queue()) {

            self.instruct.removeFromSuperview()
        }

        MainBall.size = CGSize(width: 135, height: 135)
        MainBall.position = CGPoint(x: frame.width/2, y: frame.height/2)
        MainBall.zPosition = 1.0
        MainBall.physicsBody = SKPhysicsBody(circleOfRadius: MainBall.size.width/2)
        MainBall.physicsBody?.categoryBitMask = PhysicsCategory.MainBall
        MainBall.physicsBody?.collisionBitMask = PhysicsCategory.square
        MainBall.physicsBody?.collisionBitMask = PhysicsCategory.pentagon
        MainBall.physicsBody?.contactTestBitMask = PhysicsCategory.square
        MainBall.physicsBody?.contactTestBitMask = PhysicsCategory.pentagon
        MainBall.physicsBody?.collisionBitMask = PhysicsCategory.NonStop
        MainBall.physicsBody?.contactTestBitMask = PhysicsCategory.NonStop

        MainBall.physicsBody?.affectedByGravity = false
        MainBall.physicsBody?.dynamic = false
        MainBall.name = "MainBall"

        self.addChild(MainBall)

            }

    func pentDelay(){

        let delay1 = 20.0 * Double(NSEC_PER_SEC)
        let time1 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay1))
        dispatch_after(time1, dispatch_get_main_queue()) {

            self.pentTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: Selector("PentSpawn"), userInfo: nil, repeats: true)

        }

    }
    func circleDelay(){

        let delay2 = 40.0 * Double(NSEC_PER_SEC)
        let time2 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay2))
        dispatch_after(time2, dispatch_get_main_queue()) {

            self.circleTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: Selector("CircleSpawn"), userInfo: nil, repeats: true)

        }

    func moveDelay(){
        let delay1 = 30.0 * Double(NSEC_PER_SEC)
        let time1 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay1))
        dispatch_after(time1, dispatch_get_main_queue()) {
            var left = SKAction.moveToX(self.frame.width/2 - 60, duration: 2.0)
            var right = SKAction.moveToX(self.frame.width/2 + 120, duration: 2.0)
            var moving = SKAction.sequence([left, right])
            self.MainBall.runAction(SKAction.repeatActionForever(moving))

        }

    }

    func NonstopPower(){
        NonStop.size = CGSize(width: 40, height: 40)
        var PositionX = arc4random_uniform(UInt32(self.frame.width))
        var PositionY = arc4random_uniform(UInt32(self.frame.height))
        NonStop.position = CGPoint(x: CGFloat(PositionX), y: CGFloat(PositionY))
        NonStop.physicsBody = SKPhysicsBody(rectangleOfSize: NonStop.size)
        NonStop.physicsBody?.categoryBitMask = PhysicsCategory.NonStop
        NonStop.physicsBody?.collisionBitMask = PhysicsCategory.bullet
        NonStop.physicsBody?.contactTestBitMask = PhysicsCategory.bullet
        NonStop.physicsBody?.collisionBitMask = PhysicsCategory.MainBall
        NonStop.physicsBody?.contactTestBitMask = PhysicsCategory.MainBall
        NonStop.physicsBody?.affectedByGravity = false
        NonStop.physicsBody?.dynamic = true
        NonStop.name = "NonStop"
        self.addChild(NonStop)
    }

    func didBeginContact(contact: SKPhysicsContact) {
        if contact.bodyA.node != nil && contact.bodyB.node != nil{
            let firstBody = contact.bodyA.node as! SKSpriteNode
            let secondBody = contact.bodyB.node as! SKSpriteNode

            if((firstBody.name == "square") && (secondBody.name == "bullet")){
                collisionBulletSquare(firstBody, bullet: secondBody)
            }else if((secondBody.name == "square") && (firstBody.name == "bullet")){
                collisionBulletSquare(secondBody, bullet: firstBody)
            }else if((firstBody.name == "pentagon") && (secondBody.name == "bullet")){
                collisionBulletPentagon(firstBody, bullet: secondBody)
            }else if((secondBody.name == "pentagon") && (firstBody.name == "bullet")){
                collisionBulletPentagon(secondBody, bullet: firstBody)
            }else if ((firstBody.name == "circle") && (secondBody.name == "bullet")){
                collisionBulletCircle(firstBody, bullet: secondBody)
            }else if((secondBody.name == "circle") && (firstBody.name == "bullet")){
                collisionBulletCircle(secondBody, bullet: firstBody)
            }else if((secondBody.name == "MainBall") && (firstBody.name == "square")){
                collisionBallSquare(secondBody, square: firstBody)
            }else if((firstBody.name == "MainBall") && (secondBody.name == "square")){
                collisionBallSquare(firstBody, square: secondBody)
            }else if((secondBody.name == "MainBall") && (firstBody.name == "pentagon")){
                collisionBallPentagon(secondBody, pentagon: firstBody)
            }else if((firstBody.name == "MainBall") && (secondBody.name == "pentagon")){
                collisionBallPentagon(firstBody, pentagon: secondBody)
            }else if((secondBody.name == "MainBall") && (firstBody.name == "circle")){
                collisionBallCircle(secondBody, circle: firstBody)
            }else if((firstBody.name == "MainBall") && (secondBody.name == "circle")){
                collisionBallCircle(firstBody, circle: secondBody)
            }else if((secondBody.name == "bullet") && (firstBody.name == "NonStop")){
                NonStopCollect(firstBody, bullet: secondBody)
            }else if((firstBody.name == "bullet") && (secondBody.name == "NonStop")){
                NonStopCollect(secondBody, bullet: firstBody)
          //  }else if((secondBody.name == "bullet") && (firstBody.name == "Ultimate")){
               // UltimateCollect(firstBody, bullet: secondBody)
        //    }else if((firstBody.name == "bullet") && (secondBody.name == "Ultimate")){
               // UltimateCollect(secondBody, bullet: firstBody)
            }else if((secondBody.name == "MainBall") && (firstBody.name == "NonStop")){
                NonStop.removeFromParent()
            }else if((firstBody.name == "MainBall") && (secondBody.name == "NonStop")){
                NonStop.removeFromParent()
        //     }else if((secondBody.name == "MainBall") && (firstBody.name == "Ultimate")){
               //  Ultimate.removeFromParent()
          //  }else if((firstBody.name == "MainBall") && (secondBody.name == "Ultimate")){
               // Ultimate.removeFromParent()
            }

        }

    }

    func NonStopCollect(NonStop : SKSpriteNode, bullet : SKSpriteNode){
        NonStop.removeFromParent()
        NonStopPowerBool = true
        bullet.removeFromParent()
        let delay4 = 10.0 * Double(NSEC_PER_SEC)
        let time4 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay4))
        dispatch_after(time4, dispatch_get_main_queue()) {
            self.NonStopPowerBool = false
        }

    }

   /* func UltimateCollect(Ultimate : SKSpriteNode, bullet : SKSpriteNode){
        Ultimate.removeFromParent()
        bullet.removeAllActions()
        var path = UIBezierPath()
        var dx = bullet.position.x
        var dy = bullet.position.y
        var rad = atan2(dy, dx)
        path = UIBezierPath(arcCenter: CGPoint(x: bullet.position.x, y: bullet.position.y), radius: 40, startAngle: rad, endAngle: rad + CGFloat(M_PI * 4), clockwise: true)
        let follow = SKAction.followPath(path.CGPath, asOffset: true, orientToPath: true, speed: 150)
        bullet.runAction(SKAction.repeatActionForever(follow))
    }*/

    func collisionBulletSquare(square : SKSpriteNode, bullet : SKSpriteNode){
        square.removeAllActions()
        square.runAction(SKAction.scaleTo(0.2, duration: 0.2))
        playBackgroundMusic("Pop.mp3")
        score++
        ScoreLabel.text = "\(score)"
        if (NonStopPowerBool == false){
            bullet.removeFromParent()
        let delay1 = 0.2 * Double(NSEC_PER_SEC)
        let time1 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay1))
        dispatch_after(time1, dispatch_get_main_queue()) {

        square.removeFromParent()
        }

        }
    }
    func collisionBulletPentagon(pentagon : SKSpriteNode, bullet : SKSpriteNode){
        pentagon.removeAllActions()

        pentagon.runAction(SKAction.scaleTo(0.2, duration: 0.2))

        playBackgroundMusic("Pop.mp3")
        score = score + 2
        ScoreLabel.text = "\(score)"
        if (NonStopPowerBool == false){
        bullet.removeFromParent()
            let delay1 = 0.2 * Double(NSEC_PER_SEC)
            let time1 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay1))
            dispatch_after(time1, dispatch_get_main_queue()) {

        pentagon.removeFromParent()
            }
        }
    }
    func collisionBulletCircle(circle : SKSpriteNode, bullet : SKSpriteNode){
        circle.removeAllActions()

        circle.runAction(SKAction.scaleTo(0.2, duration: 0.2))

        playBackgroundMusic("Pop.mp3")
        score = score + 3
        ScoreLabel.text = "\(score)"
        if (NonStopPowerBool == false){
            bullet.removeFromParent()
        }
        let delay1 = 0.2 * Double(NSEC_PER_SEC)
        let time1 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay1))
        dispatch_after(time1, dispatch_get_main_queue()) {

        circle.removeFromParent()
        }
    }

    func collisionBallSquare(MainBall : SKSpriteNode, square : SKSpriteNode){
        hits++
        if (hits < 2){
            MainBall.runAction(SKAction.scaleBy(2.0, duration: 3.0))
        }else if (hits>=2){
            squareTimer.invalidate()
            pentTimer.invalidate()
            circleTimer.invalidate()
            pentDelay()
            circleDelay()
            NonStopTimer.invalidate()
            gameStarted = false
            begin.runAction(SKAction.fadeInWithDuration(0.2))
            begin.runAction(SKAction.repeatActionForever(Fading))
            HighScoreLabel.runAction(SKAction.fadeInWithDuration(0.2))
//highscore
            var defaults = NSUserDefaults()
            highscore = defaults.integerForKey("highscore")
            if (score > highscore){
                defaults.setInteger(score, forKey: "highscore")
            }
            var HighScoreShow = defaults.integerForKey("highscore")
            HighScoreLabel.text = "Highscore: \(HighScoreShow)"
            MainBall.physicsBody?.affectedByGravity = true
            MainBall.physicsBody?.dynamic = true
            square.removeFromParent()

        }
        square.removeFromParent()
    }
    func collisionBallPentagon(MainBall : SKSpriteNode, pentagon : SKSpriteNode){
        hits++
        if (hits < 2){
            MainBall.runAction(SKAction.scaleBy(2.0, duration: 3.0))
        }else if (hits>=2){
            pentTimer.invalidate()
            circleTimer.invalidate()
            squareTimer.invalidate()
            pentDelay()
            circleDelay()
            NonStopTimer.invalidate()
            gameStarted = false
            begin.runAction(SKAction.fadeInWithDuration(0.2))
            begin.runAction(SKAction.repeatActionForever(Fading))
            HighScoreLabel.runAction(SKAction.fadeInWithDuration(0.2))
            //highscore
            var defaults = NSUserDefaults()
            highscore = defaults.integerForKey("highscore")
            if (score > highscore){
                defaults.setInteger(score, forKey: "highscore")
            }
            var HighScoreShow = defaults.integerForKey("highscore")
            HighScoreLabel.text = "Highscore: \(HighScoreShow)"
            MainBall.physicsBody?.affectedByGravity = true
            MainBall.physicsBody?.dynamic = true
            pentagon.removeFromParent()

        }
        pentagon.removeFromParent()

    }
    func collisionBallCircle(MainBall : SKSpriteNode, circle : SKSpriteNode){
        hits++
        if (hits < 2){
            MainBall.runAction(SKAction.scaleBy(2.0, duration: 3.0))
        }else if (hits>=2){
            circleTimer.invalidate()
            pentTimer.invalidate()
            squareTimer.invalidate()
            pentDelay()
            circleDelay()
            NonStopTimer.invalidate()
            gameStarted = false
            begin.runAction(SKAction.fadeInWithDuration(0.2))
            begin.runAction(SKAction.repeatActionForever(Fading))
            HighScoreLabel.runAction(SKAction.fadeInWithDuration(0.2))
            //highscore
            var defaults = NSUserDefaults()
            highscore = defaults.integerForKey("highscore")
            if (score > highscore){
                defaults.setInteger(score, forKey: "highscore")
            }
            var HighScoreShow = defaults.integerForKey("highscore")
            HighScoreLabel.text = "Highscore: \(HighScoreShow)"
            MainBall.physicsBody?.affectedByGravity = true
            MainBall.physicsBody?.dynamic = true
            circle.removeFromParent()

        }

        circle.removeFromParent()

        }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */

        if gameStarted == false{
            begin.removeAllActions()
            begin.fontColor = UIColor.whiteColor()
            begin.runAction(SKAction.fadeOutWithDuration(0.2))
            circleTimer.invalidate()
            pentTimer.invalidate()
            squareTimer.invalidate()
            NonStopTimer.invalidate()
           // UltimateTimer.invalidate()
            NonStopPowerBool = false
            let delay3 = 2.0 * Double(NSEC_PER_SEC)
            let time3 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay3))
            dispatch_after(time3, dispatch_get_main_queue()) {
                self.HighScoreLabel.runAction(SKAction.fadeOutWithDuration(0.2))
                self.ScoreLabel.runAction(SKAction.sequence([SKAction.waitForDuration(0.5), SKAction.fadeInWithDuration(0.2)]))
                self.circleTimer.invalidate()
                self.pentTimer.invalidate()
                self.squareTimer.invalidate()
                self.squareTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: Selector("SquareSpawn"), userInfo: nil, repeats: true)
                self.NonStopTimer = NSTimer.scheduledTimerWithTimeInterval(20.0, target: self, selector: Selector("NonstopPower"), userInfo: nil, repeats: true)
              //  self.UltimateTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("UltimatePower"), userInfo: nil, repeats: true)
                self.pentDelay()
                self.circleDelay()
                self.MainBall.removeAllActions()
                self.moveDelay()
                self.gameStarted = true
                self.MainBall.runAction(SKAction.scaleTo(0.66, duration: 0.2))
                self.hits = 0
                self.score = 0
                self.ScoreLabel.text = "\(self.score)"
                self.MainBall.physicsBody?.affectedByGravity = false
                self.MainBall.runAction(SKAction.moveToY(self.frame.height/2, duration: 0.5))
                self.MainBall.runAction(SKAction.moveToX(self.frame.width/2, duration: 0.5))
                self.MainBall.physicsBody?.dynamic = false
            }
        }else{
        for touch in touches {
            let location = touch.locationInNode(self)
            begin.runAction(SKAction.fadeOutWithDuration(0.2))
            var defaults = NSUserDefaults()
            highscore = defaults.integerForKey("highscore")
            if (score > highscore){
                defaults.setInteger(score, forKey: "highscore")
            }
            var HighScoreShow = defaults.integerForKey("highscore")
            HighScoreLabel.text = "Highscore: \(HighScoreShow)"

            var bullet = SKSpriteNode(imageNamed: "CircleBullet.png")
            bullet.position = MainBall.position
            bullet.zPosition = -1
            bullet.size = CGSize(width: 15, height: 15)

            bullet.physicsBody = SKPhysicsBody(circleOfRadius: bullet.size.width/2)
            bullet.physicsBody?.affectedByGravity = false
            bullet.physicsBody?.categoryBitMask = PhysicsCategory.bullet
            bullet.physicsBody?.collisionBitMask = PhysicsCategory.square
            bullet.physicsBody?.collisionBitMask = PhysicsCategory.pentagon
            bullet.physicsBody?.contactTestBitMask = PhysicsCategory.square
            bullet.physicsBody?.contactTestBitMask = PhysicsCategory.pentagon
            bullet.physicsBody?.contactTestBitMask = PhysicsCategory.NonStop
            bullet.physicsBody?.collisionBitMask = PhysicsCategory.NonStop
           // bullet.physicsBody?.contactTestBitMask = PhysicsCategory.Ultimate
           // bullet.physicsBody?.collisionBitMask = PhysicsCategory.Ultimate
            bullet.name = "bullet"
            bullet.physicsBody?.dynamic = true

            self.addChild(bullet)
            let delay4 = 10.0 * Double(NSEC_PER_SEC)
            let time4 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay4))
            dispatch_after(time4, dispatch_get_main_queue()) {
                bullet.removeFromParent()
            }

            var dx = CGFloat(location.x - MainBall.position.x)
            var dy = CGFloat(location.y - MainBall.position.y)

            let magnitude = sqrt(dx * dx + dy * dy)

            dx /= magnitude
            dy /= magnitude

            let vector = CGVector(dx: 2.0 * dx, dy: 2.0 * dy)

            bullet.physicsBody?.applyImpulse(vector)

        }
        }
    }

    func SquareSpawn(){

        let square = SKSpriteNode(imageNamed: "Square.png")
        square.size = CGSizeMake(35, 35)
        square.physicsBody = SKPhysicsBody(rectangleOfSize: square.size)
        square.physicsBody?.categoryBitMask = PhysicsCategory.square
        square.physicsBody?.contactTestBitMask = PhysicsCategory.bullet | PhysicsCategory.MainBall
        square.physicsBody?.collisionBitMask = PhysicsCategory.bullet | PhysicsCategory.MainBall
        square.physicsBody?.dynamic = true
        square.physicsBody?.affectedByGravity = false
        square.name = "square"

        let RandomPosNmbr = arc4random() % 4

        switch RandomPosNmbr{
        case 0:
            square.position.x = 0
            var PositionY = arc4random_uniform(UInt32(frame.size.height))
            square.position.y = CGFloat(PositionY)
            self.addChild(square)
            break
        case 1:
            square.position.x = frame.size.width
            var PositionY = arc4random_uniform(UInt32(frame.size.height))
            square.position.y = CGFloat(PositionY)
            self.addChild(square)

            break
        case 2:
            square.position.y = 0
            var PositionX = arc4random_uniform(UInt32(frame.size.width))
            square.position.x = CGFloat(PositionX)
            self.addChild(square)
            break
        case 3:
            square.position.y = frame.size.width
            var PositionX = arc4random_uniform(UInt32(frame.size.width))
            square.position.x = CGFloat(PositionX)
            self.addChild(square)
            break
        default:

            break
        }

        square.runAction(SKAction.moveTo(MainBall.position, duration: 3.0))
        let delay3 = 3.0 * Double(NSEC_PER_SEC)
        let time3 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay3))
        dispatch_after(time3, dispatch_get_main_queue()) {
            square.removeFromParent()
        }

    }

    func PentSpawn(){

        let pentagon = SKSpriteNode(imageNamed: "Pentagon.png")
        pentagon.size = CGSizeMake(35, 35)
        pentagon.physicsBody = SKPhysicsBody(rectangleOfSize: pentagon.size)
        pentagon.physicsBody?.categoryBitMask = PhysicsCategory.pentagon
        pentagon.physicsBody?.contactTestBitMask = PhysicsCategory.bullet | PhysicsCategory.MainBall
        pentagon.physicsBody?.collisionBitMask = PhysicsCategory.bullet | PhysicsCategory.MainBall
        pentagon.physicsBody?.dynamic = true
        pentagon.physicsBody?.affectedByGravity = false
        pentagon.name = "pentagon"

        let RandomPosNmbr = arc4random() % 4

        switch RandomPosNmbr{
        case 0:
            pentagon.position.x = 0
            var PositionY = arc4random_uniform(UInt32(frame.size.height))
            pentagon.position.y = CGFloat(PositionY)
            self.addChild(pentagon)
            break
        case 1:
            pentagon.position.x = frame.size.width
            var PositionY = arc4random_uniform(UInt32(frame.size.height))
            pentagon.position.y = CGFloat(PositionY)
            self.addChild(pentagon)

            break
        case 2:
            pentagon.position.y = 0
            var PositionX = arc4random_uniform(UInt32(frame.size.width))
            pentagon.position.x = CGFloat(PositionX)
            self.addChild(pentagon)
            break
        case 3:
            pentagon.position.y = frame.size.width
            var PositionX = arc4random_uniform(UInt32(frame.size.width))
            pentagon.position.x = CGFloat(PositionX)
            self.addChild(pentagon)
            break
        default:

            break
        }

        pentagon.runAction(SKAction.moveTo(MainBall.position, duration: 2.5))
        let delay3 = 2.5 * Double(NSEC_PER_SEC)
        let time3 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay3))
        dispatch_after(time3, dispatch_get_main_queue()) {
            pentagon.removeFromParent()
        }

    }
    func CircleSpawn(){

        let circle = SKSpriteNode(imageNamed: "BlueCircle.png")
        circle.size = CGSizeMake(35, 35)
        circle.physicsBody = SKPhysicsBody(circleOfRadius: circle.size.width/2)
        circle.physicsBody?.categoryBitMask = PhysicsCategory.circle
        circle.physicsBody?.contactTestBitMask = PhysicsCategory.bullet | PhysicsCategory.MainBall
        circle.physicsBody?.collisionBitMask = PhysicsCategory.bullet | PhysicsCategory.MainBall
        circle.physicsBody?.dynamic = true
        circle.physicsBody?.affectedByGravity = false
        circle.name = "circle"

        let RandomPosNmbr = arc4random() % 4

        switch RandomPosNmbr{
        case 0:
            circle.position.x = 0
            var PositionY = arc4random_uniform(UInt32(frame.size.height))
            circle.position.y = CGFloat(PositionY)
            self.addChild(circle)
            break
        case 1:
            circle.position.x = frame.size.width
            var PositionY = arc4random_uniform(UInt32(frame.size.height))
            circle.position.y = CGFloat(PositionY)
            self.addChild(circle)

            break
        case 2:
            circle.position.y = 0
            var PositionX = arc4random_uniform(UInt32(frame.size.width))
            circle.position.x = CGFloat(PositionX)
            self.addChild(circle)
            break
        case 3:
            circle.position.y = frame.size.width
            var PositionX = arc4random_uniform(UInt32(frame.size.width))
            circle.position.x = CGFloat(PositionX)
            self.addChild(circle)
            break
        default:

            break
        }

        circle.runAction(SKAction.moveTo(MainBall.position, duration: 2.4))
        let delay3 = 2.4 * Double(NSEC_PER_SEC)
        let time3 = dispatch_time(DISPATCH_TIME_NOW, Int64(delay3))
        dispatch_after(time3, dispatch_get_main_queue()) {
            circle.removeFromParent()
        }

    }

}

A: Your circleDelay has an opening {, then the dispatch_after has an opening { and closing }. But your circleDelay has no closing }. Therefore the following function declaration of moveDelay is happening in the scope of circleDelay and is not available outside that method scope.
There might be something else wrong with your code, but it is hard to tell since you do not properly indent your code, you not following the the regular naming guidelines, e.g. camel case for variable names.
Aaaand you posted too much code. Therefore take my first found error, fix that, properly indent your code and then come back and post a second question where you ask about one specific error.


text:
Q: Pcbnew for Kicad cannot be imported in python3.5 I just started learning to customize my foorprint in Kicad via python scripts. I got stuck on "import pcbnew" because it gave me the error "no module name pcbnew" all the time. I checked my Kicad folder and found all the py examples for script foorprint wizard, but there's no file named "pcbnew.py".
I'm wondering if it's because I'm using python3.5 rather than python2.7 and how can I fix this problem. Should I download the pcbnew script from somewhere like Kicad Github (I searched a lot but didn't find any really helpful solutions…)? Or should I re-install my Kicad or python? My Kicad version is 5.0.
Thanks a lot!

A: Kicad includes it own version of Python (Version 2.7.13 at time of writing for Kicad 5.1 but moving to python 3 shortly). You can access Kicad python via the Pcbnew python terminal Tools > Scripting console.
If you wish to run a script you have a couple of options.

*

*Run it using the inbuilt python 2.7 using either the scripting console or specifying the Kicad python version in the shebang line (you will have to search for this but, in macOS, for instance it is found in /Applications/Kicad/kicad.app/Contents/Frameworks/Python.framework/Versions/Current/bin/python)

*Import the kicad site-packages into the python environment you are using.
import sys
sys.path.insert(0,"/Applications/Kicad/kicad.app/Contents/Frameworks/python/site-packages/")
import pcbnew

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do to put elements of different sizes immediately on top of one another? The following program segment generates the output within the red box as shown in the figure:
st = c.con.createStatement();
rs = st.executeQuery("SELECT itemName, itemMaxQty, itemImage FROM item");

while(rs.next()){
    JPanel itemPanel = new JPanel();

    itemPanel.setLayout(new BoxLayout(itemPanel, BoxLayout.PAGE_AXIS));
    JPanel componentPanel = new JPanel();
    componentPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    JLabel itemName = new JLabel(rs.getString(1));
    ImageIcon itemImage = new ImageIcon(rs.getString(3));
    Image scaleImage = itemImage.getImage().getScaledInstance(120, 120, Image.SCALE_SMOOTH);
    JLabel imageHolder = new JLabel(new ImageIcon(scaleImage));
    JSpinner quantityField = new JSpinner();
    Dimension d = quantityField.getPreferredSize();
    d.width = 60;
    d.height = 30;
    quantityField.setPreferredSize(d);

    componentPanel.add(imageHolder);
    componentPanel.add(quantityField);
    itemPanel.add(componentPanel);
    itemPanel.add(itemName);

    add(itemPanel);
}

I know that probably some parts of the code are not the best way to do it, but that is what I can do for now in line with the knowledge that I have.
I actually have two problems here.
First, I don't understand why the itemName's value (Cupcake Stand, chafers, etc) are centred.
1. How do I make it left centred such that it is aligned with its corresponding picture on top?
Second, as you can see, there is a large space in between the componentPanel (the picture and the JSpinner) and the itemName. I think it's because the height allotted for itemName is the same as that for the componentPanel. So
2. How do I make itemName immediately below the componentPanel?

A: You can do that by changing the LayoutManager of itemPanel to BorderLayout (with that line itemPanel.setLayout(new BorderLayout());), and add the component to itemPanel in that way:
itemPanel.add(componentPanel, BorderLayout.CENTER);
itemPanel.add(itemName, BorderLayout.SOUTH);


text:
Q: Total Number of Imaps and Multimaps Hazelcast Is there a limit on the total number of iMaps and Multimaps that can be created?
I have created around 100k small maps, the memory occupied seems high compared to a few large maps having the same data.
hazelcast verion :4.0.2

A: Creating any object in Hazelcast consumes some heap memory. With the Enterprise edition of Hazelcast, the data for maps may be off-heap, but there is still the map itself on-heap. This is common to any java object.
There's no hard limit, but you may find that the memory pressure becomes excessive.
I'd like to know why you have that many maps - there may be another approach to your application. Have you looked at MultiMaps? Hazelcast supports these and this will support many key-to-collection-of-values mappings.


text:
Q: AWS Python script (Rekognition) working when called from command line, but not automatically i am working on a script which uploads pictures to S3 and then adds that picture to a rekognition collection. When i run this script from the command line everything works perfectly - no issues. However, when the system executes it automatically (the script runs whenever a new file is added to the specified upload folder) the rekognition portion of the code does not run. Everything up through os.remove works fine automatically, but i can't get the images added to the collection. After days of messing with the code i am looking for some help - please let me know if i am missing something here.
After messing around with the script a bit and debugging it is client=boto3.client('rekognition') which for some reason does not allow the script to run. Any thoughts on why that would be?
import boto3
import os

#Get file name of newly uploaded picture
path = "/var/www/html/upload/webcam-capture/"
files = os.listdir(path)
for name in files:
 #Split up file name for proper processing
 components = name.split('-')
 schoolName = components[0]
 imageType = components[1]
 idNumber = components[2]

 # Upload files to  bucket with Python SDK
 s3 = boto3.resource('s3')
 s3.meta.client.upload_file(path + name, schoolName + '-' + imageType + '-' + 'media.XXX.school', idNumber)

 # Delete file from webcam-capture temp folder
 os.remove (path+name)

 #Add Face to Facial Recognition Collection
 collection_id = schoolName + '-' + imageType
 bucket= collection_id + '-media.XXX.school'
 client=boto3.client('rekognition')
 response=client.index_faces(CollectionId=collection_id,Image={'S3Object':{'Bucket':bucket,'Name':idNumber}},MaxFaces=1,QualityFilter="AUTO",DetectionAttributes=['ALL'])```


text:
Q: Servidor wildfly Standalone do wildfly
<interfaces>
        <interface name="management">
           <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
        </interface>
        <interface name="public">
            <any-address/>
        </interface>
        <interface name="unsecure">
            <inet-address value="${jboss.bind.address.unsecure:127.0.0.1}"/>
        </interface>
    </interfaces>

    <socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
        <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
        <socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9993}"/>
        <socket-binding name="ajp" port="${jboss.ajp.port:8009}"/>
        <socket-binding name="http" port="${jboss.http.port:8100}"/>
        <socket-binding name="https" port="${jboss.https.port:8443}"/>
        <socket-binding name="txn-recovery-environment" port="4712"/>
        <socket-binding name="txn-status-manager" port="4713"/>
        <outbound-socket-binding name="mail-smtp">
            <remote-destination host="localhost" port="25"/>
        </outbound-socket-binding>
    </socket-binding-group>

Acesso somente localhost. Não consigo acessar em outro local. Precisa configurar mais algo ?
A porta 8100 e 9990, está liberada no firewall do windows server 2008.

A: Geralmente você precisa mexer no wildfly.conf e editar a variável de ambiente JBOSS_OPTS para que ele "escute" outras interfaces; para que ele responda em todas é algo assim:
JBOSS_OPTS="-b 0.0.0.0 -bmanagement=0.0.0.0"

Estes parâmetros são utilizados quando o servidor é iniciado.


text:
Q: webpack less is not working I'm using the yo fluxible generator by yahoo (following http://fluxible.io/quick-start.html).
I made a new folder called assets and inside it I have another folder called styles which will have my .less files.
So,
 [Project]
 |
 +-- [assets]
     |
     +-- [styles]
         |
         +-- main.less
         |
         +-- componentOne.less
 +-- [components]
     |
     +-- App.js
     |
     +-- ComponentOne.js
 |
 +-- webpack.config.js

Here's what my webpack.config.js looks like:
var webpack = require('webpack');
var path = require('path');

var webpackConfig = {
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    entry: [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        './client.js'
    ],
    output: {
        path: path.resolve('./build/js'),
        publicPath: '/public/js/',
        filename: 'main.js'
    },
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                loaders: [
                    require.resolve('react-hot-loader'),
                    require.resolve('babel-loader')
                ]
            },
            { test: /\.json$/, loader: 'json-loader'},
            {
                test: /\.less$/,
                loader: "css!less"
              }
        ]
    },
    node: {
        setImmediate: false
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify(process.env.NODE_ENV)
            }
        })
    ],
    devtool: 'eval'
};

module.exports = webpackConfig;

However, I get the following error when I npm run dev:

module.js:340
      throw err;
      ^
Error: Cannot find module './main.less'
      at Function.Module._resolveFilename (module.js:338:15)
      at Function.Module._load (module.js:289:25)
      at Module.require (module.js:366:17)
      at require (module.js:385:17)
      at Object. (/home/userOne/Development/reactjs/fluxible/fluxible-posts/components/Home.js:2:1)
      at Module._compile (module.js:435:26)
      at normalLoader (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babel-core/lib/api/register/node.js:199:5)
      at Object.require.extensions.(anonymous function) [as .js] (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babel-core/lib/api/register/node.js:216:7)
      at Module.load (module.js:356:32)
      at Function.Module._load (module.js:313:12)

Here is Home.js component:
import React from 'react';
require('../assets/styles/main.less');

class Home extends React.Component {
    render() {
        return (

Home

Welcome to the site!

        );
    }
}

export default Home;

Thanks to @zerkms, I installed the less module.  However, the following now happens:
/home/userOne/Development/reactjs/fluxible/fluxible-posts/assets/styles/main.less: Unexpected token (1:1)
> 1 | p{color:red;}
    |  ^
    at Parser.pp.raise (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/parser/location.js:24:13)
    at Parser.pp.unexpected (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/parser/util.js:82:8)
    at Parser.pp.semicolon (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/parser/util.js:69:81)
    at Parser.pp.parseExpressionStatement (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/parser/statement.js:427:8)
    at Parser.parseExpressionStatement (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/plugins/flow.js:642:20)
    at Parser.pp.parseStatement (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/parser/statement.js:142:21)
    at Parser.parseStatement (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/plugins/flow.js:621:22)
    at Parser.pp.parseTopLevel (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/parser/statement.js:30:21)
    at Parser.parse (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/parser/index.js:70:17)
    at Object.parse (/home/userOne/Development/reactjs/fluxible/fluxible-posts/node_modules/babylon/lib/index.js:45:50)


text:
Q: How to pass data to modal from controller in rails? I have a controller and i want to send some data from my controller to modal. How can I achive that?
this is my contoller - customers_controller.rb
def hours_approved
    @project = Project.find params[:project_id]
    respond_to do |format|
      format.js { render :file => "/customers/hours_approved.js.erb"}
    end
  end

hours_approved.js.erb
$('#hours_approved').html("<%= j render partial: 'hours_approved_modal' %>");
$('#hoursapproved').modal('show');

this is my modal file- hours_approved_modal.html.slim
iv class="modal fade" id="hoursapproved" tabindex="-1" role="dialog" aria-hidden="true"
    div class="modal-dialog" role="document"
        div class="modal-content" style="left:-240px;"
            div class="modal-header" style="padding:0px;"
                h1 Hours Approved
                button type="button" class="close" data-dismiss="modal" aria-label="Close"
                span aria-hidden="true" ×
           div class="modal-body"
               *i want to use here*

i want to pass @project from controller to my modal 'hours_approved_modal.html.slim' and use this to fetch values.How can I do that?
EDIT 1: if i use this inside my js file
$('#hours_approved').html("<%= j render partial: 'hours_approved_modal', projects: @projects%>");
$('#hoursapproved').modal('show');

it gives this error-
undefined local variable or method `projects' for #<#<Class:0x0055bc4c9b0998>:0x0055bc505bc180>
Did you mean?  @projects

EDIT 2: this is how i want to use in modal body
div class="modal-body"
                 table class="display" width="100%" cellspacing="0"
                  thead
                    tr
                      th Project Users
                  tbody
                      - projects.each do |project|
                      tr
                        td = project.name

A: You must use locals to pass the variable along
render partial: 'hours_approved_modal', locals: { projects: @projects }

This way you have access to it in your .slim file as projects

A: $('#hours_approved').html("<%= j render partial: 'hours_approved_modal', projects: @projects %>");
Now, inside your modal, there is a projects variable, which contains the data of @projects
Also, please rename your hours_approved_modal.html.slim file to _hours_approved_modal.html.slim with a _ in front. Otherwise, it'll not be recognised as a partial.


text:
Q: how to make this union query more effecient? I've created the SQL query below, using a UNION join.
As you can see, I query the same table 2 times, with slightly different criteria. If TYP is A then it's an Offer. If TYP is N and AB is true, then it's an order.
The whole thing works. But I'm guessing there's a more elegant way to do this? I'm hoping you can tell me what that way is! :)
Thanks.
(btw, using advantage sql if it makes a difference)
SELECT
DATUM as report_month,
REGION as region,
count(DISTINCT NUMMER) as order_number,
'Offer' as Type
from xxxxxxxxxxxx
left join xxxxxxxxx on KDNR = anotherDAB.KDNR
WHERE DATUM = '2021-02-16' AND TYP = 'A'
group by report_month, region

UNION

SELECT
DATUM as report_month,
REGION as region,
count(DISTINCT NUMMER) as order_number,
'Order' as Type
from xxxxxxxxxxx
left join xxxxxxxxx on KDNR = anotherDAB.KDNR
WHERE DATUM = '2021-02-16' AND TYP = 'N' AND AB = true
group by report_month, region

A: I suspect you just want conditional aggregation:
SELECT DATUM as report_month, REGION as region,
       count(DISTINCT NUMMER) as order_number,
       typ
from xxxxxxxxxxxx left join
     xxxxxxxxx
     on KDNR = KDNR
WHERE DATUM = '2021-02-16' AND
      (TYP = 'A' OR TYP = 'N' AND AB = true)
GROUP BY report_month, region, type;

The above leaves TYP as A or N.  You can use a case expression if you want strings:
(CASE WHEN typ = 'A' THEN 'Offer' ELSE 'Order' END)


text:
Q: Showing same infowindow for every marker google maps api I am using Google Maps API, I would like to show an infowindow for every marker.
But the problem is the same content is showing for every marker infowindow. i.e., the last string of an array is showing in infowindow even though I have used function bindInfoWindow() it is not working:
I am using Google Maps API, I would like to show an infowindow
for every marker.
But the problem is the same content is showing for every marker infowindow.i.e., the last string of an array is showing in infowindow even though I have used function bindInfoWindow() it is not working:
var poly;
var map;
var infodatajson = [
  17.4172192, 78.401285,
  17.418407, 78.401629,
  17.418090, 78.400610,
  17.417865, 78.398234
];

// for center the map
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center: {
      lat: 17.4172192,
      lng: 78.401285
    }
  });

  // for polyline
  var flightPlanCoordinates = new Array();

  for (i = 0; i < infodatajson.length; i += 2) {
    var point = new google.maps.LatLng(infodatajson[i], infodatajson[i + 1]);
    flightPlanCoordinates.push(point);
  }

  poly = new google.maps.Polyline({
    path: [new google.maps.LatLng(17.4172192, 78.401285),
      new google.maps.LatLng(17.418407, 78.401629),
      new google.maps.LatLng(17.418090, 78.400610),
      new google.maps.LatLng(17.417865, 78.398234)
    ],
    geodesic: true,
    strokeColor: '#0000FF',
    strokeOpacity: 1.0,
    strokeWeight: 3,
  });

  var infowindow;
  var infodata;
  var marker;

  // for markers
  for (var i = 0, ln = infodatajson.length; i < ln; i += 2) {

    infodata = infodatajson[i] + ", " + infodatajson[i + 1];

    marker = new google.maps.Marker({
      position: new google.maps.LatLng(infodatajson[i], infodatajson[i + 1]),
      map: map,
      title: infodatajson[i] + ", " + infodatajson[i + 1],
    });

    infowindow = new google.maps.InfoWindow({});

    //function bindInfoWindow(marker, map, infowindow, infodata) {
     marker.addListener('click', function() {
     infowindow.setContent(infodata);
     infowindow.open(map, this);
   });
    //}
  }

  poly.setMap(map);
}

A: instead of your bindInfoWindow() function, use this
google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(infodata);
    infowindow.open(map, this);
    });


text:
Q: Want to convert big numbers into exact number string const num = 100000000000000000000001

console.log(num.toString()) //1.0000000000000001e+23
console.log(num.toLocaleString('fullwide', { useGrouping: false })) //100000000000000010000000

I want to convert num in to exact string like 1000000000000000000001. I tried these two methods but non of them works. At last I want to split these individual digits into an array and array doesn't works on number that's why i want to convert it to exact string.

A: Since ECMAScript 2020 you can use bigint data type, which will have a toString() method that works as you want it.

// note the "n" which denotes this is a bigint
const num = 100000000000000000000001n;
// verify it's a bigint
console.log(typeof num);
// print the number
console.log(num.toString());
// put inidividual digits in array
console.log(num.toString().split(""));


text:
Q: Adding additional hot swap drive to HP ProLiant DL360 in RAID1 config I have a HP ProLiant DL360p Gen8 server. It has 8 drive bays with only 6 being used in a RAID1 config.
Can I add an additional 2 drives to the empty bays hot and the HP Smart Array Controller will configure them automatically into the RAID and they'll appear as one logical drive or do I have to power down the server and configure them manually in the HP Intelligent Provisioning utility like I did with the original 6 drives?

A: You can do this live with the HP Smart Storage Administrator utility for your operating system.
The process is called an array transformation.


text:
Q: How to split array of object to individual arrays I'm developing an angular application where I call the following endpoint from CoinGeko API that provides me market charts:
https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=cad&days=7&interval=daily
It returns an like the following:
{
    "prices": [
        [
            1643414400000,
            48329.41585141156
        ],
        [
            1643494489000,
            48870.92050262988
        ]
    ],
    "market_caps": [
        [
            1643414400000,
            915485662636.434
        ],
        [
            1643494489000,
            925791491728.014
        ]
    ],
    "total_volumes": [
        [
            1643414400000,
            24532182816.548737
        ],
        [
            1643494489000,
            18070713602.083645
        ]
    ]
}

From this response, I need to work on the "prices" property only.
It is an array of arrays with UNIX timestamp and the Crypto price.
So what I'm trying to reach is to have two different arrays where:

*

*the first one includes only the dates

*second one includes only the prices

The following snippet show my attempt:
Interfaces.ts
export interface Chart {
    prices:        Array<DatePrice>;
    market_caps:   Array<DatePrice>;
    total_volumes: Array<DatePrice>;
}

export interface DatePrice {
    unixDate: string[];
    price: number[];
}

Component.ts
[...]

coinChart: Chart[];
sevenDayPrices: number[];
sevenDayDates: Date[];

ngOnInit() {
    this._apiService
        .getWeeklyChartData()
        .subscribe(chartData => {
             this.coinChart = chartData;
             console.log(chartData);

             chartData.map(x =>
                 x.prices.map(daysPrice => {
                     console.log(daysPrice.price);
                     this.sevenDayPrices = daysPrice.price
                 })
             );
  }

Unfortunately it doesn't work. What I would to achive is something like:
sevendayprices = [48329.4158514115, 48870.92050262988]
sevendaydates = [1643414400000, 1643494489000]

How can I reach this goal?
~SRJ

A: Looks like what you're doing is pretty much fine. As for the solution, you're receiving Array of arrays, and your Chart interface already contains that. You'd be much better using Array rather than another DatePrice interface bc you don't need it. So first thing first, fix this:
//this is wrong
coinChart: Chart[];
//use this instead
coinChart: Chart;
//since you want in readable date, use
sevenDayDates: string[];//instead of date

Here goes the easiest logic to split both arrays:
ngOnInit() {
    this._apiService
        .getWeeklyChartData()
        .subscribe(chartData => {
             this.coinChart = chartData;
             this.sevenDayDates = this.coinChart.prices.map(function(tuple) {
        return  new Date(tuple[0]).toLocaleTimeString()
          });
          this.sevenDayPrices = this.coinChart.prices.map(function(tuple) {
            return  tuple[1]
          });
  }

Let me know if that works. If your interface is proper, you can literally use all these properties in your chartData response. And I hope in the API call, you're returning Chart type rather than Chart[] type.

A: If I understand your needed well, the following snippet could do the trick:
const response = {
    prices: [
        [
            1643414400000,
            48329.41585141156
        ],
        [
            1643494489000,
            48870.92050262988
        ]
    ],
    market_caps: [
        [
            1643414400000,
            915485662636.434
        ],
        [
            1643494489000,
            925791491728.014
        ]
    ],
    total_volumes: [
        [
            1643414400000,
            24532182816.548737
        ],
        [
            1643494489000,
            18070713602.083645
        ]
    ]
}

...
// Interface
export interface MyObjInterface = {
  prices: string[],
  dates: string[]
}

...
// inside class, above constructor()
myPrices: number[]
obj: MyObjModel

ngOnInit() {
  this.myPrices = response.prices.flat()
  this.obj = {
  prices: this.checkDotInNumber(myPrices, true),
  dates: this.checkDotInNumber(myPrices, false)
}

  console.log(this.obj)
}

checkDotInNumber(arr, hasDot): string[] {
  const a = arr.flat();
  let includeDot = (num) => {
    return num.toString().includes('.')
  }

  return (hasDot) ? a.filter(x => includeDot(x)) : a.filter(x => !includeDot(x))
}

##Explanation:##
You receive an object as response, so you can access to "prices" property just navigating to "response.prices" (with "response" I refer to my object that is the same that you have in your subscription: chartData).
Having "response.prices" you can do some operation on the array and create a new object that I named "this.obj" with two properties: "prices" with the prices array, and "dates" with dates array.
##Why I've created a new object?##
Because "this.myobj" can be destructured so you can quickly and easy access to its property when you need them. So for example:
const {prices, dates} = this.myobj

console.log(prices, dates);

##Hint##:
The object returns two array of string, so if you need to work with number you need to convert elements array to number again.
##UPDATE:##
Based on The Fool comments, he is right, the performance is important, by the way is important find a compromise between performance and readability.
So my other suggestion to achive your goal is:
const mapper = new Map(response.prices);
const prices = Array.from(mapper.values());
const dates = Array.from(mapper.keys());

console.log(dates, prices)

I find this way simpler, fastest and more readable.


text:
Q: How to display HTML code in UIWebView? I have HTML code that I get from a  web service - it has style tags,(CSS I think)  images and that sort of thing. I want to display it in a web view and have the remote images load as well as all the styling.
I've tried to set it like this:
    [self.webView setBackgroundColor:[UIColor clearColor]];

NSMutableString *myString = [NSMutableString stringWithString:self.itemDecription];

[myString replaceOccurrencesOfString:@">" withString:@">" options:NSLiteralSearch range:NSMakeRange(0, [myString length])];
[myString replaceOccurrencesOfString:@"<" withString:@"<" options:NSLiteralSearch range:NSMakeRange(0, [myString length])];

[self.webView loadHTMLString:myString baseURL:nil];

However the web view just shows text without any styling and images don't load.

A: Try this one:
 NSString *myFile = [[NSBundle mainBundle] pathForResource:@"tag" ofType:@"html"];
 NSString* myString = [NSString stringWithContentsOfFile:myFile encoding:NSUTF8StringEncoding error:nil];
 [webView loadHTMLString:myString baseURL:nil];


text:
Q: PHP/CODEIGNITER:Trying to get property of non-object I got this error and cant fix it help me please

Message: Trying to get property of non-object

Filename: controllers/auth.php
Line Number: 20
and this is my code:
 The line 20 starts at if ($user->mail){
if ($user->mail) {
            $this->session->set_flashdata("Success","You Are now logged in");

            $_SESSION['user_logged'] = TRUE;
            $_SESSION['username']=$user->username;
        }
        else {
            $this->session->set_flashdata("error", "No Account exists in Database");
        }
    }

A: The most likely cause of the error message is that $user is null.

A: Well as the error is self explanatory, you are using:
$user->mail
$user->username

But according to the error $user is not an object and as such you can not get property of non-object. So try to figure out what exactly are you doing with $user, returning an object or an array.


text:
Q: C, Why is my 'px' variable zero? Ok, the bug is strange and I have no idea what's going on.
I'm running my code on an at90usb1286.
Here's the problematic code:
        uint16_t r = rand();
        t1 = r;

        px = r%52;
        t2 = px;

        py = r%28;
        t3 = py;

        px = px * 6;
        t4 = px;

        py = py * 8;
        t5 = py;

        py += 8;

Context:
The t# variables are temporary variables I am using to debug this...
They are displayed on a connected display. px and py are just global uint16_ts.
The Bug:
All t# variables except t4 display sensible values, but t4 remains 0 no matter what value is displayed for t2.
Why!!!?
It's been screwing with my mind for hours! :'(
Thanks for any advice! :)
I know this probably isn't a good way to use random's though :P
(I've tagged arduino as I suspect it may be similar)
Rest of the code:
(I have tried with the global vars non-static aswell)
#include "util/cli.h"
#include "drivers/lcd/syscalls.h"
#include "drivers/input/syscalls.h"
#include "drivers/led/syscalls.h"
#include "drivers/scheduler/syscalls.h"
#include <util/delay.h>

static int x = 0, y = 0;

static int px;
static int py; /*Pickup*/

static uint16_t score = 0;

static uint8_t dir; /*0 -> NESW <- 3*/

static uint16_t t1, t2, t3, t4, t5;

void render_thread() {
    lcd_clear_screen();

    while(1) {
        cli();
        lcd_display_char_xy(' ', x, y);
        if(dir & 0x01)
            y -= 8;

        if(dir & 0x02)
            x += 6;

        if(dir & 0x04)
            y += 8;

        if(dir & 0x08)
            x -= 6;

        if(x < 0)
            x = 0;
        if(y < 8)
            y = 8;
        if(x > 312)
            x = 312;
        if(y > 232)
            y = 232;

        lcd_display_char_xy('.', px, py);
        lcd_display_char_xy('@', x, y);
        /*Display score*/
        lcd_display_move(0, 0);
        lcd_display_hex(&score, 2);

        /*Display test variables*/
        lcd_display_move(60, 0);
        lcd_display_hex(&t1, 2);
        lcd_display_move(100, 0);
        lcd_display_hex(&t2, 2);
        lcd_display_move(140, 0);
        lcd_display_hex(&t3, 2);
        lcd_display_move(180, 0);
        lcd_display_hex(&t4, 2);
        lcd_display_move(220, 0);
        lcd_display_hex(&t5, 2);
        sei();
        _delay_ms(16);
    }
}

void game_thread() {
    px = 24;
    py = 32;

    while(1) {
        cli();
        if(px == x && py == y) {
            uint16_t r = rand();
            t1 = r;

            px = r%52;
            t2 = px;

            py = r%28;
            t3 = py;

            px = px * 6;
            t4 = px;

            py = py * 8;
            t5 = py;

            py += 8;
            score++;
        }
        sei();
        scheduler_switch();
    }
}

void user_thread() {
    while(1) {
        if(switch_north())
            dir |= 1;
        else
            dir &= 0x0E;

        if(switch_east())
            dir |= 1<<1;
        else
            dir &= 0x0D;

        if(switch_south())
            dir |= 1<<2;
        else
            dir &= 0x0B;

        if(switch_west())
            dir |= 1<<3;
        else
            dir &= 0x07;

        scheduler_switch();
    }
}

void cli_start() {
    Task* game_task = scheduler_create_task(game_thread, 128);
    scheduler_submit_task(game_task);

    Task* render_task = scheduler_create_task(render_thread, 128);
    scheduler_submit_task(render_task);

    Task* user_task = scheduler_create_task(user_thread, 128);
    scheduler_submit_task(user_task);
}

A: Your initial value of rand() is probably divisable by 52 (as suggested by Lashane).  First of all try to make sure you call srand() if you are using -- BUT do make sure you are calling it exactly and only ONCE.  For simple applications you can use the time() value for seeding into srand, however for more secure applications you should find something to seed with that cannot easily be guessed.
You always have the risk of the value be divisable by 52, so if zero is an undesirable values use
px = (r%51)+1;

to make sure that the values returned are between 1 and 51

A: You are creating 3 threads, BUT YOU ARE NOT TAKING CARE ABOUT WRITE MEMORY COLLISIONS.
Two threads are using px: game_thread and render_thread, maybe lcd_display_char_xy in render_thread takes px referenced, and modifies it in a unspected time.
I suggest you try using a "int pxg" for exclusive use of game_thread and other "int pxr" for exclusive use in render_thread (and remove int px). It must solve the problem.
Or, just for test, you could comment lcd_display_char_xy('.', px, py);, and px in game_thread must work in expected way.

A: Well it seemed to be an optimisation issue. I was initially using the optimisation flag -Os and after changing it to -O3 or -Ofast it seemed to run perfectly :)
I don't know what on earth was going on with the size optimised code but it appeared that the compiler had split the game_thread code into a couple of jumbled pieces...
Thanks for the help everyone! :D


text:
Q: Remove duplicate x-values from array of tuples I want to remove items from a javascript array iff the x-value of the tuple is duplicated in the array, in which case I want to take the max y-value and trash the others.
Ex:
arr = [[0,1],[0,2],[1,1],[1,1],[2,2],[2,2],[2,4]]
filtered = [[0,2],[1,1],[2,4]]

Please help me understand if Array.prototype.filter, or Array.prototype.map etc. can fix my problem. I am trying to utilize ES6 methods rather than just simply iterating through the list in mention.

A: You can use Array.reduce() and Array.map()

var data = [[0,1],[0,2],[1,1],[1,1],[2,2],[2,2],[2,4]];
var map = data.reduce((a, arr) => a.set(arr[0], Math.max((a.get(arr[0]) || arr[1]), arr[1])), new Map());

var result = Array.from(map);
console.log(result);

A: Is this this sort of thing your after?

var arr = [[0,1],[0,2],[1,1],[1,1],[2,2],[2,2],[2,4],[5,6]]
// var filtered = [[0,2],[1,1],[2,4]]

// temp array to store key value pairs
var items = []
arr.map((item) => {
  let [x, y] = item
  // store the max value of y for this x in items
  if (typeof items[x] === 'undefined'){
    items[x] = y
  }else{
    items[x] = Math.max(items[x], y)
  }
})

var filtered = items.map((y, x) => {
  // rejoin data into x,y pairs
  return [x,y]
}).filter(a => !!a) // fitler undefined pairs

console.log(filtered)

A: For this you don't want to use filter. Filter is more for applying a boolean test to include or exclude elements. If you really wanted to use filter you could do something like
var newArr = arr.filter(function (elem)
    {
        allOtherX's = arr.filter(function(secondElem){return elem[0] == secondElem[0]});
        return elem[1] >= Math.max(...arr);
     });

However this is an ineffective way of doing this since you will be repeating alot of calulcations. I would recommend instead dividing the list into a bunch of lists based off of x-values.Such as
var buckets = {};
arr.map(function(elem)
        {
           if(typeof(buckets[elem[0]]) == 'undefined')
                 buckets[elem[0]] = [];
           buckets[elem[0]].push(elem[1]);
           return elem; // Unneccessary
         });
var newArr = Object.keys(buckets).map(function (x)
         {
            return [x,Math.max(...buckets[x])];
         });

A: A cleaner alternative: you can use reduce to aggregate the intermediary hash where key is x and value is y, and then convert it to the desired filtered array:
const arr = [[0,1],[0,2],[1,1],[1,1],[2,2],[2,2],[2,4]];

const dataObj = arr.reduce((all, [x,y]) => {

    all[x] = Math.max(y, all[x] || 0);

    return all;

}, {});

const filtered = Object.keys(dataObj).map(x => [Number(x), dataObj[x]]);

console.log(filtered);


text:
Q: Transform or change values of columns in based on values of others columns I have a dataframe that contains 5 columns. What I would like to do is to change the last 4 columns to the first column.
Basically if the value of the first column is below a certain threshold, the following columns are modified and if this value is higher than the threshold there is no change.
So I tried this :
import pandas as pd
df = pd.DataFrame({
  'col1' : [0.1, 0.3, 0.1, 0.2],
  'col2' : [2,4,3,7],
  'col3' : [3,4,4,9],
  'col4' : [4,2,2,6],
  'col5' : [0.3, 2.1, 1.0, .9],
})

def motif(col1, col2, col3, col4, col5):
  col2 = col2
  col3 = col3
  col4 = col4
  col5 = col5
  if col1 <=.15:
    col2 = col2 * .15
    col3 = col3 * .15
    col4 = col4 * .15
    col5 = col5 * .15
    return col2, col3, col4, col5
  else:
    return col2, col3, col4, col5

df.apply(lambda x: modify(x[col1], x[col2], x[col3], x[col4], x[col5]), axis=1)

But this does not work.
If you have any ideas I would be very grateful

A: We can use loc to select rows where col1 is less than or equal to .15 then multiply the rest of the columns by .15:
df.loc[df['col1'] <= 0.15, 'col2':] *= 0.15

df:
   col1  col2  col3  col4   col5
0   0.1  0.30  0.45   0.6  0.045
1   0.3  4.00  4.00   2.0  2.100
2   0.1  0.45  0.60   0.3  0.150
3   0.2  7.00  9.00   6.0  0.900

Naturally other column selections work if all columns after col2 is overly broad:
df.loc[df['col1'] <= 0.15, ['col2', 'col3', 'col4', 'col5']] *= 0.15

df.loc[df['col1'] <= 0.15, 'col2':'col5'] *= 0.15

The mask can also be saved and reused if different columns need different modifications:
m = df['col1'] <= 0.15
df.loc[m, 'col2':'col4'] *= 0.15
df.loc[m, 'col5'] *= 0.5  # col5 is different than col2-4

df:
   col1  col2  col3  col4  col5
0   0.1  0.30  0.45   0.6  0.15
1   0.3  4.00  4.00   2.0  2.10
2   0.1  0.45  0.60   0.3  0.50
3   0.2  7.00  9.00   6.0  0.90

The apply can work (although it is slower and a lot more code), but since apply can produce both aggregated and unaggregated results the overwritten columns will need explicitly defined and the result needs to be a Series not a tuple:
def modify(col1, col2, col3, col4, col5):
    if col1 <= .15:
        col2 = col2 * .15
        col3 = col3 * .15
        col4 = col4 * .15
        col5 = col5 * .15
    return pd.Series([col2, col3, col4, col5])

df[['col2', 'col3', 'col4', 'col5']] = df.apply(lambda x: modify(
    x['col1'], x['col2'], x['col3'], x['col4'], x['col5']
), axis=1)

df:
   col1  col2  col3  col4   col5
0   0.1  0.30  0.45   0.6  0.045
1   0.3  4.00  4.00   2.0  2.100
2   0.1  0.45  0.60   0.3  0.150
3   0.2  7.00  9.00   6.0  0.900


text:
Q: AnyLogic - Why does my condition based transition not work?
I have a question related to a transition in my statechart (see image above). I have a variable called palletInUse which is a boolean-type and changes between true and false. For one transition in my statechart I want it to change when the variable palletInUse has the value true. I have tried it with for example:
palletInUse == true;

and also tried different code like, equals and contentEquals etc. but nothing seems to work. Do you have a solution for this, seemingly simple problem?
Thanks in advance

A: The condition is not monitored constantly, only when something is changed in the agent. When you assign a new value to variable with common "=" Java operator, it is not caught by the AnyLogic engine. You need to call onChange() function after that. Then, the transition should be executed.
There are other ways to trigger the condition check without explicit onChange() call. You may find them in AnyLogic Help article.
BTW, you may specify just boolean variable as the condition, it is not required to compare it with true or false:
palletInUse

A: The condition is not evaluated if nothing is happening, for that reason you have to make something happen constantly to have your condition evaluated. A typical way of doing is as you see in the following pictures:


text:
Q: Shared Server cum VPS I am working on dynamic web application for hosting on Internet. Since this is a java based application, so Tomcat server is required on hosting.
So, can anyone please tell me about Shared VPS server, for deployment of .war? And how to configure Tomcat on shared VPS?


text:
Q: How to embed verbatim in pspicture? I'm trying to insert a QR code at the beginning of my thesis with the contents being the BibTeX entry for it.
Any way of embedding the raw text in \psbarcode?
\documentclass[a4paper,12pt]{minimal}

\usepackage[utf8]{inputenc}
\usepackage{pst-barcode}
\usepackage{auto-pst-pdf}

\begin{document}
  \begin{pspicture}(1.378in, 1.5in)
    \psbarcode{
      \begin{verbatim} % won't work
@MastersThesis{,
  author = {J\'ulio ...},
  title = {...},
  year = {...},
  ...
}
      \end{verbatim}
    }{}{qrcode}
  \end{pspicture}
\end{document}

It seems the fancyvrb package provides a BVerbatim environment for this.

A: I don't think you want verbatim anyway as you also need to take care of PostScript quoting such as \\ for \.

which an online decoder says is
Raw text    @MastersThesis{, author = {J\'ulio ...}, title = {...}, year = {...}, ... }
Raw bytes   44 d2 04 04 d6 17 37 46 57 27 35 46 86 57 36 97 37 b2 c2 06 17 57 46 86 f7 22 03 d2 07 b4 a5 c2 77 56 c6 96 f2 02 e2 e2 e7 d2 c2 07 46 97 46 c6 52 03 d2 07 b2 e2 e2 e7 d2 c2 07 96 56 17 22 03 d2 07 b2 e2 e2 e7 d2 c2 02 e2 e2 e2 07 d2 00 ec 11 ec 11 ec 11 ec 11 ec 11 ec 11 ec
Barcode format  QR_CODE
Parsed Result Type  TEXT
Parsed Result   @MastersThesis{, author = {J\'ulio ...}, title = {...}, year = {...}, ... }

tex:
\documentclass[a4paper,12pt]{minimal}

\usepackage[utf8]{inputenc}
\usepackage{pst-barcode}
\usepackage{auto-pst-pdf}

\begin{document}
  \begin{pspicture}(1.378in, 1.5in)
    \psbarcode{
@MastersThesis{,
  author = {J\string\\'ulio ...},
  title = {...},
  year = {...},
  ...
}
    }{}{qrcode}
  \end{pspicture}
\end{document}

For newlines this works:
  \begin{pspicture}(1.378in, 1.5in)
    \psbarcode{\string\n
@MastersThesis{,\string\n
  author = {J\string\\'ulio ...},\string\n
  title = {...},\string\n
  year = {...},\string\n
  ...\string\n
}
    }{}{qrcode}
  \end{pspicture}

A: use the optional argument parse and decimal values for the characters:
\documentclass{minimal}
\usepackage[utf8]{inputenc}
\usepackage{pst-barcode}

\begin{document}
  \begin{pspicture}(1.378in, 1.5in)
    \psbarcode{%
@MastersThesis^123,author=^123J^250lio ...^125,title=^123...^125,year=^123...^125,...^125}{parse}{qrcode}
  \end{pspicture}
\end{document}

^123 decimal ASCII for {,
^125 for }, and ^250 for ú


text:
Q: Convert a list of DateTime objects to string in python I have a list of Dates returning Mondays between two dates
mondays =[datetime.date(2019, 2, 14), datetime.date(2019, 2, 21)]
How do I format this list to %Y%m%d format?
Expecting output list to be in the below format:
['20190214','20190221']
is there a way?

A: the following will work
[date_obj.strftime('%Y%m%d') for date_obj in mondays]

Output
['20190214', '20190221']


text:
Q: Passing a Rails Ruby Variable to Javascript I have a variable in my controller @data that is a very long string.  I have a javascript function that needs access to this variable. Should I do this:
$(document).ready(function(){
  var data='<%=j @data%>'
})

or should I put the string in an html data-attribute and then do something like:
<div data-stuff="<%=h @data%>">

$(document).ready(function(){
  var data=$("div").data('stuff')
})

If one is preferable, why?

A: Between your two options, the former is preferred.
But consider using the gon gem: https://github.com/gazay/gon


text:
Q: Developing for Windows Server 2003 64 bit on Windows XP 32 bit I have been developing an ASP.NET application on Windows XP Professional.  While promoting to production I have only now found out that the server is 64 bit.  I installed Oracle Client 32 bit on the server and cannot connect to Oracle.
I am using the Microsoft Provider for Oracle, and my question is, how do I get an ASP.NET application compiled on a 32 bit machine to connect to Oracle on a Windows Server 2003 64 bit machine?
EDIT:
In response to a comment on my original question, the error I am getting is "Attempt to load Oracle client libraries threw BadImageFormatException. This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed"
I have uninstalled the 32 bit client and am getting the 64 bit client installed, the problem is that the server is a production server in a DMZ and I have no access to the server myself, so I am trying to anticipate any problems I will have when the 64 bit client is installed and I try to access the ASP.NET application on the server

A: Another thing to try would be to set the app pool hosting the application to 32-bit mode.
http://extended64.com/blogs/rhoffman/archive/2005/05/10/482.aspx
This should allow a 32-bit driver to be loaded.

A: Straightforward solution : you should install the Oracle client according to the platform (x64 on a x64 machine). The reason is that your .NET application is very likely to be built in AnyCPU configuration, which means it will run as a x64 application on a x64 platform. It then can only load x64 native libraries...
Note that when it comes to Oracle, I like to use Oracle Instant Client :

*

*You don't have to install anything on the target machines (including dev boxes !).

*You can make sure that your application will run with the specific client you picked (version, x86/x64).

*You could even easily have multiple applications work with different client versions on the same computer.

*As a downside, it adds a significant weight to your application (~19Mb minimum).

Check What is the minimum client footprint required to connect C# to an Oracle database? for more information.
In your particular case, I recommend setting up a Visual Studio project that will work on x86 as well as x64 machines : check my blog post Oracle Instant Client in Visual Studio. Then here is a guidance on how to configure a WiX package for Oracle Instant Client targeting x86 or x64 machines. If you use another deployment strategy, just make sure you ship the correct client according to the target platform.


text:
Q: Get name of the child component through ActivatedRoute or any Consider My router component is as below:
{
              path: 'abc-def-ghi',
              component: ExampleComponent,
              children: [
                {
                  path: ':type',
                  component: ViewComponent,
                  children:[{
                     path: '',
                     component: HomeComponent
                  },{
                     path:':id',
                     component: InformationComponent
                  }]
                }
              ]
            }

And consider ExampleComponent has router-outlet where page get loaded based on the url.
i route to abc-def-ghi/pet/1234 or abc-def-ghi/pet . When i do console.log(this.activatedRoute.component.name) on ExampleComponent , i only get ExampleComponent. I don't get the child component. Is there a way to get the name of the actual child component loaded?


text:
Q: Thunderbird is preferred mail app, messaging menu still loads evolution
Possible Duplicate:
Is there a way to add Mozilla Thunderbird to the messaging menu?

Hi,
After installing ubuntu I setup my email in evolution, which is fine but on balance I prefer Thunderbird so I installed and set that up.
Under preferred applications I have set the mail to Thunderbird, but when I click on the icon in the top right (the mail envelope) and select mail it still loads evolution.
Is there a way to switch this to Thunderbird?

A: There is an extension that let's Thunderbird use the message indicator in Ubuntu:

But it will not delete the evolution entry, to do that you need to remove /usr/share/indicators/messages/applications/evolution
Related: How can I remove "Set Up Mail" and other entries from the message indicator?


text:
Q: MySQL update column value where else update another column value (single query) I would like to link these two queries together rather than executing them both at different times.
UPDATE `table` SET `column_one` = @value WHERE `column_one_key` = @key LIMIT 1;

and also this query;
UPDATE `table` SET `column_two` = @value WHERE `column_two_key` = @key LIMIT 1;

Something like this but can't seem to get it to work
UPDATE `table` (SET `column_one` = @value WHERE `column_one_key` = @key) || (SET `column_two` = @value WHERE `column_two_key` = @key) LIMIT 1;

Some additional information
column_one_key and column_two_key are never the same which is why you can use OR.

A: If you don't need the limit (that is, one match per key), you can do:
UPDATE `table`
     SET column_one = (CASE WHEN @key = column_one_key THEN @value ELSE column_one END),
         column_two = (CASE WHEN @key = column_two_key THEN @value ELSE column_two END)
    WHERE @key IN (column_one_key, column_two_key);

I think two updates are simpler.  And, if you do need the limit, then two updates are definitely a simpler approach.

A: Try something like this:
UPDATE `table` SET `column_one` = @value, `column_two` = @value  WHERE `column_one_key` = @key AND `column_two_key` = @key LIMIT 1;


text:
Q: Determine if Internet Explorer is in private browsing mode from extension Is it possible to detect private browsing mode on Internet Explorer using Forge Trigger.IO's framework from an extension?
EDIT
I am looking for something similar to Firefox's nsIPrivateBrowsingService or to Chrome's chrome.tabs API's incognito check.

A: Couldn't you just attempt to place a cookie (or write to local storage)?  If the cookie (and data) does not exist... then private mode is on?

A: Internet Explorer disables all browser extensions when entering private browsing mode which means that:

*

*Your extension never runs on tabs in private browsing mode.

*Instances of your extension running in other tabs are neither aware of nor can they interact with pages in private browsing mode.

The unfortunate result of this decision by Microsoft is that even if you had a method of detecting incognito status on a window [1] you wouldn't be able to do anything with that information!
[1] e.g. Writing a BHO that enumerates all desktop windows and checks for the string "InPrivate" in their titles.

A: Conclusion

*

*Extensions indeed can run on inPrivate Mode if the option (OFF by default) to enable extensions inPrivate Mode is ON.

*There is no way of getting this information using Trigger.IO's framework at this moment.


text:
Q: How to get class constant name in ruby I need get constant name from this:
class Sex
    Male = 1
    Female = 2
end

But this is perfect variant, can i get constant name at least from this:
class Sex
    self.Male = 1
    self.Female = 2
end

Few details about the problem:

*

*You can get a list of methods: Class.methods - Object.methods

*You can get a list of instance variables: instance_variables.map{|ivar| instance_variable_get ivar}

*You can get a list of constant names from Module: Module.constants
But i have no idea how I can get class constant names.

A: class Sex
  Male = 1
  Female = 2
end

This defines two constants on the Sex class. Sex is an instance of Class and the superclass of Class is Module:
c = Sex.class  # => Class
c.superclass   # => Module

You already know how to get an array of constant names as symbols from a module and since this method is inherited, you can just call it on the Sex class:
Sex.constants  # => [:Male, :Female]

I'm not sure about your second example. Assuming you mean this (read about class << self):
class Sex
  class << self
    Male = 1
    Female = 2
  end
end

This defines two constants on the singleton class of the Sex class. The method Object#singleton_class returns the singleton class of an object. After that methods, instance_variables or constants can be called in the usual way:
Sex.singleton_class.constants  # => [:Male, :Female]

A: You can use constants on Class object as well as shown below
class Sex
    Male = 1
    Female = 2
end

p Sex.constants # will return [:Male, :Female]

The reason it will work is Module happens to be base class of Class
p Sex.class.ancestors
#=> [Class, Module, Object, Kernel, BasicObject]


text:
Q: Want to insert timestamp through procedure in oracle I have this procedure
PROCEDURE insertSample
  (
    return_code_out OUT VARCHAR2,
    return_msg_out OUT VARCHAR2,
    sample_id_in IN table1.sample_id%TYPE,
    name_in IN table1.name%TYPE,
    address_in IN table1.address%TYPE
  )
  IS

  BEGIN
    return_code_out := '0000';
    return_msg_out := 'OK';

    INSERT INTO table1
    sample_id, name, address)
    VALUES
    (sample_id_in, name_in, address_in);

  EXCEPTION
    WHEN OTHERS
    THEN
      return_code_out := SQLCODE;
      return_msg_out := SQLERRM;

  END insertSample;

I want to add 4th column in table1 like day_time and add current day timestamp in it.. ho can i do that in this procedure.. thank you

A: Assuming you you have (or add) a column to the table outside of the procedure, i.e.
ALTER TABLE table1
  ADD( insert_timestamp TIMESTAMP );

you could modify your INSERT statement to be
   INSERT INTO table1
    sample_id, name, address, insert_timestamp)
    VALUES
    (sample_id_in, name_in, address_in, systimestamp);

In general, however, I would strongly suggest that you not return error codes and error messages from procedures.  If you cannot handle the error in your procedure, you should let the exception propagate up to the caller.  That is a much more sustainable method of writing code than trying to ensure that every caller to every procedure always correctly checks the return code.

A: SYSDATE will give you the current data and time.
and if you add the column with a default value you can leave your procedure as it is
ALTER TABLE table1 ADD when_created DATE DEFAULT SYSDATE;

A: Using Sysdate can provide all sorts of manipulation including the current date, or future and past dates.
http://edwardawebb.com/database-tips/sysdate-determine-start-previous-month-year-oracle-sql


text:
Q: How to compile a Mono program for Raspberry Pi Zero on Windows? I want to be able to compile a c# console app with Mono so that it will run on the Raspberry Pi Zero.  I want to do it on my Windows machine.  And after I'd like to copy/ssh the binary to the Pi Zero and just run it.
I've already done the following:

*

*Mono runtime is already installed on the Pi Zero.

*I can compile it directly on the Pi Zero and it works fine, but it's slow and, consequently, so is the dev cycle.

Is it possible or am I required to use the Mono toolchain on the destination box?

A: If your Pi Zero is all set up, then just compiling on your Windows machine with "Any CPU" setting (rather than targeting x86/x64) should do the trick, as it's just IL at that point; it gets JITted on the Pi by the Mono runtime to ARM assembly.


text:
Q: Failover and KeepAlive in Spring Integration Similarly to the question asked at How can I define a failover spring integration gateway?
I have to implement the failover feature, however my expactations are different.
I have two brokers: primary and secondary and one service that is running on the same servers either in PRIMARY or BACKUP mode. Synchronization of internal data is performed using SYNC queue.
Within the service I would like to implement following functionality with Spring Integration:

*

*Each 1Q, 2Q, 3Q, ..., 5Q queue has a receiver and 1SQ queue has a sender. Both receiver and sender operate with primary broker (already implemented in Spring using message gateway & router for sender, and service activator for receiver).

*When a message from 1Q-5Q is received a new message is sent to 1SQ (this already works). In the same time the update of internal data is sent to SYNC queue. This way the interal data structures are synchronized in case of a failover.

*external module sends to the 1Q queue of the primary broker additional KeepAlive Message. If the message is not received after N secs. the new receiver and sender should be launched that operate with secondary broker. This way the receiver/sender take on the functionality of the primary broker.
Questions:
Obviously round-robin strategy is not suitable. Also automatic selection of secondary server as in  question is not the way to go. That is why keepAlive message was chosen to detect whether the primary broker is down. Is it possible to have this functionality with Spring Integration? To be more precise:

*

*how to implement the switching between primary and secondary server for my senders/receivers when the keepAlive message is not received by the primary server?

*Is it possible to switch back to primary server when it is up&running again?


text:
Q: Android Studio: Newly added module is not showing in Project Structure window I am trying to integrate UnityAds in my Android Studio project.
And for that unity-ads.aar package needs to be added as a module and in the later part, that module must be added as a dependency.
I have successfully added the unity-ads.aar package as a module but when I go to the Project Structure-> Dependencies.
There's no unity-ads below the <All Modules>. Only the app module is present.
According to the documentation the unity-ads should be present on that window from where I will be able to add that unity-ads as a dependency in my project.

What could be the problem????
How can I add that module as a dependency in my project???

A: To add the unity-ads.aar module in your app.
Download latest version here
After the download extract it anywhere you want.
open your project.
Go to File -> Project Structure -> Dependencies (add new dependency)
Select import jar/aar package.

Give the path of the unity-ads.aar file.
Click ok and you're done.

A: Open settings.gradle and add the missing line:
include :unity-ads3.7.1


text:
Q: Login in with Alamofire : Could not cast value of type '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString' (0x102e66c40) Hi I am new to programming and I'm stuck at this error. I am logging in from Xcode to MySQL, but I am unable to move on to home page. My code works fine in PHP and I am unable to login.
Below is my code:
@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters = [
            "username":username.text!,
            "password":password.text!
    ]

    Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
    {
        response in
        //printing response
        print(response)

        if let result = response.result.value
        {
            let resultValue:String = result as! String;

            if (resultValue == "login_success")
            {
                //login is successful
                UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                UserDefaults.standard.synchronize();

                self.dismiss(animated: true, completion: nil)
            }
        }
    }
}

It returns:

login_success Could not cast value of type
  '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString'
  (0x102e66c40).

That's why I am unable to move on to my home page.

A: Because your result is dictionary type not string type:-
use this
let resultValue = result as! [String:Any];

later you can get value of login_success based on key

A: Try another way of retrieving your http result and adding a failure enclosure. Not knowing the output format of you login.php doesn't help but it should look like this:
@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters=[

        "username":username.text!,

        "password":password.text!

         ]

    Alamofire.request(.POST, URL_USER_REGISTER, parameters: parameters, encoding: ParameterEncoding.URL).responseJSON { result in
        switch result {
            case .Success(let data):
                let json = JSON(data)
                let resultValue = json["value"].string
                if (resultValue == "login_success")
                {
                    //login is successful
                    UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                    UserDefaults.standard.synchronize();

                    self.dismiss(animated: true, completion: nil)
                }
            case .Failure(_, let error):
                print("Request failed with error: \(error)")
        }
    }

}

Source: How to get the result value of Alamofire.request().responseJSON in swift 2?


text:
Q: CUDNN Installation I am trying to install CUDNN to use tensorflow with GPU support on my Macbook Pro. After downloading cudnn from NVDIA website, these are all the instructions i could find:
OS X
cd <installpath>
export DYLD_LIBRARY_PATH=`pwd`:$DYLD_LIBRARY_PATH

Add <installpath> to your build and link process by adding -I<installpath> to your compile
line and -L<installpath> -lcudnn to your link line.

While, the first step is really straightforward, what is the meaning of second statement and how do I finish the second step?
Please advise. Thanks.

A: So I was stuck at the same place and what I found was that the cudnn archive basically had just two library files a : .h and .so files. so I figured it was best to put them someplace that is already looked at and I found this :
Untar the folder and copy the necessary files to the existing cuda
library we installed earlier.

tar -xzvf cudnn-7.0-linux-x64-v4.0-prod.tgz
cp cuda/lib64/* /usr/local/cuda/lib64/
cp cuda/include/cudnn.h /usr/local/cuda/include/

so I guess u should find an equivalent for mac
source:
https://medium.com/@acrosson/installing-nvidia-cuda-cudnn-tensorflow-and-keras-69bbf33dce8a


text:
Q: How to calculate the max number of pallets in a truck load? I want to maximise the number of pallets of material I can send in a shipment. My pallets of material are one of three different classes:

*

*Material Type 1 (fragile): Can be stacked with another pallet of type 1,
can be stacked on top of a pallet of material type 2.

*Material Type 2 (sturdy): Can be stacked with another pallet of
material type 2, can be stacked underneath material type 1. Cannot be stacked on top of Material 1

*Material Type 3 (very fragile): Cannot be stacked.

I need to calculate how many pallet footprints or bottom pallets are required for any order if I am given a list of the materials pallets are ordered. For example: 10 Pallets of Material Type 1 and 20 pallets of Material Type 2 and 3 pallets of Material type 3. How many Bottom Pallets would the order take up?
EDIT: Let's set the limit of bottom pallets for the truck to 24. The max pallets stackable are two, that is to say, you can not stack more than two pallets on top of each other. Note: Material 2 cannot be stacked on top of Material 1.

A: Given the current constaints, the number of footprints necessary for the stacking would be
t3 + ( 1 if t1 + t2 > 0, 0 otherwise )

where t1 denotes number of pallets of Type 1, t2 denotes the number of pallets of Type 2 and t3 denotes the number of pallets of Type 3. The pallets of Type 3 cannot be stacked together with anything else; if pallets of Type 1 or Type 2 are present, they can be stacked together, first the pallets of Type 2 and then the pallets of Type 1.
Edit
Since at most 2 pallets can be stacked on top of each other and each truck can load at most 24 stacks, the answer is different. The number of total stacks would be
#Stacks = t3 + ceil( ( t1 + t2 ) / 2 )

where ceil denotes rounding up to the nearest integer. Each pallet of Type 3 must be stacked alone, so at least t3 stacks are necessary. The remaining pallets of Type 1 and Type 2 can be organized in stacks of height at most 2 with apparently no real limitation; if Type 1 and Type 2 go alone into one stack there is no problem, if both Type 1 and Type 2 are present, put Type 2 to the bottom.
Finally, the total number of trucks necessary would be
#Trucks = ceil(#Stacks/24)

where the last truck possibly has some unused space left.


text:
Q: What postfix does if it is unable to deliver a message? If I send a message from

postfixA -> smartHost postfixB -> smartHost postfixC ->  exchange

and only postfixC does MX lookup and it is unable to deliver the message no matter if it is a hard bounce or soft bounce, what does it exactly do ?
Does it look at the header return path and send a message there ? Or does it use envelopeFrom information for it ?
By default, it doesn't let postfixB know in any way, right ? So that if I want to search through logs for what went wrong, I can do it in postfixC only.

A: You're right that the logs on the error will only be on the host that tried the unsuccessful delivery. (You could, of course, have all server send log messages via syslog to a common syslog host, but as long as you're only logging locally, only the host that does the delivery will have the logs.)


text:
Q: ImportError: No module named requests - even though it is installed I'm running Mac OS X and Python (version 2.7).
Apparently I'm missing requests, but it should be installed.
$ python setup.py
Traceback (most recent call last):
  File "setup.py", line 1, in <module>
    import requests
ImportError: No module named requests

$ pip install requests
Requirement already satisfied: requests in /usr/local/lib/python2.7/site-packages
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python2.7/site-packages (from requests)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/site-packages (from requests)
Requirement already satisfied: idna<2.7,>=2.5 in /usr/local/lib/python2.7/site-packages (from requests)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/local/lib/python2.7/site-packages (from requests)

A: alias python=/usr/local/bin/python3 fixed the issue..


text:
Q: Sorted collections: How do i get (extended) slices right? How can I resolve this?
>>> class unslice:
...     def __getitem__(self, item): print type(item), ":", item
...
>>> u = unslice()
>>> u[1,2]    # using an extended slice
<type 'tuple'> : (1, 2)
>>> t = (1, 2)
>>> u[t]  # or passing a plain tuple
<type 'tuple'> : (1, 2)

Rational:
I'm currently overengineering a sorted associative collection with the ability to return ranges of items. It is quite likely that I will want to store tuples of small integers (or even more pathologically wierd values like Ellipsis) in the collection (as keys), and will need some kind of sane way of differentiating extended slices from plain keys
In the one-dimensional case, it's sort of a non-issue.  I can't think of any real reason I would want to collect values of type slice, especially since xrange values are functionally similar and more recognizable to pythonistas (in my judgement).  All other extended slice constructs are tuples of slice, Ellipsis or plain-old python values
No other type of extended slice seems to be in common use for any kind of collection except multidimensional arrays as in NumPy.
I do need to support n-dimensional axes, similar to oct-trees or GiS indices.

A: Since there is no way to differentiate between the calls u[x,y] and u[(x,y)], you should shift one of the two operations you are trying to define off to an actual method.  You know, something named u.slice() or u.range() or u.getslice() or u.getrange() or something like that.
Actually, when writing my own programs, I generally find that when I'm trying to overload a Python operation with two quite distinct semantics, it means that both of the things I am doing need to be turned into named methods!  Because if the two are so similar in meaning that neither one has an obviously superior claim to getting to use the braces [] getitem shortcut, then probably my code will be more readable if both operations get real, readable, explicit method names.
But, it's hard to say more since you haven't told us how on earth you've gotten into this mess.  Why would you want to both store things under tuples and get ranges of things?  One suspects you are doing something to complicated to begin with. :-)
Oh, and other languages with this problem make you say a[1][2] to do multi-dimensional access to easily distinguish from a[1,2]. Just so you know there's another option.

A: From the docs:

There is ambiguity in the formal
  syntax here: anything that looks like
  an expression list also looks like a
  slice list, so any subscription can be
  interpreted as a slicing. Rather than
  further complicating the syntax, this
  is disambiguated by defining that in
  this case the interpretation as a
  subscription takes priority over the
  interpretation as a slicing (this is
  the case if the slice list contains no
  proper slice nor ellipses). Similarly,
  when the slice list has exactly one
  short slice and no trailing comma, the
  interpretation as a simple slicing
  takes priority over that as an
  extended slicing.

As such, I don't think it's possible to distinguish u[1,2]-as-extended-slice from u[1,2]-as-tuple-key.

A: My current thinking about this is to simply let the types that normally associate with slices be uncollectable.  I can't think of any sane reason why anyone would want to do anything with a slice value or Ellipsis except to use them in subscript expressions.
On the off chance a user of the collection wants to sort on a tuple (instead of numbers or strings or dates or any other obvious thing) It might make sense to just require some extra cruft.  As the example...
>>> u[t]
<type 'tuple'> : (1, 2)
>>> u[t,]
<type 'tuple'> : ((1, 2),)

Haven't really tried it with actual code (don't actually have a working GiS index at this time) but i suspect that this might just automatically do the right thing, since the extended slice is a tuple of length one (one dimension), which happens to be a tuple.


text:
Q: Piping iostat -d 1 to python sys.stdin I am trying to pipe the output of utilities like iostat, mongostat, etc with the command:
$ iostat -d 1 | ./script.py

in which I am using the code:
for line in sys.stdin:
    print line

I see that it hangs and does not print each line to the console.
if I run without the flag to repeat every second '-d 1' where output only happens once, the script behaves as expected.
$ iostat | ./script.py

A: The data is being buffered, you can call iter on sys.stdout.readline:
import sys
for line in iter(sys.stdin.readline,""):
    print line

Running iostat on it's own just outputs a few lines, iostat -d 1 loops continuously so the data gets buffered.


text:
Q: Apache Spark: Reduce number of cores during an execution Is there a way to reduce the number of cores / executors during a certain part of the run.  We don't want to overrun the end datastore, but need more cores to do computational work effectively.
Basically
// want n cores here
val eventJsonRdd: RDD[(String,(Event, Option[Article]))] = eventGeoRdd.leftOuterJoin(articlesRdd)

val toSave =  eventJsonRdd.map(processEventsAndArticlesJson)

// want two cores here
toSave.saveToEs("apollobit/events")

A: You can try:
toSave.repartition(2).saveTo...

Although this will entail a potentially expensive shuffle.
If your store supports bulk updates, you will get way better performance by calling foreachPartition and doing something with a chunk of data rather than one at a time.