Q:

Tower defense: turret tracking enemy and shooting issues

Here is my code:
func bombTowerTurnShoot() {
    var prevDistance:CGFloat = 1000000
    var closesetZombie = zombieArray[0]
        self.enumerateChildNodes(withName: "bomb tower") {
            node, stop in
            if self.zombieArray.count > 0 {
            for zombie in self.zombieArray {
            if let bombTower = node as? SKSpriteNode {
                let angle = atan2(closesetZombie.position.x - bombTower.position.x , closesetZombie.position.y - bombTower.position.y)
                let actionTurn = SKAction.rotate(toAngle: -(angle - CGFloat(Double.pi/2)), duration: 0.2)
                bombTower.run(actionTurn)
                let turretBullet = SKSpriteNode(imageNamed: "Level 1 Turret Bullet")
                turretBullet.position = bombTower.position
                turretBullet.zPosition = 20
                turretBullet.size = CGSize(width: 20, height: 20)
                //turretBullet.setScale (frame.size.height / 5000)
                turretBullet.physicsBody = SKPhysicsBody(circleOfRadius: max(turretBullet.size.width / 2, turretBullet.size.height / 2))
                turretBullet.physicsBody?.affectedByGravity = false
                turretBullet.physicsBody!.categoryBitMask = PhysicsCategories.Bullet //new contact
                turretBullet.physicsBody!.collisionBitMask = PhysicsCategories.None
                turretBullet.physicsBody!.contactTestBitMask = PhysicsCategories.Zombie
                self.addChild(turretBullet)
                var dx = CGFloat(closesetZombie.position.x - bombTower.position.x)
                var dy = CGFloat(closesetZombie.position.y - bombTower.position.y)
                let magnitude = sqrt(dx * dx + dy * dy)
                dx /= magnitude
                dy /= magnitude
                let vector = CGVector(dx: 4.0 * dx, dy: 4.0 * dy)
                func fire () {
                    turretBullet.physicsBody?.applyImpulse(vector)
                }
                func deleteBullet() {
                    turretBullet.removeFromParent()
                }
                turretBullet.run(SKAction.sequence([SKAction.wait(forDuration: 0), SKAction.run(fire), SKAction.wait(forDuration: 2.0), SKAction.run(deleteBullet) ]))

                let distance = hypot(zombie.position.x - bombTower.position.x, zombie.position.y - bombTower.position.y)
                if distance < prevDistance {
                    prevDistance = distance
                    closesetZombie = zombie
                }

                }
            }
        }
    }
}

What this code does is turns a turret towards the closest zombie and shoot at it. As far as I can tell the turret is turn towards the closest zombie (if you can tell whether this code actually accomplishes that or not I would like to know). The bigger problem I am having is that the turrets sometimes shoot more than one bullet. I think it is because it is trying to fire at all zombies in the array not the specified one (the closest to the tower). How can I make it so that the turret only shoots the zombie that is closest?
class GameScene: SKScene, SKPhysicsContactDelegate {//new contact
     var zombieArray:[SKSpriteNode] = []
...
...
}

And I append all the zombie to the array once they are added and remove them from the array once they die.

A:

Basically, I don't know what you were doing wrong exactly. You had a ton of stuff going on, and trying to figure out the bug would probably have taken longer than rewriting it (for me at least). So that is what I did.
Here is a link to the project on github:
https://github.com/fluidityt/ShootClosestZombie/tree/master
For me, this was all about separating actions into somewhat distinct methods, and separating actions in general from logic.
You had so much going on, it was hard to test / see which parts were working correctly or not. This is where having somewhat smaller methods come in, as well as separating action from logic.. Your action may work fine, but perhaps it's not getting called due to a logic error.
So, how I implemented this was to just make your bomb turret it's own class.. that way we can have the bomb turret be in charge of most of its actions, and then let gameScene handle most of the implementation / and or logic.
The demo I've uploaded shows two turrets that auto-orient themselves to the closest zombie every frame, then shoot at them every second. Click the screen to add more zombies.
The turrets independently track the closest zombie to them so if you spawn a zombie on the left and the right, then the left turret will shoot at left zombie, and right turret will shoot at right zombie (and only once!).

class BombTower: SKSpriteNode {

  static let bombName = "bomb tower"

  var closestZombie: SKSpriteNode!

  func updateClosestZombie() {
    let gameScene = (self.scene! as! GameScene)
    let zombieArray = gameScene.zombieArray

      var prevDistance:CGFloat = 1000000
      var closestZombie = zombieArray[0]

      for zombie in zombieArray {

        let distance = hypot(zombie.position.x - self.position.x, zombie.position.y - self.position.y)
        if distance < prevDistance {
          prevDistance = distance
          closestZombie = zombie
        }
      }
    self.closestZombie = closestZombie
  }

  func turnTowardsClosestZombie() {
    let angle = atan2(closestZombie.position.x - self.position.x , closestZombie.position.y - self.position.y)
    let actionTurn = SKAction.rotate(toAngle: -(angle - CGFloat(Double.pi/2)), duration: 0.2)
    self.run(actionTurn)
  }

  private func makeTurretBullet() -> SKSpriteNode {
    let turretBullet = SKSpriteNode(imageNamed: "Level 1 Turret Bullet")
    turretBullet.position = self.position
    turretBullet.zPosition = 20
    turretBullet.size = CGSize(width: 20, height: 20)
    //turretBullet.setScale (frame.size.height / 5000)

    turretBullet.physicsBody = SKPhysicsBody(circleOfRadius: max(turretBullet.size.width / 2, turretBullet.size.height / 2))
    turretBullet.physicsBody?.affectedByGravity = false
    //    turretBullet.physicsBody!.categoryBitMask = PhysicsCategories.Bullet //new contact
    //    turretBullet.physicsBody!.collisionBitMask = PhysicsCategories.None
    //    turretBullet.physicsBody!.contactTestBitMask = PhysicsCategories.Zombie

    return turretBullet
  }

  private func fire(turretBullet: SKSpriteNode) {
    var dx = CGFloat(closestZombie.position.x - self.position.x)
    var dy = CGFloat(closestZombie.position.y - self.position.y)
    let magnitude = sqrt(dx * dx + dy * dy)
    dx /= magnitude
    dy /= magnitude

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

    turretBullet.physicsBody?.applyImpulse(vector)
  }

  func addBulletThenShootAtClosestZOmbie() {
    let bullet = makeTurretBullet()
    scene!.addChild(bullet)
    fire(turretBullet: bullet)
  }
}

// TODO: delete bullets, hit detection, and add SKConstraint for tracking instead of update.
// Also, I think that we are iterating too much looking for nodes. Should be able to reduce that.
// Also also, there are sure to be bugs if zombieArray is empty.
class GameScene: SKScene {

  var zombieArray: [SKSpriteNode] = []

  private func makeBombArray() -> [BombTower]? {
    guard self.zombieArray.count > 0 else { return nil }

    var towerArray: [BombTower] = []
    self.enumerateChildNodes(withName: BombTower.bombName) { node, _ in towerArray.append(node as! BombTower) }
    guard towerArray.count > 0 else { return nil }

    return towerArray
  }

  private func towersShootEverySecond(towerArray: [BombTower]) {

    let action = SKAction.run {
      for bombTower in towerArray {
        guard bombTower.closestZombie != nil else { continue } // I haven't tested this guard statement yet.
        bombTower.addBulletThenShootAtClosestZOmbie()
      }
    }
    self.run(.repeatForever(.sequence([.wait(forDuration: 1), action])))
  }

  override func didMove(to view: SKView) {
    // Demo setup:
    removeAllChildren()

    makeTestZombie: do {
      spawnZombie(at: CGPoint.zero)
    }
    makeTower1: do {
      let tower = BombTower(color: .yellow, size: CGSize(width: 55, height: 55))
      let turretGun = SKSpriteNode(color: .gray, size: CGSize(width: 25, height: 15))
      turretGun.position.x = tower.frame.maxX + turretGun.size.height/2
      tower.name = BombTower.bombName
      tower.addChild(turretGun)
      addChild(tower)
    }
    makeTower2: do {
      let tower = BombTower(color: .yellow, size: CGSize(width: 55, height: 55))
      let turretGun = SKSpriteNode(color: .gray, size: CGSize(width: 25, height: 15))
      turretGun.position.x = tower.frame.maxX + turretGun.size.height/2
      tower.addChild(turretGun)
      tower.position.x += 200
      tower.name = BombTower.bombName
      addChild(tower)
    }

    guard let towerArray = makeBombArray() else { fatalError("couldn't make array!") }

    towersShootEverySecond(towerArray: towerArray)
  }

  private func spawnZombie(at location: CGPoint) {
    let zombie = SKSpriteNode(color: .blue, size: CGSize(width: 35, height: 50))
    zombieArray.append(zombie)
    zombie.position = location
    zombie.run(.move(by: CGVector(dx: 3000, dy: -3000), duration: 50))
    addChild(zombie)
  }

  // Just change this to touchesBegan for it to work on iOS:
  override func mouseDown(with event: NSEvent) {
    let location = event.location(in: self)
    spawnZombie(at: location)
  }

  // I think this could be a constrain or action, but I couldn't get either to work right now.
  private func keepTowersTrackingNearestZombie() {
    guard let towerArray = makeBombArray() else { return }
    for tower in towerArray {
      tower.updateClosestZombie()
      tower.turnTowardsClosestZombie()
    }
  }

  override func update(_ currentTime: TimeInterval) {
    keepTowersTrackingNearestZombie()
  }
}


Q:

Replace every other occurence with different replacements

I have a string that looks something like this:
$post = "Test $asd$ lol test asd $test$";

I want it to become:
$post = "Test [bb]asd[/bb] lol test asd [bb]test[/bb]";

Which is the easiest/best way to accomplish this? Note that the number of $ occurrences differs from time to time. The basic idea is to replace every other occurrence with [b] respectively [/bb].
I hope you understand.

A:

try this :
<?php
$str  = $post = 'Test $asd$ lol test asd $test$';
echo preg_replace('/\$(\w+)\$/','[bb]$1[/bb]',$str);
?>

Output :
Test [bb]asd[/bb] lol test asd [bb]test[/bb]


Q:

Is this compulsory for a Muslim to obey all the government rules in a non-Islamic country

By non-Islamic, I mean a country that is not ruled according to Shariah. Not necessarily non-Muslim-majority. For example, my country, Bangladesh, is a Muslim-majority country, but not a Islamic country.
And by rules, of course I mean those rules which do not contradict Shariah. I am sure if a rule contradict shariah, it cannot be obeyed by a Muslim.

I believe most countries have an age restriction for marriage. Bangladesh has 18 years for women and 21 years for men. Now, I have seen many people give their daughter to marriage before 18. Perhaps because it is encouraged by the Prophet (S).
Now, Is it farz for a Muslim to obey such a rule? Or it depends on situation and type of the rule.

A:

Here is a hadith which says that our Prophet (pbuh) said that we must obey the ruler of the country we reside in unless ofcourse the rule goes against islam:

the Messenger of Allah (Allah bless him & give him peace) said: “It is
  necessary upon a Muslim to listen to and obey the ruler, as long as
  one is not ordered to carry out a sin. If he is commanded to commit a
  sin, then there is no adherence and obedience.” (Sahih al-Bukhari, no.
  2796 & Sunan Tirmidhi)

Here is a fatwa about this issue, and here is a relevant extract from that fatwa:

The ruler who does not rule according to the Book of Allaah and the
  Sunnah of His Messenger should be obeyed in matters that do not
  involve disobedience towards Allaah and His Messenger


Q:

PHP: file_get_contents(): failed to open stream error - works on test XAMPP test server, not live

I’m creating a PHP application that for a movie theater that, when accessed by a user, fetches an external XML document, saves it to our server. That XML file is then used to load the showtimes and other movie information. If the file on our server is older than 15 minutes, it’ll be overwritten, otherwise, it’ll load the existing one. I already pretty much finished the application, and it works perfect on my XAMPP test server, however it fails to work on the live server.
The external XML file is located at this URL: http://45502.formovietickets.com:2235/showtimes.xml. Our server that I am trying to save the file to is on one of HostGator’s Linux-based servers. Using PHP’s curl functions, I have been able to successfully load the XML file on the XAMPP test server only. On the live server, it simply fails to connect.
I feel like it might be an some sort of access restriction on the formovietickets.com server, but the people behind it insist there isn't any sort of restriction going on. Does anyone know a work around for this issue?
<?php

$url = 'http://45502.formovietickets.com:2235/showtimes.xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) === false) {
    echo 'Curl error: '.curl_error($ch);
} else {
    echo 'Retrieved file with no errors!';
}
curl_close($ch);

?>

What Have I Tested?

I’ve tried transferring the php.ini file over from XAMPP to the live server and it still fails.
I was able to successfully retrieve an XML file located on another external server.
I’ve tested the code on a Windows-based server and the problem persists.

NOTE: If you load the URL more than a couple times from the same IP address in less than 15 minutes, you’ll get an error saying “Too many requests from this IP address”. Just saying in case you try testing it out.

A:

My guess is that your hoster is blocking outbound access to non-standard ports like 2235 in their firewall. If that is the case, you should ask them to open that port and hope that they are willing to do so. If they aren't, then you'll have to come up with another solution to get the file on the server, like using a proxy or pushing the file to the server instead of fetching it.


Q:

Как cделать вычитание дробей?

Вообщем, задали нам калькулятор дробей. Всё получилось, но если 1\1 - 1\2 то выдает 0.
Я так и не нашел решение данной проблемы
from tkinter import *
from math import *

def aaa(event):
    a = int(assq.get())
    b = int(ass1q.get())
    c = int(ass2q.get())
    d = int(ass3q.get())
    e = ass4q.get()
    z=b
    x=d
    while z!=x:
        if z>x:
            z=z-x
        else:
            x=x-z

    if z > x:
        qwerty=z*(b//z)*(d//z)
    else:
        qwerty=x*(b//x)*(d//x)

    if e == '+':

        pop1=((qwerty//b)*a)+((qwerty//d)*c)
        k = gcd(pop1,qwerty)

        if pop1 == 0:
            labd2['text']=''
            labd['text']='0'
            laba['text']=''
            lab['text']=''
        elif (pop1//k)>=(qwerty//k):
            labd2['text']=str((pop1//k)//(qwerty//k))
            laba['text']=str((pop1//k)%(qwerty//k))
            lab['text']=str(qwerty//k)
            labd['text']='_'
        else:
            labd2['text']=''
            labd['text']='_'
            laba['text']=str(pop1//k)
            lab['text']=str(qwerty//k)
        if lab['text']!='0'and((pop1//k)%(qwerty//k)) == 0:
            laba['text']=''
            lab['text']=''
            labd['text']=''
    ####################вот и вычитание#################################
    if e == '-':
        pop2=((qwerty//b)*a)-((qwerty//d)*c)
        k = gcd(pop2,qwerty)

        if pop2 == 0:
            labd2['text']=''
            labd['text']='0'
            laba['text']=''
            lab['text']=''
        elif (pop2//k)>=(qwerty//k):
            labd2['text']=str((pop2//k)//(qwerty//k))
            laba['text']=str((pop2//k)%(qwerty//k))
            lab['text']=str(qwerty//k)
            labd['text']='_'
        else:
            labd2['text']=''
            labd['text']='_'
            laba['text']=str(pop2//k)
            lab['text']=str(qwerty//k)
        if lab['text']!='0'and((pop2//k)%(qwerty//k)) == 0:
            laba['text']=''
            lab['text']=''
            labd['text']='0'
    if e == '*':
        pop3=(a*c)
        qwerty=(b*d)
        k = gcd(pop3,qwerty)

        if pop3 == 0:
            labd2['text']=''
            labd['text']='0'
            laba['text']=''
            lab['text']=''
        elif (pop3//k)>=(qwerty//k):
            labd2['text']=str((pop3//k)//(qwerty//k))
            laba['text']=str((pop3//k)%(qwerty//k))
            lab['text']=str(qwerty//k)
            labd['text']='_'
        else:
            labd2['text']=''
            labd['text']='_'
            laba['text']=str(pop3//k)
            lab['text']=str(qwerty//k)
        if lab['text']!='0'and((pop3//k)%(qwerty//k)) == 0:
            laba['text']=''
            lab['text']=''
            labd['text']=''
    if e == ':':
        pop4=(a*d)
        qwerty=(c*b)
        k = gcd(pop4,qwerty)

        if pop4 == 0:
            labd2['text']=''
            labd['text']='0'
            laba['text']=''
            lab['text']=''
        elif (pop4//k)>=(qwerty//k):
            labd2['text']=str((pop4//k)//(qwerty//k))
            laba['text']=str((pop4//k)%(qwerty//k))
            lab['text']=str(qwerty//k)
            labd['text']='_'
        else:
            labd2['text']=''
            labd['text']='_'
            laba['text']=str(pop4//k)
            lab['text']=str(qwerty//k)
        if lab['text']!='0'and((pop4//k)%(qwerty//k)) == 0:
            laba['text']=''
            lab['text']=''
            labd['text']=''

root = Tk()

root.geometry('400x400+100+100')
root.title('Okno')
root['bg']='#999999'

assq = Entry(root,width=5)
assq.place(x = 20, y = 1)

ass1q = Entry(root,width=5)
ass1q.place(x = 20, y = 29)

ass2q = Entry(root,width=5)
ass2q.place(x = 90, y = 1)

ass3q = Entry(root,width=5)
ass3q.place(x = 90, y = 29)

ass4q = Entry(root,width=5)
ass4q.place(x = 55, y = 15)

butq = Button(root,bg='blue',width=5, height=2)
butq.place(x = 187, y = 100)
butq.bind('<Button-1>',aaa)

laba = Label(root,font='Ariel 8',bg='#999999')
laba.place(x = 160, y = 1)
lab = Label(root,font='Ariel 8',bg='#999999')
lab.place(x = 160, y = 30)
labd = Label(root,font='Ariel 8',bg='#999999',text='_')
labd.place(x = 160, y = 16)
labd2 = Label(root,font='Ariel 8',bg='#999999')
labd2.place(x = 145, y = 16)
labd3 = Label(root,font='Ariel 10',bg='#999999',text='=')
labd3.place(x = 130, y = 16)

root.mainloop()

A:

Вычитание дробей
 a/b - c/d

даёт числитель и знаменатель
nom = a * d - c * b
den = b * d

Их можно сократить (целочисленно разделить на наибольший общий делитель, если он больше 1)


Q:

How to enable FinderSync Extension in macOS System Preferences

I am integrating FinderSync Extension in my Cocoa Application to show badges in files and folders. Look at the below two scenario:

When i run application using FinderSync Extension (like DemoFinderSync) look at the blue popup in the below image, in that case Extension is added in the System Preference with Check mark and called that principal class "FinderSync.m" as well.

When i run application using my Application Scheme (like DemoApp) look at the blue popup in the below image, in that case Extension is added in the System Preference but without check mark and that principal class "FinderSync.m" do not call and FinderSync Extension does not work in this case.

Does anybody have an idea how to enable Finder Extension in the System Preference using second scenario?

A:

Non-debug scheme (#if !DEBUG):
system("pluginkit -e use -i com.domain.my-finder-extension");

When running under debugger give path to your extension directly:
NSString *pluginPath = [[[NSBundle mainBundle] builtInPlugInsPath] stringByAppendingPathComponent:@"My Finder Extension.appex"];
NSString *pluginkitString = [NSString stringWithFormat:@"pluginkit -e use -a \"%@\"", pluginPath];
system([pluginkitString cStringUsingEncoding:NSUTF8StringEncoding]);

Specify this in your applicationDidFinishLaunching method.  You should also manually turn this on only once so that if user turned your extension off in the System Preferences you don't turn it on every time your application starts.  I set an NSUserDefaults key the first time user launches my app that has the finder sync extension support.

A:

I got the solution:
Code to Enable Extension (bundle ID)
system("pluginkit -e use -i YourAppBundleID")

Code to Disable Extension (bundle ID)
system("pluginkit -e ignore -i YourAppBundleID")

Before i used:
system("pluginkit -e use -i AppBundleID.FinderSync")

so just remove ".FinderSync" its working.


Q:

Re-using function inside jade

I have a inline script and code block repeated 2 times inside a .jade file and would like to:

re-use it. (i mean DRY it and have just one block/function)
escape the html like suggested here, right now I am using != linkExist('foo')

My idea was to use mixin, but don't know how to. My code works as is, but would like to know how to write it better. Thought about codereview (because my code actually works and I just want to improve it) but the jade has not even a tag there yet, so I think SO might be better.
h1 Teachers
for result in object.teachers
    - var linkExist = function(i){
    -   if (result[i] != 'undefined'){
    -       var html = ', follow on ' + i + ': ' + result[i].split("http://")[1] + '';
    -       return html;
    -   };
    - }

    section
        h3 #{result.Name}
        p.inline #{result.Nick}

        img(src=result.img)

        p.small Location: #{result.Location}

        p.small
            | Web:
            for webResult in result.Web
                a(href=webResult,target='_blank') #{webResult.split('http://')[1]}

            != linkExist('Twitter')
            != linkExist('GitHub')

//now it repeats the code but for students
h1 Students
for result in object.students
    - var linkExist = function(i){
//etc.......

A:

You should be able to use a mixin; if you pass result as well, it should be pretty generic:
mixin linkExist(result, type)
  if result[type] !== undefined
    | , follow on #{type}: ...

//- use like this
for result in object.teachers
  ...
  mixin linkExist(result, 'Twitter')
  mixin linkExist(result, 'GitHub')

for result in object.students
  ...
  mixin linkExist(result, 'Twitter')
  mixin linkExist(result, 'GitHub')


Q:

Direct limit and constant are adjoint functors

I have a question. Why $(\varinjlim, | |)$ is an adjoint pair of functors?
Here the definition of constant direct system || is: For any I, fix a module A and set $A_i=A$, all $i\in I$, and $\phi_j^i=1_A$ for all $i\leq j$.
The adjoint pair of functors is an ordered pair (F,G), $F:C\rightarrow D, G:D\rightarrow C$ such that there is a bijection $\tau: Hom_C(FA,C)\rightarrow Hom_D(A,GC) $   which is natural in each variable.
The definition of constant direct system is clear. It is a functor G from C to D, here C is the index set I. But the direct limit seems like consisting of an object and a family of morphisms such that the universal property holds. Then how we regard it as a functor? I guess it might be a functor from a direct system to an object with some morphisms? Then I am confused about how to check the condition of adjoint functors. Thanks for any help!

A:

By definition, a direct limit of a system $\{B_i\}_{i \in I}$, if it exists, is an object $\varinjlim B_i \in \mathsf{C}$ together with morphisms $f_i : B_i \to \mathcal{B}$, such that for all objects $A \in \mathsf{C}$,
$$\hom_{\mathsf{C}}(\mathcal{B}, A) \cong \hom_{\mathsf{C}^I}(\{B_i\}, |A|) \tag{*}$$
is a bijection, the map being given by
$$(g : \mathcal{B} \to A) \mapsto \{ g_i = g \circ f_i : B_i \to |A|_i = A \}_{i \in I}.$$
You can easily see that this is equivalent to the universal property of the direct limit: it exactly means that for all system of morphisms $g : B_i \to A$ (compatible with the system $\{B_i\}$) there exists a unique morphism $\mathcal{B} \to A$ compatible with the $g_i$. (It's one of these things you need to work out yourself to really understand, so I encourage you to write down the details.)
It can be shown that if for all systems $\{B_i\} \in \mathsf{C}^I$, the direct limit exists, then the constant direct system functor $|-| : \mathsf{C} \to \mathsf{C}^I$ has a left adjoint. It can be denoted $\varinjlim : \mathsf{C}^I \to \mathsf{C}$ and is called the direct limit (or colimit) functor. Since this is a left adjoint, equation $(\text{*})$ holds (with $\mathcal{B} = \varinjlim B_i$), and you see that therefore $\varinjlim B_i$ is a direct limit of the system $\{B_i\}$.
I won't prove that it's a functor, but to get an idea, suppose that you have two systems $\{B_i\}$ and $\{C_i\}$ and a collection of morphisms $h_i : B_i \to C_i$, compatible with the systems. Then you can compose with the "injection" morphisms to get $\tilde{h_i} : B_i \to C_i \to {\varinjlim}_j C_j$, and these maps commute with the maps of the system $\{B_i\}$. So by the universal property you get a map $$\varinjlim h_i : \varinjlim B_i \to \varinjlim C_i.$$
It remains to show that $\varinjlim (h_i \circ g_i) = \varinjlim h_i \circ \varinjlim g_i$, a healthy exercise.


Q:

angular + jasmine: mock a directive

I have a controller that "feeds" a directive with data:
HTML

    <my-drtv data="ctrl.data"></my-drtv>

javascript
function MyCtrl(){
    this.data = "dummy";
}

function myDrtv() {
   return {
      template:'
{{myData}}
'
      scope:{
        data:'='
      },
      link:function(scope){
        scope.myData = scope.data.toUpperCase();
      }
   }
}

I need to mock the directive in order to verify that the controller has passed the correct data.

A:

Ok, got it.
This is a bad approch.
Since I want to test my controller, I should test it's output (ctrl.data) directly.


Q:

Making a file empty

I have a csv file.
On Certain condition, I want to make the file empty.
How i can make the file empty. as i dont not delete it & create a new file.
Please suggest any.
Thanks

A:

How about System.IO.File.WriteAllText(filePath,string.Empty);
Found here: To clear the contents of a file

A:

File.WriteAllBytes(filePath, new byte[] { 0 });

Will turn the CSV into a void. If you actually want a blank CSV file (as opposed to an empty file), then replace the byte[] parameter with the actual bytes of an empty CSV file (from a template that you've prepared from Excel, for example).


Q:

VM Not Using 100% CPU On Hyper-V

I have a dedicated Hyper-V server setup, with 4 VMs.
Logged into one of the VM's which is running XP and with Integration Services installed.
All other VMs are idle.
Using Windows Task Manager to monitor CPU usage on both the server and the vm.
If I launch Visual Studio for example, the CPU on the VM is pegged at 100% until the app is loaded.  However during this time, none of the cores on the Hyper-V server never even ripple. It's almost like nothing is happening.
How can I get/let my VM's utilize more of the host's CPU time?

A:

Task Manager doesn't show total processor time, it only shows the root partition's processor time. Take a look at the following article for information on how to determine the aggregate / total processor usage:
See: http://blogs.msdn.com/tvoellm/archive/2009/04/23/monitoring-hyper-v-performance.aspx
To Quote:
Processor:
Once you have an idea of the overall system capabilities and configuration though the “Hyper-V Hypervisor” counter set you will want to monitor the processors on the system. The most important counter set to monitor is the “Hyper-V Hypervisor Logical Processor”. This counter set allows you to determine how much of the physical processor are being used. The virtual processor counter sets only show a slice of the “Hyper-V Hypervisor Logical Processor”.
Hyper-V Hypervisor Logical Processor
Hyper-V Hypervisor Root Virtual Processor
Hyper-V Hypervisor Virtual Processor


Q:

Calculate $\lim_{n\to\infty}\int_{[0,1]}\frac{nx}{1+nx^2}$.

It is required to calculate $\lim_{n\to\infty}\int_{[0,1]}\frac{nx}{1+nx^2}$. Here is my attempt.
Let $x\in(0,1]$. Then $|\frac{nx}{1+nx^2}|\leq|\frac{nx}{nx^2}|=\frac{1}{nx}$ for each $n\in\mathbb{N}$. Hence it follows that $f_n(x)=\frac{nx}{1+nx^2}$ converges pointwise to $f\equiv 0$. Moreover $|f_n(x)|\leq g(x)$, where $g(x)=\frac{1}{x}$ if $x\in(0,1]$ and $g(0)=0$. So $|f_n(x)|\leq g(x)$ $a.e.$ on $[0,1]$ and $g$ is integrable as it is continuous $a.e.$ on $[0,1]$. Now by Lebesgue Dominated Convergence theorem $\lim_{n\to\infty}\int_{[0,1]}f_n=\int_{[0,1]}f\ $ , i.e. $\lim_{n\to\infty}\int_{[0,1]}\frac{nx}{1+nx^2}=0$.
Could someone please tell me if this solution is alright? Thanks.

A:

As pointed out by comments, your attempt has a couple of issues. Here is a valid approach. Write
$$ \int_{[0,1]} \frac{nx}{1+nx^2} \, dx
= \int_{[0,1]} \frac{x}{\frac{1}{n}+x^2} \, dx. $$
It is easy to check that the integrand is monotone increasing in $n$. So by the monotone convergence theorem,
$$ \lim_{n\to\infty} \int_{[0,1]} \frac{nx}{1+nx^2} \, dx
= \int_{[0,1]} \lim_{n\to\infty} \frac{x}{\frac{1}{n}+x^2} \, dx
= \int_{[0,1]} \frac{1}{x} \, dx
= \infty. $$


Q:

Git user dependent history or user dependent content

I'm facing a problem of watermarking my work. I want to provide my work to my customers using git repository but with benefits of a doubt. I know how to watermark my work but the question is how to do it per user.
Is there a way to modify content of git clone that it will differ for particular user?
My first thought was to somehow provide different version of single commit for each user but there are couple problems with this solution. First I do not know how to do it and second it is probably not reliable solution as it will be easy to find this commit and change it.
Do you have any idea of how to resolve this issue?

A:

Is there a way to modify content of git clone that it will differ for
  particular user?

The short answer is: No, it's not possible.

The long answer is: To reliable modify the contents of a git clone in a way that cannot be undone by just removing the last commit as you describe, would require you to have a lot of control over the Git server where the repository is being cloned from, and be able to intercept the clone operation and takeover.
It's probably best if you create a separate Git repository for each client, that contains a single commit flattening the whole history and with the contents already watermarked, and allow the client to clone that repository, instead of the original one with all the history.
Of course, this repository will have no relation with the original one, so might not satisfy your needs, if you wanted the client to contribute back in the repo - i.e. it wouldn't be easy to merge the client's changes back to the original one.


Q:

copying the value of a const uint * to another variable in c++

I have a generic problem I suppose.
I`m currently learning C++ and SDL 2.0. SDL provides a function which returns a pointer to a const uint * containing all the keystates.
These are the variables I would like to use:
const Uint8* oldKeyState;
const Uint8* currentKeyState;

In the construction of my input.cpp:
currentKeyState = SDL_GetKeyboardState(&this->length);
    oldKeyState =  currentKeyState;

And in the Update() method I use:
oldKeyState = currentKeyState;
currentKeyState = SDL_GetKeyboardState(NULL);

However, instead of copying over the last values, all I do is giving a pointer to the oldKeyState, which in turn points to the current keystates..
So how do I go about copying the actual values from the variable's pointer to the current and old keystate? I don't want the pointer in my old keystate since I will not be able to check whether the previous state was UP and the new state is DOWN.

A:

Uint8 oldKeyState[SDL_NUM_SCANCODES];

// ...

memcpy(oldkeystate, currentKeyState, length);

A:

The problem you have here is that you are trying to copy the pointer to a const array, which never changes. As a result, you will see that both pointers go to the same memory address, and you never have two copies of the input state which allows you to check for pressed keys.
Instead, you should use memcpy to copy one array to the other. But in order to do so, you should change the type of oldKeyState to just Uint8*, or else you will get an error for copying into a const array.
So, the code should end up like this:
const Uint8 * currentKeyState;
Uint8 * oldKeyState;

...

//Constructor
currentKeyState = SDL_GetKeyboardState(&this->length);
oldKeyState = new Uint8[this->length];

...

//Input update
memcpy(oldKeyState, currentKeyState, this->length);
SDL_PumpEvents(); //Copy the array before calling PumpEvents()!
currentKeyState = SDL_GetKeyboardState(NULL);


Q:

Vue.js print raw html and call component methods

I am dynamically loading the html content from an ajax request. This html has some buttons like
<button @click="someComponentMethod">Add</button>

As you can see I am trying to call components methods. But Its not working.
I think instead of @click html's default attribute "onclick" should work. But this will only recognize the function that are defined in global scope. Can someone guide me how I can call component's function from core javascript i.e using "onclick".
Update
Ok! I got it that v-html will not compile that html. But can you guys tell me how can I call component method from javascript (i.e outside of component scope). In this way I will be able to use onclick="JAVASCRIPT_CODE_TO_EXECUTE_METHOD".

A:

That content will not be compiled as mentioned in official docs :

The contents of the span will be replaced with the value of the rawHtml property, interpreted as plain HTML - data bindings are ignored. Note that you cannot use v-html to compose template partials, because Vue is not a string-based templating engine. Instead, components are preferred as the fundamental unit for UI reuse and composition.

A:

Instead of loading html I end up saving component in JSON format. This component has a template property that stores the html string. In this way I am able to store and load component to and from database and it works without any issue.


Q:

Using a String in run configurations as an argument and using it in an if-statement

The code below works as long as the argument in the run configuration equals "-output". But when the arguments are empty the compiler throws and ArrayOutOfBoundsException.
The point of this piece of code would eventually be to;
- Perform an action when -output is written in the run configurations arguments
- Perform something else if the arguments are empty or different from -output
I found many problems that looked like this one. But I've been working on a solutions for far to long, so I started a new post. Help is very much appreciated.
...
public static void main(String[] args) {
        Version_5 v5 = new Version_5("Test");
        {
            if(args[0].equals("-output")){
                System.out.println("It works");
            }
        }
    }
...

A:

You need to check if you have arguments first, that's all.
if ((args.length > 0) && (args[0].equals("-output")) {
    ...

You might also consider using an argument-parsing library, of which there are several.
What are the extra brackets for?


Q:

ASP.NET MVC3 ValueProvider drops string input to a double property

I'm attempting to validate the input of a text box which corresponds to a property of type double in my model. If the user inputs "foo" I want to know about it so I can display an error. However, the ValueProvider is dropping the value silently (no errors are added to the ModelState).
In a normal submission, I fill in "2" for the text box corresponding to myDouble and submit the form.
Inspecting controllerContext.HttpContext.Request.Form shows that myDouble=2, among other correct inputs. bindingContext.ValueProvider.GetValue("myDouble") == 2, as expected. The bindingContext.ModelState.Count == 6 and bindingContext.ModelState["myDouble"].Errors.Count == 0. Everything is good and the model binds as expected.
Then I fill in "foo" for the text box corresponding to myDouble and submitted the form.
Inspecting controllerContext.HttpContext.Request.Form shows that myDouble=foo, which is what I expected. However, bindingContext.ValueProvider.GetValue("myDouble") == null and bindingContext.ModelState.Count == 5 (The exact number isn't important, but it's one less than before). Looking at the ValueProvider, is as if myDouble was never submitted and the model binding occurs as if it wasn't. This makes it difficult to differentiate between a bad input and no input.
Is this the expected behavior of ValueProvider? Is there a way to get ValueProvider to report when conversion fails without implementing a custom ValueProvider? Thanks!

A:

Part of the problem here is that your model has a type of double.
The problem is that double cannot be null, and as such will default to a value of 0, thus on submit.. if the ValueProvider returns null, the value of the field will still be 0 and validation will pass.
You should make the double nullable, by using double? and then add a Required attribute to the property.  If the type is not required, then you can add a regular expression validator.


Q:

Line Break in PHP for-loop

There have been a bunch of questions like this already, but none of the answers seem to help me. I would like to have a line-break after each output from a loop. I am using double-quoted strings, like I read here, as well as using HTML (because I want the browser to recognize the line-breaks too) as I read here.
It does create a line-break, however only below the complete output.
I cannot manage to create a line-break between the outputs of the loop. Basically I get a block of text and then a linebreak.
Here is the loop I am using:
<?php
include_once('simple_html_dom.php');
$target_url = "http://www.buzzfeed.com/trending?country=en-us";
$html = new simple_html_dom();

$html->load_file($target_url);

$posts = $html->find('ul[class=list--numbered trending-posts trending-posts-    now]');
$limit = 10;
$limit = count($posts) < $limit ? count($posts) : $limit;
for($i=0; $i < $limit; $i++){
  $post = $posts[$i];
  $post->find('div[class=trending-post-text]',0)->outertext = "";
  echo strip_tags($post, '
') . "
\n";
}

I've also tried "\r\n" and a bunch of variations, as well as the nl2br() function. I believe the PHP_EOL command is meant only for the command line, from what I've researched.
I'm an absolute beginner with PHP, so I am probably missing something simple, but I can't figure it out.
EDIT:
Here is what it prints:
http://globalsocialnews.com/crawler/test8.php
I also included the complete code in case that helps.

A:

You can do line break using css implementation ...
like:
.rcorners1 a {
    display: block;
    margin-bottom: 10px;//for show extra margin between each line...

    }

Edit: Use margin css attribute for extra margin...
please try implementing this...


Q:

What does PAC learning theory mean?

I am new in machine learning. I am studying a course in machine learning (Stanford University ) and I did not understand what is meant by this theory and what is its utility. I am wondering if someone could detail this theory for me.
This theory is based on this equation.

A:

Probably approximately correct (PAC) learning theory helps analyze whether and under what conditions a learner $L$ will probably output an approximately correct classifier. (You'll see some sources use $A$ in place of $L$.)
First, let's define "approximate." A hypothesis $h \in H$ is approximately correct if its error over the distribution of inputs is bounded by some $\epsilon, 0 \le \epsilon \le \frac{1}{2}.$ I.e., $error_D(h)\lt \epsilon$, where $D$ is the distribution over inputs.
Next, "probably." If $L$ will output such a classifier with probability $1 - \delta$, with $0 \le \delta \le \frac{1}{2}$, we call that classifier probably approximately correct.
Knowing that a target concept is PAC-learnable allows you to bound the sample size necessary to probably learn an approximately correct classifier, which is what's shown in the formula you've reproduced:
$$m \ge\frac{1}{\epsilon}(ln|H| + ln\frac{1}{\delta})$$
To gain some intuition about this, note the effects on $m$ when you alter variables in the right-hand side. As allowable error decreases, the necessary sample size grows. Likewise, it grows with the probability of an approximately correct learner, and with the size of the hypothesis space $H$. (Loosely, a hypothesis space is the set of classifiers your algorithm considers.) More plainly, as you consider more possible classifiers, or desire a lower error or higher probability of correctness, you need more data to distinguish between them.
For more, this and other related videos may be helpful, as might this lengthy introduction or one of many machine learning texts, say Mitchell, for example.

A:

The definition of probably approximately correct is due to Valiant.  It is meant to give a mathematically rigorous definition of what is  machine learning.
Let me ramble a bit.  While PAC uses the term 'hypothesis', mostly people use the word model instead of hypothesis. With a nod to the statistics community I prefer model, but I'll attempt to use both.
Machine learning starts with some data,  $(x_i, y_i)$ and one wants to find a hypothesis or  model that will, given the inputs $x_i$ return $y_i$ or something very close. More importantly given new data $\tilde{x}$  the model will compute or predict the corresponding $\tilde{y}$ .
Really one isn't interested in how accurate the hypothesis is on the given (training) data except that it is hard to believe that a model that was created using some data will not accurately reflect that data set, but will be accurate on any future data sets.   The two important caveats are that one cannot predict new data with 100% accuracy and there is also the possibility that the data examples one has seen miss something important.  A toy example would be that if I gave you the 'data' 1,2,3,4 one would 'predict' that 5 would be the next number.  If you tested this by asking people what was the next number in the sequence, most people would say 5.  Someone could say 1,000,000 though.  If you were given the sequence 1,2,3,...999,999 one would be surer that the next number is 1,000,000. However the next number could be 999,999.5, or even 5. The point is that the more data one sees, the more sure one can be that one has produced an accurate model, but one can never be absolutely certain.
The definition of probably approximately correct gives a mathematically precise version of this idea.  Given data $x_i, 1 \leq i \leq m$ with output $y_i$ and a class of models $f_{\theta} $ which constitute the hypotheses one can ask 2 questions.  Can we use the data to find a specific hypothesis $f_{\Theta}$ that is likely to be really accurate in predicting new values ? Further how likely is it that the model is as accurate as we expect it to be ? That is can we train a model that is highly likely to be very accurate.  As in Sean Easter's answer, we say a class of hypotheses (class of models) is PAC if we can do an 'epsilon, delta' argument.  That is we can say with probability $ p >1-\delta $ that our model $f_{\Theta}$ is accurate to within $\epsilon$ .  How much data one must see to satisfy a specific pair $(\delta,\epsilon) $ depends on the actual $(\delta,\epsilon) $ and how complex the given class of hypothesis are.
More precisely, a class of hypotheses $\mathcal{H}$ or models $f_{\theta}$ is PAC if for any pair  $(\epsilon, \delta)$ with $ 0 < \epsilon,\delta , <.5 $ there is a specific model $f_{\Theta}$ such that any new data $\tilde{x}, \tilde{y} $, this model will satisfy $Err(f_{\Theta}(\tilde{x}) ,\tilde{y} ) < \epsilon$  with probability $ p > 1-\delta $ if the model was selected (trained) with at least  $ m = m(\delta,\epsilon,\mathcal{H}) $ training examples. Here Err is the chosen loss function which is usually $(f_{\Theta}(\tilde{x}) -\tilde{y})^2$.
The diagram you have gives a formula for how much data one needs to train on for a given class of hypotheses to satisfy a given pair $(\delta,\epsilon) $.
I could be wrong, but I believe that this definition was given by Valiant in a paper called "A Theory of the Learnable" and was in part responsible for Valiant winning the Turing prize.


Q:

Angular2 to form is invalid for auto selected dropdown

My html looks like below
<div>My app
  <form [formGroup]="selectForm">
    <select [formControl]="selectForm.controls['filename']">
    <option *ngFor="let item of files; let i = index;" [value]="item" [selected]="i==0">{{item}}</option>
    </select>
    <button type="submit" [disabled]="!selectForm.valid">Submit</button>
  </form>
</div>

My component is as below
export class App {
    files: Array<any>=[];
    selectForm: FormGroup;
    name:string;
    constructor(private _formbulider: FormBuilder) {
        this.selectForm = this._formbulider.group({
        'filename': ['', Validators.required]
        });
        this.files = [1];
    }
}

But my problem is submit is disabled since form is invalid. I expect form to be valid. Plunkr link is here

A:

You can initialize field with value, like this:
'filename': [this.files[0], Validators.required]

Then you can remove [selected] tag from HTML code.
* Edit

Another option is to use ngModel directive and that's the way I prefer the most.
Check the plnkr with updated code.


Q:

"Slow" scrolling on image causes image to open

When you hold your finger down on a post in the iOS mobile app, then move your finger, the page scrolls, no matter how long it is until you start moving your finger - this is fine.
When viewing posts with images in, you can tap on the image to open it up full screen for zooming etc - still fine.
When you hold your finger down on an image and begin moving it fairly soon, the page scrolls - also still fine.
When you hold your finger down on an image, but pause because you were just finishing reading a sentence, then begin scrolling, the image gets the "active" overlay and when you finish scrolling and release your finger, it opens up full screen - rather annoying and breaks the flow of reading the post.
I think the act of beginning the scroll action should cancel the "I want to open this image for full viewing" action.
iOS App, Version 1.4.0
Update: I just realised that links exhibit the expected behaviour too - holding down then pulling a link to scroll won't navigate to the link upon releasing your finger - it is just the images.

As mentioned in the comments, using the website in Safari on iOS displays the expected behaviour - holding your finger on an image makes it gain the "active" overlay, but as soon as you start scrolling it loses that overlay, and doesn't open when you release your finger.

A:

This will be fixed in 1.4.4, shipping in mid-February.
The issue was that highlighting is normally cancelled when the web view begins scrolling, but in our case the web view never scrolls, its parent table view does.  Now when the table view begins scrolling, I cancel all the gesture recognizers in the web view.


Q:

What is a good way to handle unplanned work with Scrum and tfs Scrum 2.1 template?

I have come to a team that is just starting to implement scrum.  One reality that we are going to face is what to do when an emergency occurs.
In this case, we have a system that started failing  while we were inside of our sprint.  It's a critical system, so triageing the failure had to become the top priority.
Here's how I've done it in the past:
(note, we were not using any sort of electronic scrum board or burndown, it was on paper and stickies):

Wrote the fire up on a sticky that was a different color than the planned items
Got an activity-point vote as soon as the team understood the problem well enough to vote it.
If necessary, removed an item from the sprint backlog
Updated the paper burn-down to reflect the change.
Noted unplanned work in an Excel spreadsheet that we used for tracking our velocity

At this shop, we are trying to use TFS 2012 and the Scrum 2 template (with the web-based scrum board and burn down).  Is there some guidance on how to notate this using the template?

A:

Scope of Answer
Others will hopefully address your Team Foundation Server template question. My answer is focused more on the issue of how you should handle the interruption from a process standpoint.
Abnormal or Early Termination

In this case, we have a system that started failing while we were inside of our sprint. It's a critical system, so triageing (sic) the failure had to become the top priority.

This is exactly the use case for an Early Termination of a sprint and a return to Sprint Planning. Unless you already had spare capacity in your sprint which could be allocated to your triage or break/fix process, it is likely that this interruption (and the task-switching that goes with it) has impacted your team's productivity for the sprint.
By all means, perform the business-critical work necessary to get your systems up and running again. However, immediately afterwards the entire Scrum team (including the Product Owner) should assess the sprint to see if your Sprint Goal has been compromised. If you can no longer meet the goal, or if assessing the impact to the sprint requires the team to re-estimate or refactor the Sprint Backlog, then you should have the Product Owner terminate your sprint and return to Sprint Planning.
Since you say that your team is new to Scrum, the team will be better off calling for Early Termination on principle. Re-planning is the safer (and framework-sanctioned) route for what you've experienced. Seat-of-your-pants adjustments to the Sprint Backlog and on-the-fly analysis of your Sprint Goal are adventuresome options sometimes undertaken by experienced Scrum teams with a high tolerance for schedule risk, but I certainly wouldn't recommend them as best practices to a newly-formed Scrum team.


Q:

How do I fix slow, clunky CSS transitions?

I apologize if this has already been asked. I'm having a hard time finding an answer on my own. My CSS transitions are not very smooth. I've noticed this is becoming a pattern for me. I'm trying to figure out how to fix that. Is it faster to add/remove a class? Is it the high res images I'm using? Would JQuery be faster? Here's the codepen
https://codepen.io/tyl-er/pen/OgZmQg?editors=0010
let sidePanelOpen = false;

let urls = [
    'https://images.unsplash.com/photo-1498898733745-c8c6df58e4ba',
    'https://images.unsplash.com/photo-1499006619764-59e5b0c0e7ca',
    'https://images.unsplash.com/photo-1498503603722-8de8df0beb96'
];

function openNav() {
    document.getElementById("accordion").style.width = "60vw";
    document.getElementById("splash").style.width = "40vw";
    document.getElementById("splash").style.marginRight = "60vw";
    document.getElementById("splash").style.opacity = ".5";
}

function closeNav() {
    document.getElementById("accordion").style.width = "0";
    document.getElementById("splash").style.width = "100vw";
    document.getElementById("splash").style.marginRight = "0";
    document.getElementById("splash").style.opacity = "1";
    let item = urls[Math.floor(Math.random()*urls.length)];
    document.getElementById("splash").style.backgroundImage = "url(" + item + ")";
}

document.querySelector("#nav-toggle").addEventListener("click", function() {
    this.classList.toggle("active");
    sidePanelOpen = !sidePanelOpen;
    sidePanelOpen ? openNav() : closeNav();
});

A:

Check out this article: Smooth as Butter: Achieving 60 FPS Animations with CSS3
In short, changing elements so that the browser has to re-calculate it's document flow is most likely causing your performance issues.


Q:

Fetch specific property in hibernate One-to-many relationship

I have two pojo classes with one-to-many relationship in hibernate
CustomerAccountEnduserOrderDetails.class
@Entity @Table(name="customer_account_enduser_order_details")
public class CustomerAccountEnduserOrderDetails  implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private Long id;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name = "product_id", insertable = false, updatable = false)
private CustomerCmsProduct customerCmsProduct;
}

Second is CustomerCmsProduct.class
@Entity
@Table(name="customer_cms_product")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomerCmsProduct {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private Long id;

    @Column(name="name")
    private String name;

    @Column(name="offer_price")
    private String offerPrice;

    @Column(name="original_price")
    private String originalPrice;

    @Column(name="discount")
    private String discount;
}

Here if I fetch the object of CustomerAccountEnduserOrderDetails class,then  i will get the CustomerCmsProduct class also , my problem is that here i want the specific column of CustomerCmsProduct table (not all by default i am getting all) like only id and originalPrice.
How i can do like that projection here?

A:

In the service layer or at a webservice layer( if this is a web project) Create two different classes other than @Entity as DTO(Data Transfer Objects) which helps is data transfer from one layer to the other.
public class CustomerAccountEnduserOrderDetailsPojo {
    private List<CustomerCmsProductPojo> productPojoList = new ArrayList<> ();
    // getter and setter
}

public class CustomerCmsProductPojo {}

Follow the below steps

Retrieve the @Entity class data by executing the query from service layer.
Iterate over all the fields and copy only required fields to pojo layer
Expose the data to other layers using service method.

This way, we can avoid changing the custom hibernate behavior as it is linked with many parameters like cache, one to many queries that are fired per iteration.
And also, do any customization that you want in this layer. Hope this is multi layered project where you have different layers which servers different purpose.


Q:

Generalization of intermediate value theorem for derivative

Let $f: \Bbb R^n \to \Bbb R $ be a differentiable function (not necessarily  smooth), and $C$ is a connected set. Is $\nabla f(C)$  connected subset of $\Bbb R^n?$

A:

I do not know what happens in dimension 2, but the answer to your question is negative in higher dimensions:
Theorem. For every $n\ge 3$ there exists a differentiable function $f: R^n\to R$ and a path-connected subset $C\subset R^n$ such that $\nabla f(C)$ is disconnected.
Proof. First of all, for every $n\ge 2$ there exists a  differentiable function $f: R^n\to R$ such that $\nabla f({\mathbf 0})={\mathbf 0}$ and
$$
G= \nabla f^{-1}(B({\mathbf 0}, 1))
$$
has Hausdorff dimension 1. In particular, $\nabla f(R^n)$ has nonempty intersection with the complement of the unit ball $B({\mathbf 0}, 1)$.
This is Theorem 1.2 in
M. Zelený, The Denjoy-Clarkson property with respect to Hausdorff measures for the gradient mapping of functions of several variables,
Annales de l'institut Fourier, 58 no. 2 (2008), p. 405-428.
I will also need:
Lemma. If $n\ge 3$ then for every subset $E\subset R^n$ of Hausdorff dimension $\le 1$, the complement $A:= R^n -E$ is path-connected.
Proof.
For each point $p\in R^n - E$, $n\ge 3$, almost every (in the sense of the Lebesgue measure on the projective space $RP^{n-1}$) straight line through $p$ is disjoint from $E$. This is an application of Theorem 6.8 in
P. Mattila, Hausdorff dimension, orthogonal projections and intersections with planes,
Ann. Acad. Sci. Fenn. Ser. A I Math. 1 (1975), no. 2, 227–244.
Now, pick two points $p, q\in A$. Let $S_p, S_q$ be the unions of lines through $p, q$ respectively, which have nonempty intersection with $E$. Then $S_p, S_q$ have zero $n$-dimensional Lebesgue measure: This is a consequence of Mattila's theorem. Hence, their union also has zero measure.
Thus, there exists a point $x\in R^n -(S_p \cup S_q)$. Let $L_p, L_q$ denote the lines passing through $p, x$ and $q, x$ respectively. Then $L_p\cup L_q$ is path-connected, contains $p$ and $q$, and is disjoint from $E$.
qed
I will apply this lemma to the set $E= G -\{{\mathbf 0}\}$. Its complement $A$ is path-connected.  On the other hand, its image under $\nabla f$ is disconnected: It contains ${\mathbf 0}$ and some points in $R^n - B({\mathbf 0}, 1)$ but no points in $B({\mathbf 0}, 1)- \{{\mathbf 0}\}$. qed


Q:

Select a specific img element out of a div

I have a div element with multiple img elements in it. I want to select one specific img out of it, that is tagged with the classname "active" and then get the html value of this specific image. The rest of the images has epmty classes.

When I select the outer class with $(".images").html() I get a string that contains all 3 inner images. But When I try to do it like this $(".images.active").html() I only get returned an undefined. Why is it working the first time but not the second? And how can I select only the element tagged with active?

A:

Change it to:
$(".images .active").attr('src');

You need a space between the classes to select descendant elements, otherwise you're telling it to look for an element with both classes. Also, image elements have to .html() value; you probably want the src attribute.


Q:

Can I pass a reference type to a template to specify following non-type template parameters' types?

Consider an example:
#include <type_traits>

template <class T, T>
struct has_duplicates_info { };

template <class T, T...>
struct has_duplicates;

template <class T, T First, T... Others>
struct has_duplicates<T, First, Others...>:
          has_duplicates<T, Others...>,
          has_duplicates_info<T, First> {
   static constexpr bool value =
      std::is_base_of<has_duplicates_info<T, First>, has_duplicates<T, Others...>>::value
        || has_duplicates<T, Others...>::value;
};

template <class T, T Last>
struct has_duplicates<T, Last>: has_duplicates_info<T, Last>, std::false_type { };

int a, b;

int main() {
   static_assert(!has_duplicates<int, 0, 1, 2>::value, "has_duplicates<int, 0, 1, 2>::value");
   static_assert(has_duplicates<int, 1, 2, 2, 3>::value, "!has_duplicates<int, 1, 2, 2, 3>::value");
   static_assert(has_duplicates<int&, a, a, b>::value, "!has_duplicates<int&, a, a, b>::value");
}

This compiles fine with clang but not with gcc. The problem is in a line:
static_assert(has_duplicates<int&, a, a, b>::value, "has_duplicates<int&, a, a, b>::value");

where compiler suggests that has_duplicates<int&, a, a, b> is an incomplete type:

has_duplicates.cc:26:18: error: incomplete type ‘has_duplicates<int&, a, a, b>’ used in nested name specifier
    static_assert(has_duplicates<int&, a, a, b>::value, "has_duplicates<int&, a, a, b>::value");
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

So... which compiler is right?
Edit:
To clarify I am not trying to check if the runtime values behind variables passed to has_duplicates contains duplicates only if there are duplicated references passed to this trait... E.g. the code below compiles successfully in both gcc and clang:
template <int &X>
struct a { };

int b;

int main() {
   a<b> c;
}

A:

First off, it's definitely a bug in gcc. You're nearly correct in your diagnosis of the nature of the bug, but it's not that gcc doesn't accept reference-type non-type template parameters, it's rather that gcc fails to recognise reference-type non-type template parameters as a class template partial specialization where the reference type is a previous template parameter:
template<int, class T, T> struct S;  // #1
template<class T, T A> struct S<0, T, A> {};  // #2
int i;
S<0, int&, i> s;  // #3 error: aggregate 'S<0, int&, i> s' has incomplete type

#2 is a perfectly legitimate partial specialization of #1 and should be matched by the instantiation #3, per [temp.class.spec.match] and [temp.deduct].
Fortunately, there's a simple workaround, which is to provide a further partial specialization for reference types:
template<class R, R& A> struct S<0, R&, A> {};

A correct compiler like clang will also be fine with this.
In your case the further partial specializations would be:
template <class R, R& First, R&... Others>
struct has_duplicates<R&, First, Others...> // ...
template <class R, R& Last>
struct has_duplicates<R&, Last> // ...


Q:

C# binding a combobox to a growing list

WinForms, .NET 3.5
I have a ComboBox that needs to display a growing list of items -- there is a long running process fetching items, and I want to be able to display items to the user as they build up over time.
Setting the DatSource property to a naive Array/List doesn't work since subsequent additions are not registered by the ComboBox.
Now I can set the DatSource to a BindingList -- but it seems that this becomes tragically slow.  When I throttle additions things go fine; but I'm adding maybe a thousand items every couple of seconds, and this rate just hangs the form.
I'm entirely willing to believe this is an inherent shortcoming of binding directly to a BindingList, but would like to be better understand what is going on.  The MSDN articles on DatSource, BindingList and BindingSource discuss concepts like and BindingContexts, CurrencyManagers but don't help me understand the specific events, redraws and what-not that are being fired that might cause this slow down.
I suspect the BindingSource registers an item-add event to the ComboBox, which then goes through a series of Item-additions, DropDown-checks and invalidation.  But MSDN browsing and Googling hasn't helped me answer this.
Can anyone point me in the right direction?

Clarification
I'm aware of the design problems, and ways to work around this problem.  So I'm not really looking for a solution -- but I do want to understand the deeper mechanics of what is going on.

A:

The default control is not made for such operations, since all entries are cached on the control as far as I know.
You need to use a control which properly supports a "virtual" mode, which means that it only loads the few items to be displayed currently from the list.


Q:

Unable to insert null values using setNull into the MySql database using Java on the fly?

I want to the set null values on runtime depending on the type I get
Here is my code
@SuppressWarnings("rawtypes")
// input can be Intger,Date, BigInt etc which Mysql supports
String input = "."+st.getType();
// param :- java.sql.Types.Integer or java.sql.Types.BigInt
Class clazz = Class.forName("java.sql.Types");
Field field = clazz.getField(input);
int val = field.getInt(null);
pstmt.setNull(1,val);

A:

I'm going to slightly challenge your question in this answer.  I do not believe that you need to do what you are doing, but as it's somewhat unclear, I'll do what I can to help you out.
First, based on the variable name pstmt I'm going to guess that this is a PreparedStatement that looks something like this:
INSERT INTO my_table (my_int, my_date, my_varchar, my_bool) VALUES (?, ?, ?, ?);

If this is the case, then you don't need to do any reflection at all, because Parameter 1 will always be an INTEGER, Parameter 2 will always be a DATE and so on.  So you know what type to use in setNull because you know the position already (because you have to, because it's the first argument to setNull), and you know the statement.  It's generally going to be much easier to follow your code if you just do the obvious thing and set the values.
if (myInt != null) {
    pstmt.setInt(1, myInt);
} else {
    pstmt.setNull(1, Types.INTEGER);
}
pstmt.setDate(2, myDate);  // already handles null
// and so on

Now, this might get a tad trickier if you're trying to set the columns in a loop for some reason.  I suggest to you that this is a bad idea because it'll be less obvious to future developers what you're up to.
However, the JDBC API has setObject for just such an occasion.  setObject will allow null values, so you don't have to handle the null and not-null cases separately.  There's even a version of setObject that will allow you to do this without specifying the type.  In that case, it's just:
for (int i = 0; i < myObjects.size(); ++i) {
    Object obj = myObjects.get(i);
    pstmt.setObject(i, obj);
}

No casting, no remembering the type, no reflection needed.  The documentation says it's not supported by every database, but I'd give this a shot before you do reflection.
Now to Answer Your Question
If, for some reason, you need to do this with reflection (because you're one of the unlucky few whose database doesn't support un-typed nulls), you were actually pretty close.
public void apply(PreparedStatement pstmt, int param, String typeName, Object value) {
    try {
        Class<?> types = Types.class;
        Field field = types.getField(typeName);
        int typeValue = field.getInt(null);

        pstmt.setObject(param, obj, typeValue);
    } catch (Exception e) {
        // handle exceptions
    }
}

So what's different here from what you were trying?  First, the field name doesn't have a . in front of it.  That's not part of the field name.  Secondly, the typeName parameter here must exactly match the java.sql.Types field name.  This is a case-sensitive String.  So, for example it's "INTEGER" not "int".  In your comment, you indicated that your st.getType() method had an ArrayList.  I've assumed that this method returns a single string, based on its knowledge of the query.  Just make sure that your type names are the same as the names used by java.sql.Types and that the object in question can actually be used as (cast / converted to) that type.


Q:

Need to show cropped image under another image

I have 5 stars on a line, and 2 kind of pictures empty and filled. I need to crop by css filled one, under empty, so that it looks like percent of fillness. But looks like I have problems with standart crop approach. Can you suggest ideas?

A:

I’d use two nested containers and do it somehow like this:
#outer {
    background: url('empty.png') top left repeat-x #666666;
    position: relative;
    height: 16px;  /* set this to the height of the image */
    width: 80px;   /* set this to a multiple of the image’s width */
}

#inner {
    background: url('filled.png') top left repeat-x #999900;
    position: absolute;
    top: 0;
    left: 0;
    height: 16px;  /* same as above */
}

Set the width property on the inner container via inline CSS as needed:
style='width: 32px;'
style='width: 64px;'

(It doesn’t necessarily have to be a multiple of one image’s width.)
Bonus: If your images don’t use transparency, the fallback background colors of the CSS will make up for percentage bars if the images fail to load.


Q:

ActionView::Template::Error (undefined method `voted_for?' for #)

I got this error when deploying my rails project to Heroku. This is my polls/_vote_option.html.erb file:

    <%= content_tag(:label) do %>
        <% unless current_user.voted_for?(@poll) %>
            <%= radio_button_tag 'vote_option[id]', option.id %>
        <% end %>
        <%= option.title %>
    <% end %>
    <%= visualize_votes_for option %>

and here is polls/_voting_form.html.erb partial
<%= form_tag votes_path, method: :post, remote: true, id: 'voting_form' do %>
    <%= hidden_field_tag 'poll[id]', @poll.id %>

    <%= render partial: 'polls/vote_option', collection: @poll.vote_options, as: :option %>

Total votes: <%= @poll.vote_summary %>

    <% if current_user.voted_for?(@poll) %>

You have already voted!

    <% else %>
        <%= submit_tag 'Vote', class: 'btn btn-lg btn-primary' %>
    <% end %>
<% end %>

here is user.rb model(voted_for? method was located here):
class User < ActiveRecord::Base

    has_many :votes, dependent: :destroy
    has_many :vote_options, through: :votes
    class << self
        def from_omniauth(auth)
            uid = auth.uid
            info = auth.info.symbolize_keys!
            user = User.find_or_initialize_by(uid: uid)
            user.name = info.name
            user.image_url = info.image
            user.save!
            user
        end

        def voted_for?(poll)
            vote_options(true).any? {|v| v.poll == poll }
        end
    end
end

and this is application_controller.rb file where current_user method belong to:
class ApplicationController < ActionController::Base
# encoding: utf-8
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find_by(id: cookies[:user_id]) if cookies[:user_id]
  end

  helper_method :current_user
end

Full error's logs here:
2015-03-27T04:36:35.317730+00:00 app[web.1]: Started GET "/polls/1" for 171.232.9.119 at 2015-03-27 04:36:35 +0000
2015-03-27T04:36:35.319482+00:00 app[web.1]:   Parameters: {"id"=>"1"}
2015-03-27T04:36:35.319468+00:00 app[web.1]: Processing by PollsController#show as HTML
2015-03-27T04:36:35.326980+00:00 app[web.1]:   Rendered polls/_vote_option.html.erb (2.4ms)
2015-03-27T04:36:35.327021+00:00 app[web.1]:   Rendered polls/_voting_form.html.erb (3.2ms)
2015-03-27T04:36:35.327088+00:00 app[web.1]:   Rendered polls/show.html.erb within layouts/application (3.4ms)
2015-03-27T04:36:35.329114+00:00 app[web.1]: ActionView::Template::Error (undefined method `voted_for?' for #<User:0x007f8c17ac4220>):
2015-03-27T04:36:35.327184+00:00 app[web.1]: Completed 500 Internal Server Error in 8ms
2015-03-27T04:36:35.329111+00:00 app[web.1]:
2015-03-27T04:36:35.329122+00:00 app[web.1]:     5:         <% end %>
2015-03-27T04:36:35.329116+00:00 app[web.1]:     1:

2015-03-27T04:36:35.329117+00:00 app[web.1]:     2:     <%= content_tag(:label) do %>
2015-03-27T04:36:35.329119+00:00 app[web.1]:     3:         <% unless current_user.voted_for?(@poll) %>
2015-03-27T04:36:35.329125+00:00 app[web.1]:   app/views/polls/_vote_option.html.erb:3:in `block in _app_views_polls__vote_option_html_erb___1797526152723756394_70119836293400'
2015-03-27T04:36:35.329120+00:00 app[web.1]:     4:             <%= radio_button_tag 'vote_option[id]', option.id %>
2015-03-27T04:36:35.329127+00:00 app[web.1]:   app/views/polls/_vote_option.html.erb:2:in `_app_views_polls__vote_option_html_erb___1797526152723756394_70119836293400'
2015-03-27T04:36:35.329133+00:00 app[web.1]:
2015-03-27T04:36:35.329124+00:00 app[web.1]:     6:         <%= option.title %>
2015-03-27T04:36:35.329128+00:00 app[web.1]:   app/views/polls/_voting_form.html.erb:4:in `block in _app_views_polls__voting_form_html_erb___1028737712551643635_70119836347660'
2015-03-27T04:36:35.329130+00:00 app[web.1]:   app/views/polls/_voting_form.html.erb:1:in `_app_views_polls__voting_form_html_erb___1028737712551643635_70119836347660'
2015-03-27T04:36:35.329131+00:00 app[web.1]:   app/views/polls/show.html.erb:5:in `_app_views_polls_show_html_erb__3711202749271403949_70119836438440'
2015-03-27T04:36:35.329134+00:00 app[web.1]:

I searched google to find solution, but other solutions were quite different from what I got. I also run heroku run rake db:migrate and the heroku restart, but nothing change after that. I really confused of why voted_for? method was not defined(according to the error's message). So can some one help me?

A:

Your method voted_for? is inside class << self, which actually creates class methods. In view you're calling voted_for? like this: current_user.voted_for?(@poll). Where current_user is an object of User class. Hence the error.
What you need is to take that method out of the class << self definition:
class << self
    def from_omniauth(auth)
        uid = auth.uid
        info = auth.info.symbolize_keys!
        user = User.find_or_initialize_by(uid: uid)
        user.name = info.name
        user.image_url = info.image
        user.save!
        user
    end

end
def voted_for?(poll)
    vote_options(true).any? {|v| v.poll == poll }
end


Q:

Bash history number not starting at 1?

I was customizing my bash prompt (I'm on OS X 10.7) when I came across something strange. Within my prompt I included !, which should give me the history number.
However the history number always starts out at 501, instead of 1. This is true even if I restart Terminal.
I can't seem to find anything close to this, I was wondering if you guys could offer some insight.

A:

From man bash:
   On startup, the history is initialized from the file named by the vari‐
   able HISTFILE (default ~/.bash_history).  The file named by  the  value
   of  HISTFILE  is  truncated,  if necessary, to contain no more than the
   number of lines specified by the value of HISTFILESIZE. [...] When an
   interactive  shell  exits, the last $HISTSIZE lines are copied from the
   history list to $HISTFILE.

While that text is quite clear, let's play a bit by example (this is a deb system, but bash is bash).
My history status right now:
~$ set | grep HIST
HISTCONTROL=ignoredups:ignorespace
HISTFILE=/home/hmontoliu/.bash_history
HISTFILESIZE=2000
HISTSIZE=1000

Since HISTFILESIZE is 2000 and HISTSIZE is 1000 only the last 1000 lines of the HISTFILE are available so you can get the wrong impression that my history starts at 1000.
~$ history | head -1
 1000  if i=1; then echo $i; done

~$ history | wc -l
1000

But indeed the HISTFILE stores the last 2000 commands:
 ~$ wc -l $HISTFILE
2000 /home/hmontoliu/.bash_history

If you think that it is annoying you can equal the HISTSIZE and HISTFILESIZE
~$ echo "export HISTSIZE=$HISTFILESIZE" >> .bashrc
~$ bash -l
~$ history | head -1
    1  ls
~$ history | wc -l
2000
~$ set | grep HIST
HISTCONTROL=ignoredups:ignorespace
HISTFILE=/home/hmontoliu/.bash_history
HISTFILESIZE=2000
HISTSIZE=2000

A final hint: you should run help history to view the actions you can do with your history

A:

The answer from hmontoliu is quite good, this is just a TL;DR version.
The bash history always picks up where you left off. It keeps a semi-permanent history of commands run in a file in your home directory. Every time you start a bash shell it loads this history file and you can scroll up to commands run in previous sessions. If you had 274 previous commands in history, your command history number on a new shell would start with 275.
The history file is truncated to a maximum length specified by the environment variable $HISTFILESIZE. You apparently have it truncated your history file to a maximum of 500 lines, so every new shell starts at 501. The previous history items are a collection of the last 500 items from previous shells.


Q:

CSRF tokens vs Nonce confusion - are they the same?

In a attempt to make the current application I'm developing more secure, I've been reading about CSRF tokens and also Nonce.
My question simply is, Are CSRF tokens and Nonce the same thing? from what I could gather so far is that both these methods have different techniques to accomplish the same goal, or am I misunderstanding something?
If they are different, could you be nice enough to provide some example code or point me to some links where i can learn more about how to implementing nonces in PHP apps.
Thanks!

A:

Nonce is usually some random string that is added to request just to change in unpredictable way the data, which is used to calculate the signature. So nonce usually is not used by any server-side business logic.
While CSRF-token is stored somewhere on server, passed to the client and need to be returned back to the server to compare. And if matches - then OK.
So in your case the better will be to save csrf token once in a session variable like
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));

and use it unchanged during the session life in all forms you have in your application.
(If you don't have random_bytes(), use random_compat to polyfill it.)

A:

No, they're not the same.
Nonces prevent replay attacks (prevent eavesdropper from storing signed request and re-submitting it later, e.g. if Alice sends "Pay Bob $100", you don't want somebody to re-send that 100 times).
CSRF tokens patch HTML-specific weakness in authentication of users' action, where 3rd party website can submit forms with credentials of user viewing the site (e.g. JavaScript on evil.example.com submitting form to facebook.com using your browser, authenticated as you).
CSRF tokens need to be secret, otherwise attacker would have the missing piece required to forge a request.
Nonces don't have to be secret if they're signed with requester's secret (as long as attacker cannot replace one nonce with another).
You can allow replay of requests with CSRF tokens and still be secured against CSRF (you're interested whether that was intentional action by the user, but may not necessarily want to stop user from performing it many times).
In fact, that's very often useful property, e.g. allows users to use Back button and re-submit forms with corrected values. If you implement CSRF protection with Nonce-like mechanism, you'll get false alarms when users refresh submitted pages.
An easy way to prevent CSRF without Nonces is to put session ID in a hidden from field (not a value stored in the session, but ID of the session itself, the same that you store in the cookie [session_id() in PHP]). When the form is submitted check that form's session ID matches ID in the cookie. That is enough for CSRF, since attacker cannot know value of the cookie (CSRF only allows attackers to blindly send cookies).

A:

It's sort of the same thing. A "nonce" is just a one-time password itself. It can serve as cryptographic salt, but basically is just a random value. See WP:Nonce
But to sum it up, a nonce is often used as CSRF token. It's an implementation detail. The difference to other use cases is that it later gets asserted.


Q:

Finding minimum in outputs of a forloop

How can we find minimum value in output of a loop without creating a list?
for i in range(1,5):
    R1=np.random.uniform(0,10,i)
    def L():
        d=R1**2
        return d
    print("i= ",i, min(L()))

this code gives minimum for each i:
i=1, 0.00477514033271
i=2, 5.65882743189
i=3, 0.783497908243
i=4, 0.224239938297

but the minimum value of the whole outputs is: 0.00477514033271
Thank yo for your help.

A:

This is a textbook problem (If I understood your question correctly).
import numpy as np

# variable to keep track of the minimum seen so far
temp = 1e10 # a big big big value
for i in range(1,5):
    R1=np.random.uniform(0,10,i)
    def L():
        d=R1**2
        return d
    m = min(L())
    if m < temp:
        temp = m
    print("i= ",i, min(L()))

print ("Min is :", temp)


Q:

What is meaning of 'Projection' in Deep Learning?

When i search for deep learning documents or paper,
sometimes i find 'Projection' on Deep learning.
but i don't know the definition of 'Projection'.
I think that the meaning of projection is change vector space to other vector space.
for example
# python code
X = np.zeros([200,100])
W = np.zeros([100,300])

XW = np.matmul(X,W) # XW shape is [200,300]

At this point, and i think X is projected onto XS.
Am I correct?

A:

Sounds like you might be referring to vector projection. I like lights, so if you imagine sitting directly under a light with your arm on a table before you... Keeping your elbow on the table, and raising your hand until your arm is at an angle into the air, the projected vector would then be the shadow of your arm/hand on the table!


Q:

why this error become (C2664 error c++ Visual Studio)

I am trying to modify an program.implemented in 2015 visual studio.  After opening the project in Visual Studio 2019 there are many errors of the type below.

Severity  Code    Description Project File    Line    Suppression State

Error C2664    'Model::Model(Model &&)': cannot convert argument 1 from 'const > char [24]' to 'GLchar *' OpenGl

Severity  Code    Description Project File    Line    Suppression State

Message        Conversion from string literal loses const qualifier (see /Zc:strictStrings)   OpenGl

Error formed in that line:
// Create a GLFWwindow object that we can use for GLFW's functions
 GLFWwindow *window = glfwCreateWindow( WIDTH, HEIGHT, "LearnOpenGL",
 nullptr, nullptr );

if ( nullptr == window )
{
    std::cout << "Failed to create GLFW window" << std::endl;
    glfwTerminate( );

    return EXIT_FAILURE;
}

glfwMakeContextCurrent( window );

glfwGetFramebufferSize( window, &SCREEN_WIDTH, &SCREEN_HEIGHT );

// Set the required callback functions
glfwSetKeyCallback( window, KeyCallback );
glfwSetCursorPosCallback( window, MouseCallback );

// GLFW Options
glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_DISABLED );

// Set this to true so GLEW knows to use a modern approach to retrieving
function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if ( GLEW_OK != glewInit( ) )
{
    std::cout << "Failed to initialize GLEW" << std::endl;
    return EXIT_FAILURE;
}

// Define the viewport dimensions
glViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );

// OpenGL options
glEnable( GL_DEPTH_TEST );

// Setup and compile our shaders
Shader shader( "res/shaders/modelLoading.vert",
 "res/shaders/modelLoading.frag" );

// Load models
Model ourModel("res/models/nanosuit.obj");

// Draw in wireframe
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

glm::mat4 projection = glm::perspective( camera.GetZoom( ), ( float
)SCREEN_WIDTH/( float )SCREEN_HEIGHT, 0.1f, 100.0f );

// Game loop
while( !glfwWindowShouldClose( window ) )
{
    // Set frame time
    GLfloat currentFrame = glfwGetTime( );
    deltaTime = currentFrame - lastFrame;
    lastFrame = currentFrame;

    // Check and call events
    glfwPollEvents( );
    DoMovement( );

    // Clear the colorbuffer
    glClearColor( 0.05f, 0.05f, 0.05f, 1.0f );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    shader.Use( );

    glm::mat4 view = camera.GetViewMatrix( );
    glUniformMatrix4fv( glGetUniformLocation( shader.Program, "projection"
       ), 1, GL_FALSE, glm::value_ptr( projection ) );
     glUniformMatrix4fv( glGetUniformLocation( shader.Program, "view" ),
       1,
    GL_FALSE, glm::value_ptr( view ) );

    // Draw the loaded model
    glm::mat4 model;
    model = glm::translate( model, glm::vec3( 0.0f, -1.75f, 0.0f ) ); //
  Translate it down a bit so it's at the center of the scene
    model = glm::scale( model, glm::vec3( 0.2f, 0.2f, 0.2f ) ); // It's a
  bit too big for our scene, so scale it down
     glUniformMatrix4fv( glGetUniformLocation( shader.Program, "model" ),
   1, GL_FALSE, glm::value_ptr( model ) );
    ourModel.Draw( shader );

    // Swap the buffers
    glfwSwapBuffers( window );
}

glfwTerminate( );
return 0;
}

         // Moves/alters the camera positions based on user input
    void DoMovement( )
          {
// Camera controls
if ( keys[GLFW_KEY_W] || keys[GLFW_KEY_UP] )
{
    camera.ProcessKeyboard( FORWARD, deltaTime );
}

if ( keys[GLFW_KEY_S] || keys[GLFW_KEY_DOWN] )
{
    camera.ProcessKeyboard( BACKWARD, deltaTime );
}

if ( keys[GLFW_KEY_A] || keys[GLFW_KEY_LEFT] )
{
    camera.ProcessKeyboard( LEFT, deltaTime );
}

if ( keys[GLFW_KEY_D] || keys[GLFW_KEY_RIGHT] )
{
    camera.ProcessKeyboard( RIGHT, deltaTime );
    **strong text**  }
}

       // Is called whenever a key is pressed/released via GLFW
    void KeyCallback( GLFWwindow *window, int key, int scancode, int
          action, int mode )
         {
if ( GLFW_KEY_ESCAPE == key && GLFW_PRESS == action )
{
    glfwSetWindowShouldClose(window, GL_TRUE);
}

if ( key >= 0 && key < 1024 )
{
    if ( action == GLFW_PRESS )
    {
        keys[key] = true;
    }
    else if ( action == GLFW_RELEASE )
    {
        keys[key] = false;
    }
}
}

   void MouseCallback( GLFWwindow *window, double xPos, double yPos )
     {
  if ( firstMouse )
{
    lastX = xPos;
    lastY = yPos;
    firstMouse = false;
}

GLfloat xOffset = xPos - lastX;
GLfloat yOffset = lastY - yPos;  // Reversed since y-coordinates go from
  bottom to left

lastX = xPos;
lastY = yPos;
camera.ProcessMouseMovement( xOffset, yOffset );
    }

the Error exactly in
       // Load models
       Model ourModel("res/models/nanosuit.obj");

A:

You could pass the model name as a non-const C string:
char tmp[] = "res/models/nanosuit.obj";
Model ourModel(tmp);


Q:

32-bit absolute addresses no longer allowed in x86-64 Linux?

64 bit Linux uses the small memory model by default, which puts all code and static data below the 2GB address limit. This makes sure that you can use 32-bit absolute addresses. Older versions of gcc use 32-bit absolute addresses for static arrays in order to save an extra instruction for relative address calculation. However, this no longer works. If I try to make a 32-bit absolute address in assembly, I get the linker error:
"relocation R_X86_64_32S against `.data' can not be used when making a shared object; recompile with -fPIC".
This error message is misleading, of course, because I am not making a shared object and -fPIC doesn't help.
What I have found out so far is this: gcc version 4.8.5 uses 32-bit absolute addresses for static arrays, gcc version 6.3.0 doesn't. version 5 probably doesn't either. The linker in binutils 2.24 allows 32-bit absolute addresses, verson 2.28 does not.
The consequence of this change is that old libraries have to be recompiled and legacy assembly code is broken.
Now I want to ask: When was this change made? Is it documented somewhere? And is there a linker option that makes it accept 32-bit absolute addresses?

A:

Your distro configured gcc with --enable-default-pie, so it's making position-independent executables by default, (allowing for ASLR of the executable as well as libraries).  Most distros are doing that, these days.
You actually are making a shared object: PIE executables are sort of a hack using a shared object with an entry-point.  The dynamic linker already supported this, and ASLR is nice for security, so this was the easiest way to implement ASLR for executables.
32-bit absolute relocation aren't allowed in an ELF shared object; that would stop them from being loaded outside the low 2GiB (for sign-extended 32-bit addresses).  64-bit absolute addresses are allowed, but generally you only want that for jump tables or other static data, not as part of instructions.1
The recompile with -fPIC part of the error message is bogus for hand-written asm; it's written for the case of people compiling with gcc -c and then trying to link with gcc -shared -o foo.so  *.o, with a gcc where -fPIE is not the default.  The error message should probably change because many people are running into this error when linking hand-written asm.

How to use RIP-relative addressing: basics
Always use RIP-relative addressing for simple cases where there's no downside.  See also footnote 1 below and this answer for syntax.    Only consider using 32-bit absolute addressing when it's actually helpful for code-size instead of harmful. e.g. NASM default rel at the top of your file.
AT&T foo(%rip) or in GAS .intel_syntax noprefix use [rip + foo].

Disable PIE mode to make 32-bit absolute addressing work
Use gcc -fno-pie -no-pie to override this back to the old behaviour. -no-pie is the linker option, -fno-pie is the code-gen option.  With only -fno-pie, gcc will make code like mov eax, offset .LC0 that doesn't link with the still-enabled -pie.
(clang can have PIE enabled by default, too: use clang -fno-pie -nopie.  A July 2017 patch made -no-pie an alias for -nopie, for compat with gcc, but clang4.0.1 doesn't have it.)

Performance cost of PIE for 64-bit (minor) or 32-bit code (major)
With only -no-pie, (but still -fpie) compiler-generated code (from C or C++ sources) will be slightly slower and larger than necessary, but will still be linked into a position-dependent executable which won't benefit from ASLR.  "Too much PIE is bad for performance" reports an average slowdown of 3% for x86-64 on SPEC CPU2006 (I don't have a copy of the paper so IDK what hardware that was on :/).  But in 32-bit code, the average slowdown is 10%, worst-case 25% (on SPEC CPU2006).
The penalty for PIE executables is mostly for stuff like indexing static arrays, as Agner describes in the question, where using a static address as a 32-bit immediate or as part of a [disp32 + index*4] addressing mode saves instructions and registers vs. a RIP-relative LEA to get an address into a register.  Also 5-byte mov r32, imm32 instead of 7-byte lea r64, [rel symbol] for getting a static address into a register is nice for passing the address of a string literal or other static data to a function.
-fPIE still assumes no symbol-interposition for global variables / functions, unlike -fPIC for shared libraries which have to go through the GOT to access globals (which is yet another reason to use static for any variables that can be limited to file scope instead of global).   See The sorry state of dynamic libraries on Linux.
Thus -fPIE is much less bad than -fPIC for 64-bit code, but still bad for 32-bit because RIP-relative addressing isn't available.  See some examples on the Godbolt compiler explorer.  On average, -fPIE has a very small performance / code-size downside in 64-bit code.  The worst case for a specific loop might only be a few %.  But 32-bit PIE can be much worse.
None of these -f code-gen options make any difference when just linking,
or when assembling .S hand-written asm.  gcc -fno-pie -no-pie -O3 main.c nasm_output.o is a case where you want both options.

Checking your GCC config
If your GCC was configured this way, gcc -v |& grep -o -e '[^ ]*pie'  prints --enable-default-pie.  Support for this config option was added to gcc in early 2015.  Ubuntu enabled it in 16.10, and Debian around the same time in gcc 6.2.0-7 (leading to kernel build errors: https://lkml.org/lkml/2016/10/21/904).
Related: Build compressed x86 kernels as PIE was also affected by the changed default.
Why doesn't Linux randomize the address of the executable code segment? is an older question about why it wasn't the default earlier, or was only enabled for a few packages on older Ubuntu before it was enabled across the board.

Note that ld itself didn't change its default.  It still works normally (at least on Arch Linux with binutils 2.28).  The change is that gcc defaults to passing -pie as a linker option, unless you explicitly use -static or -no-pie.
In a NASM source file, I used a32 mov eax, [abs buf] to get an absolute address.  (I was testing if the 6-byte way to encode small absolute addresses (address-size + mov eax,moffs: 67 a1 40 f1 60 00) has an LCP stall on Intel CPUs.  It does.)
nasm -felf64 -Worphan-labels -g -Fdwarf testloop.asm &&
ld -o testloop testloop.o              # works: static executable

gcc -v -nostdlib testloop.o            # doesn't work
...
..../collect2  ... -pie ...
/usr/bin/ld: testloop.o: relocation R_X86_64_32 against `.bss' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status

gcc -v -no-pie -nostdlib testloop.o    # works
gcc -v -static -nostdlib testloop.o    # also works: -static implies -no-pie

GCC can also make a "static PIE" with -static-pie; ASLRed by no dynamic libraries or ELF interpreter.  Not the same thing as -static -pie - those conflict with each other (you get a static non-PIE) although it might possibly get changed.
related: building static / dynamic executables with/without libc, defining _start or main.

Checking if an existing executable is PIE or not
file and readelf say that PIEs are "shared objects", not ELF executables.  ELF-type EXEC can't be PIE.
$ gcc -fno-pie  -no-pie -O3 hello.c
$ file a.out
a.out: ELF 64-bit LSB executable, ...

$ gcc -O3 hello.c
$ file a.out
a.out: ELF 64-bit LSB shared object, ...

 ## Or with a more recent version of file:
a.out: ELF 64-bit LSB pie executable, ...

gcc -static-pie shows up as LSB pie executable, dynamically linked with current file.  It's ELF-type DYN, but readelf shows no .interp, and ldd will tell you it's statically linked.  GDB starti and /proc/maps confirms that execution starts at the top of its _start, not in an ELF interpreter.
This has also been asked at: How to test whether a Linux binary was compiled as position independent code?

Semi-related (but not really): another recent gcc feature is gcc -fno-plt.  Finally calls into shared libraries can be just call [rip + symbol@GOTPCREL] (AT&T call *puts@GOTPCREL(%rip)), with no PLT trampoline.
The NASM version of this is call [rel puts wrt ..got]
as an alternative to call puts wrt ..plt.  See Can't call C standard library function on 64-bit Linux from assembly (yasm) code.  This works in a PIE or non-PIE, and avoids having the linker build a PLT stub for you.
Some distros have started enabling it.  It also avoids needing writeable + executable memory pages so it's good for security against code-injection.  It's a significant speedup for programs that make a lot of shared-library calls, e.g. x86-64 clang -O2 -g compiling tramp3d goes from 41.6s to 36.8s on whatever hardware the patch author tested on.  (clang is maybe a worst-case scenario for shared library calls, making lots of calls to small LLVM library functions.)
It does require early binding instead of lazy dynamic linking, so it's slower for big programs that exit right away.  (e.g. clang --version or compiling hello.c).  This slowdown could be reduced with prelink, apparently.
This doesn't remove the GOT overhead for external variables in shared library PIC code, though.  (See the godbolt link above).

Footnotes 1
64-bit absolute addresses actually are allowed in Linux ELF shared objects, with text relocations to allow loading at different addresses (ASLR and shared libraries).  This allows you to have jump tables in section .rodata, or static const int *foo = &bar; without a runtime initializer.
So mov rdi, qword msg works (NASM/YASM syntax for 10-byte mov r64, imm64, aka AT&T syntax movabs, the only instruction which can use a 64-bit immediate).  But that's larger and usually slower than lea rdi, [rel msg], which is what you should use if you decide not to disable -pie.  A 64-bit immediate is slower to fetch from the uop cache on Sandybridge-family CPUs, according to Agner Fog's microarch pdf.  (Yes, the same person who asked this question. :)
You can use NASM's default rel instead of specifying it in every [rel symbol] addressing mode.  See also Mach-O 64-bit format does not support 32-bit absolute addresses. NASM Accessing Array for some more description of avoiding 32-bit absolute addressing.  OS X can't use 32-bit addresses at all, so RIP-relative addressing is the best way there, too.
In position-dependent code (-no-pie), you should use mov edi, msg when you want an address in a register; 5-byte mov r32, imm32 is even smaller than RIP-relative LEA, and more execution ports can run it.


Q:

Ember.js: Cannot access injected object

I created a Session object:
App.Session = Ember.Object.extend({
  user: null,
  userID: '',
});

I injected this object:
Ember.Application.initializer({
name: 'login',
initialize: function (container, application) {
  App.register('session:main', App.Session, { instantiate: false, singleton: true });
  // Add `session` object to route to check user
  App.inject('route', 'session', 'session:main');
  // Add `session` object to controller to visualize in templates
  App.inject('controller', 'session', 'session:main');

  App.register('firebase:main', App.Firebase);
  // Add `session` object to route to check user
  App.inject('route', 'firebase', 'firebase:main');
  // Add `session` object to controller to visualize in templates
  App.inject('controller', 'firebase', 'firebase:main');
  }
});

I want to set the userID property of Session to the ID of the current user as per follow:
Ember.Route.reopen({
  beforeModel: function (transition) {
    var isAuth = false;
    var user = '';
    var store = this.store;
    var _this = this;
    var firebase = new Firebase("https://dynamicslife.firebaseio.com");
    firebase.onAuth(function(authData) {
      if (authData) {
        isAuth = true;
        _this.session.userID = authData.id; //THIS OPERATIONS IS NOT WORKING!!!!!!
      } else {
        isAuth = false;
      }
    });

    // These routes you do not need to be logged in to access.
    var openRoutes = ['home','index','about','stories'];
    var testMode = false;
    if (testMode == false) {
    if (openRoutes.indexOf(transition.targetName) === -1 && isAuth === false) {
      console.log('Please login to access this information');
      this.transitionTo('stories');
    }
  }
 }
});

In the code expression identified above by: //THIS OPERATIONS IS NOT WORKING!!!!!!, the authData.id contains the proper ID value. However the _this.session.userID remains undefined.
I tried to replace _this.session.userID = authData.id; with  _this.session.set('userID', authData.id); but this gave me the same error.
I think that maybe the Session object is not injected into Ember.Route.reopen. If this is the case, how can I get access to the Session object from the the Ember.Route.reopen?
Because the session.userID is undefined, I get the following error:
Error while processing route: statistics.index session is not defined ReferenceError: session is not defined

When Ember run this:
App.StatisticsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('user', session.userID);
  },
});

A:

You're telling it not to instantiate App.Session, which means it's the object you want to use, but it's a class not an instance
App.register('session:main', App.Session.create(), { instantiate: false, singleton: true });

and session exists on this in the route, not on the global namespace.
App.StatisticsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('user', this.session.get('userID'));
  },
});

And you should definitely use a setter
 _this.session.set('userID', authData.id);


Q:

How to use a Constant value of a class field in a layout?

I would like to use some java class constant value in my XML layout. Is that possible?
java class
public class ConstantKey {

   public static final String COUNTRY_CODE            = "+00";
   public static final STRING COUNTRY_NAME            = "USA";

}

Xml layout
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="ConstantKey.COUNTRY_NAME"/>

A:

You could:
1) If the strings are constant all through, you could add them as string resources inside strings.xml. This way they're accessed from both layout or java code.
2) If the values depend on a network call or are dynamically computed, I suggest using DataBinding in andorid, check my answer here for small implementation example.