问:
How to get the IID_TOKEN for Google Instance ID service?
I am trying to register a topic with FCM using the below code. As per my understanding i need two Keys to register, first is IID_TOKEN and second is FCM_APP_KEY.

I have FCM_APP_KEY, but I am unable to find the cosole or site from where i can get the Google Instance ID service token(IID_TOKEN).

It will be of great help if someone one can tell the process or site to get the IID_TOKEN. Thanks in advance.

```<code>https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC
Content-Type:application/json
Authorization:key=FCM_APP_KEY
</code>```

答:
You don't need to register a topic.

Topics are automatically created when the application calls

```<code>FirebaseCloudMessaging.getInstance().subscribeToTopic("topic-name")
</code>```

The API you mentioned in the question is used when you have the
FirebaseInstanceId token of an (mobile / client) application
(obtained via FirebaseInstanceId.getInstance().getToken()) and you want to subscribe that application to a specific topic from your server side, instead of calling the subscribeToTopic(..) method mentioned above in the client.

Body:
I am trying to register a topic with FCM using the below code. As per my understanding i need two Keys to register, first is IID_TOKEN and second is FCM_APP_KEY.

I have FCM_APP_KEY, but I am unable to find the cosole or site from where i can get the Google Instance ID service token(IID_TOKEN).

It will be of great help if someone one can tell the process or site to get the IID_TOKEN. Thanks in advance.

https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC
Content-Type:application/json
Authorization:key=FCM_APP_KEY

Body:
You don't need to register a topic.

Topics are automatically created when the application calls

FirebaseCloudMessaging.getInstance().subscribeToTopic("topic-name")

The API you mentioned in the question is used when you have the
FirebaseInstanceId token of an (mobile / client) application
(obtained via FirebaseInstanceId.getInstance().getToken()) and you want to subscribe that application to a specific topic from your server side, instead of calling the subscribeToTopic(..) method mentioned above in the client.


来源: stackexchange

问:
Clean code - Where should @Autowired be applied?
I'll start with a simple example. You have a Spring boot application that runs a CommandLineRunner class on initialization.

```<code>// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    @Autowired //IntelliJ Warning
    private DataSource ds;
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner();
    }
}
</code>```

Now, like this, this works, everything is OK. However, IntelliJ reports a warning where @Autowired is located (I marked where in the comment)

Spring team recommends: Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies.

Now if I follow this, I have a constructor based dependency injection

```<code>@Autowired
public MyCommandLineRunner(DataSource ds) { ... }
</code>```

This also means that I have to edit Application.java as well, since the constructor needs an argument. In Application.java if I try to use the setter injection, I'll get the same warning. If I refactor that as well, I'll end up with some, in my opinion, nasty code.

```<code>// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private DataSource ds;
    @Autowired // Note that this line is practically useless now, since we're getting this value as a parameter from Application.java anyway.
    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    private DataSource ds;
    @Autowired
    public Application(DataSource ds) { this.ds = ds; }
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner(ds);
    }
}
</code>```

The above code yields the same result, but doesn't report any warnings in IntelliJ.
I'm confused, how is the 2nd code better than the first one? Am I following an incorrect logic? Should this be wired differently?

In short, what's the correct way to do this?

note DataSource is just a pure example, this question applies to anything being autowired.

note 2 Just to say that MyCommandLineRunner.java can't have another, empty, constructor, since DataSource needs to be autowired/initialized. It will report an error and will not be compiled.

答:
Consider making the field ds final, then you don't need @Autowired. See more about dependency injection http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html#using-boot-spring-beans-and-dependency-injection

To keep the code clean, have you considered using Lombok annotations? @RequiredArgsConstructor(onConstructor = @__(@Autowired))
would generate the constructor with @Autowired annotations. See more here
https://projectlombok.org/features/Constructor.html

Your code could look like this:

```<code>@Slf4j
@RequiredArgsConstructor
// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {

    //final fields are included in the constructor generated by Lombok
    private final DataSource ds;

    @Override
    public void run(String... args) throws Exception {
        log.info("DataSource: {} ", ds.toString());
    }
}

// Application.java
@SpringBootApplication
@RequiredArgsConstructor(onConstructor_={@Autowired}) // from JDK 8
// @RequiredArgsConstructor(onConstructor = @__(@Autowired)) // up to JDK 7
public class Application {

    private final Datasource ds;

    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner(ds);
    }
}
</code>```

Later edit

Solution without Lombok relies on Spring to inject dependency  when the bean is created

```<code>@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    /**
     * dependency ds is injected by Spring
     */
    public MyCommandLineRunner schedulerRunner(DataSource ds) {
        return new MyCommandLineRunner(ds);
    }
}

// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());

    private final DataSource ds;

    public MyCommandLineRunner(DataSource ds){
        this.ds = ds;
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: "+ ds.toString());
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'll start with a simple example. You have a Spring boot application that runs a CommandLineRunner class on initialization.

// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    @Autowired //IntelliJ Warning
    private DataSource ds;
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner();
    }
}

Now, like this, this works, everything is OK. However, IntelliJ reports a warning where @Autowired is located (I marked where in the comment)

Spring team recommends: Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies.

Now if I follow this, I have a constructor based dependency injection

@Autowired
public MyCommandLineRunner(DataSource ds) { ... }

This also means that I have to edit Application.java as well, since the constructor needs an argument. In Application.java if I try to use the setter injection, I'll get the same warning. If I refactor that as well, I'll end up with some, in my opinion, nasty code.

// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    private DataSource ds;
    @Autowired // Note that this line is practically useless now, since we're getting this value as a parameter from Application.java anyway.
    public MyCommandLineRunner(DataSource ds) { this.ds = ds; }
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    private DataSource ds;
    @Autowired
    public Application(DataSource ds) { this.ds = ds; }
    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner(ds);
    }
}

The above code yields the same result, but doesn't report any warnings in IntelliJ.
I'm confused, how is the 2nd code better than the first one? Am I following an incorrect logic? Should this be wired differently?

In short, what's the correct way to do this?

note DataSource is just a pure example, this question applies to anything being autowired.

note 2 Just to say that MyCommandLineRunner.java can't have another, empty, constructor, since DataSource needs to be autowired/initialized. It will report an error and will not be compiled.

Body:
Consider making the field ds final, then you don't need @Autowired. See more about dependency injection http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html#using-boot-spring-beans-and-dependency-injection

To keep the code clean, have you considered using Lombok annotations? @RequiredArgsConstructor(onConstructor = @__(@Autowired))
would generate the constructor with @Autowired annotations. See more here
https://projectlombok.org/features/Constructor.html

Your code could look like this:

@Slf4j
@RequiredArgsConstructor
// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {

    //final fields are included in the constructor generated by Lombok
    private final DataSource ds;

    @Override
    public void run(String... args) throws Exception {
        log.info("DataSource: {} ", ds.toString());
    }
}

// Application.java
@SpringBootApplication
@RequiredArgsConstructor(onConstructor_={@Autowired}) // from JDK 8
// @RequiredArgsConstructor(onConstructor = @__(@Autowired)) // up to JDK 7
public class Application {

    private final Datasource ds;

    public static void main(String... args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner(ds);
    }
}

Later edit

Solution without Lombok relies on Spring to inject dependency  when the bean is created

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    /**
     * dependency ds is injected by Spring
     */
    public MyCommandLineRunner schedulerRunner(DataSource ds) {
        return new MyCommandLineRunner(ds);
    }
}

// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());

    private final DataSource ds;

    public MyCommandLineRunner(DataSource ds){
        this.ds = ds;
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: "+ ds.toString());
    }
}


问:
How do I find a value in an array in the specific situation?
I am creating an array that stores a name and a bowling score from the same line and then using Split() to split the name and score into two separate arrays.  Then I need to find the highest score along with the name with the highest score and write it to the console using a method somehow.

Here is what i have so far.  Thanks.

```<code>    const int SIZE = 10;

    string[] arrayNames = new string[SIZE];
    int[] arrayScores = new int[SIZE];

    for (int i = 0; i < SIZE; i++){
        Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

        string input = ReadLine();

        if (input == ""){
            break;
        }
        string[] scoreInfo = input.Split();
        arrayNames[i] = scoreInfo[0];

        bool valid = false;
        do{
            if (input == ""){
                break;
            }
            valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
            valid = valid && (arrayScores[i] <= 300);

        } while (!valid);

    }

    int max = bowling.CalcHighest(arrayScores);
    int min = bowling.CalcLowest(arrayScores);
    int average = bowling.CalcAverage(arrayScores);
</code>```

答:
In your for loop, you already have the highest score, you just need to keep track of it. arrayScores[i]

Here's what I'd do:

```<code>const int SIZE = 10;

string[] arrayNames = new string[SIZE];
int[] arrayScores = new int[SIZE];

int highScore = 0;
string winner = "";

for (int i = 0; i < SIZE; i++){
    Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

    string input = ReadLine();

    if (input == ""){
        break;
    }
    string[] scoreInfo = input.Split();
    arrayNames[i] = scoreInfo[0];

    bool valid = false;
    do{
        if (input == ""){
            break;
        }
        valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
        valid = valid && (arrayScores[i] <= 300);

        if(valid && arrayScores[i] > highScore){
            highScore = arrayScores[i];
            winner = arrayNames[i];
        }

    } while (!valid);

}
</code>```

Then just grab the winner and highScore after the completion of the for loop.

ContentLicense: CC BY-SA 3.0

Body:
I am creating an array that stores a name and a bowling score from the same line and then using Split() to split the name and score into two separate arrays.  Then I need to find the highest score along with the name with the highest score and write it to the console using a method somehow.

Here is what i have so far.  Thanks.

    const int SIZE = 10;

    string[] arrayNames = new string[SIZE];
    int[] arrayScores = new int[SIZE];

    for (int i = 0; i < SIZE; i++){
        Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

        string input = ReadLine();

        if (input == ""){
            break;
        }
        string[] scoreInfo = input.Split();
        arrayNames[i] = scoreInfo[0];

        bool valid = false;
        do{
            if (input == ""){
                break;
            }
            valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
            valid = valid && (arrayScores[i] <= 300);

        } while (!valid);

    }

    int max = bowling.CalcHighest(arrayScores);
    int min = bowling.CalcLowest(arrayScores);
    int average = bowling.CalcAverage(arrayScores);

Body:
In your for loop, you already have the highest score, you just need to keep track of it. arrayScores[i]

Here's what I'd do:

const int SIZE = 10;

string[] arrayNames = new string[SIZE];
int[] arrayScores = new int[SIZE];

int highScore = 0;
string winner = "";

for (int i = 0; i < SIZE; i++){
    Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

    string input = ReadLine();

    if (input == ""){
        break;
    }
    string[] scoreInfo = input.Split();
    arrayNames[i] = scoreInfo[0];

    bool valid = false;
    do{
        if (input == ""){
            break;
        }
        valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
        valid = valid && (arrayScores[i] <= 300);

        if(valid && arrayScores[i] > highScore){
            highScore = arrayScores[i];
            winner = arrayNames[i];
        }

    } while (!valid);

}

Then just grab the winner and highScore after the completion of the for loop.


问:
Android insert date into datetime SQLite
I'm working with a sqlite-android which contains a table with a field "datetime",

I'm trying to insert a value in that table with :

```<code> ContentValues cvv = new ContentValues();

            cvv.put("viatge_id",v.getId());
            ....
            cvv.put("time",s.getDate());
</code>```

s.getDate returns a Date Element. but it seems i can't use the last instruction that I show you

答:
Can't you just convert the Date instance to ms and then insert the long into your DB?

So

```<code>cvv.put("time",s.getDate().getTime());
</code>```

Body:
I'm working with a sqlite-android which contains a table with a field "datetime",

I'm trying to insert a value in that table with :

 ContentValues cvv = new ContentValues();

            cvv.put("viatge_id",v.getId());
            ....
            cvv.put("time",s.getDate());

s.getDate returns a Date Element. but it seems i can't use the last instruction that I show you

Body:
Can't you just convert the Date instance to ms and then insert the long into your DB?

So

cvv.put("time",s.getDate().getTime());


问:
Why doesn't JPanel (panel) get drawn on the green background (the jpanel)?
Why doesn't JPanel (panel) get drawn on the green background (the jpanel)? I want to be able to do this without extending j panel to...

Furthermore, for java games should i use keybindings or keylistener in java.

```<code>import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class Game {

JFrame window;
JPanel panel;

int charPosX = 0;
int charPosY = 0;

public Boolean createGui() {

    window = new JFrame("Game");
    window.setSize(1000,500);
    window.setResizable(false);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    panel = new JPanel();
    panel.setVisible(true);
    panel.setLayout(null);;
    panel.setBackground(new Color(65,130,92));

    window.add(panel);

    return true; //returns true if ran and will be ran by check status in Main.
}

public void paintComponent(Graphics g) {
    panel.paintComponents(g);
    g.setColor(Color.RED);
    g.drawRect(100,10,30,40);
    g.fillRect(10, 10, 20, 10);
}

}
</code>```

答:
Let's take your code for a second and add @Override to your paintComponent method...

```<code>public class Game {

    //...

    @Override
    public void paintComponent(Graphics g) {
        panel.paintComponents(g);
        g.setColor(Color.RED);
        g.drawRect(100, 10, 30, 40);
        g.fillRect(10, 10, 20, 10);
    }

}
</code>```

And now we have a compiler error!  This is because Game extends Object and does not have a paintComponent method.  This means that there is no way that the method could be called by any part of the existing painting system, so, it never gets called.

Components make poor "game" entities, they have a lot of "plumbing" which doesn't make them very efficient for this kind of work, you're generally better off heading down a complete custom painting route

```<code>import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Game {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Game().createGui();
            }
        });
    }

    JFrame window;
    GamePanel panel;

    int charPosX = 0;
    int charPosY = 0;

    public Boolean createGui() {

        window = new JFrame("Game");
        window.setSize(1000, 500);
        window.setResizable(false);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new GamePanel();
        panel.setBackground(new Color(65, 130, 92));
        window.add(panel);

        window.setVisible(true);
        return true; //returns true if ran and will be ran by check status in Main.
    }

    public class GamePanel extends JPanel {

        private Rectangle entity = new Rectangle(100, 10, 30, 40);

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            g2d.draw(entity);
            g2d.setColor(Color.BLUE);
            g2d.fill(entity);
            g2d.dispose();
        }

    }

}
</code>```

Also note, I called window.setVisible(true); only after I had added the panel to the window, this is because Swing is lazy when it comes to adding/removing components.  If you want to add/remove components after the UI has been realized on the screen, you'll need to call revalidate and repaint on the container to trigger a layout and paint pass

Also, beware, there is a difference between paintComponent and paintComponents ;)

I would highly recommend having a look at Painting in AWT Swing and Performing Custom Painting to gain a better understanding of how painting works in Swing and how you can take advantage of it

Body:
Why doesn't JPanel (panel) get drawn on the green background (the jpanel)? I want to be able to do this without extending j panel to...

Furthermore, for java games should i use keybindings or keylistener in java.

import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class Game {

JFrame window;
JPanel panel;

int charPosX = 0;
int charPosY = 0;

public Boolean createGui() {

    window = new JFrame("Game");
    window.setSize(1000,500);
    window.setResizable(false);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    panel = new JPanel();
    panel.setVisible(true);
    panel.setLayout(null);;
    panel.setBackground(new Color(65,130,92));

    window.add(panel);

    return true; //returns true if ran and will be ran by check status in Main.
}

public void paintComponent(Graphics g) {
    panel.paintComponents(g);
    g.setColor(Color.RED);
    g.drawRect(100,10,30,40);
    g.fillRect(10, 10, 20, 10);
}

}

Body:
Let's take your code for a second and add @Override to your paintComponent method...

public class Game {

    //...

    @Override
    public void paintComponent(Graphics g) {
        panel.paintComponents(g);
        g.setColor(Color.RED);
        g.drawRect(100, 10, 30, 40);
        g.fillRect(10, 10, 20, 10);
    }

}

And now we have a compiler error!  This is because Game extends Object and does not have a paintComponent method.  This means that there is no way that the method could be called by any part of the existing painting system, so, it never gets called.

Components make poor "game" entities, they have a lot of "plumbing" which doesn't make them very efficient for this kind of work, you're generally better off heading down a complete custom painting route

import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Game {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Game().createGui();
            }
        });
    }

    JFrame window;
    GamePanel panel;

    int charPosX = 0;
    int charPosY = 0;

    public Boolean createGui() {

        window = new JFrame("Game");
        window.setSize(1000, 500);
        window.setResizable(false);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new GamePanel();
        panel.setBackground(new Color(65, 130, 92));
        window.add(panel);

        window.setVisible(true);
        return true; //returns true if ran and will be ran by check status in Main.
    }

    public class GamePanel extends JPanel {

        private Rectangle entity = new Rectangle(100, 10, 30, 40);

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            g2d.draw(entity);
            g2d.setColor(Color.BLUE);
            g2d.fill(entity);
            g2d.dispose();
        }

    }

}

Also note, I called window.setVisible(true); only after I had added the panel to the window, this is because Swing is lazy when it comes to adding/removing components.  If you want to add/remove components after the UI has been realized on the screen, you'll need to call revalidate and repaint on the container to trigger a layout and paint pass

Also, beware, there is a difference between paintComponent and paintComponents ;)

I would highly recommend having a look at Painting in AWT Swing and Performing Custom Painting to gain a better understanding of how painting works in Swing and how you can take advantage of it


问:
How to get user information with Facebook PHP API
I use the Facebook API and I wish retrieve Facebook information of the connected user. I can retrieve the information in javascript, but I want to get the information to fill the PHP stored in my database.

Here is my code in javascript function:

```<code>    <html>
    <head>
        <title>My Application</title>
        <style type="text/css">
            div { padding: 10px; }
        </style>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
          var fbAppId = 'myAppId';
          var objectToLike = 'http://techcrunch.com/2013/02/06/facebook-launches-developers-live-video-channel-to-keep-its-developer-ecosystem-up-to-date/';

          if (fbAppId === 'replace me') {
            alert('Please set the fbAppId in the sample.');
          }

          window.fbAsyncInit = function() {
            FB.init({
              appId      : fbAppId,        // App ID
              status     : true,           // check login status
              cookie     : true,           // enable cookies to allow the server to access the session
              xfbml      : true            // parse page for xfbml or html5 social plugins like login button below
            });

            FB.login(function(response) {
               if (response.authResponse) {
                 FB.api('/me', function(response) {
                   window.alert(response.last_name + ', ' + response.first_name + ", " + response.email);
                 });
               }
             });
          };

          (function(d, s, id){
             var js, fjs = d.getElementsByTagName(s)[0];
             if (d.getElementById(id)) {return;}
             js = d.createElement(s); js.id = id;
             js.src = "//connect.facebook.net/en_US/all.js";
             fjs.parentNode.insertBefore(js, fjs);
           }(document, 'script', 'facebook-jssdk'));

        </script>
</body>
</html>
</code>```

Here is my PHP code I can not make it work

```<code><?php
require_once("php-sdk/facebook.php");

$config = array();
$config['appId'] = 'myAppId';
$config['secret'] = 'myCodeSecret';
$config['fileUpload'] = false; // optional

$facebook = new Facebook($config);

$user = $facebook->getUser();

$user_profile = $facebook->api('/me','GET');
echo "Name: " . $user_profile['name'];
?>
</code>```

If I display the variable $user, I get my user id. But then I can not get other information.

I looked more in detail and this may be a problem in the configuration of the application in Facebook. Could you explain the steps to create an application on Facebook?

答:
From here:</p>

```<code>$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',
  ]);

try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['name'];
// OR
// echo 'Name: ' . $user->getName();
</code>```

Body:
I use the Facebook API and I wish retrieve Facebook information of the connected user. I can retrieve the information in javascript, but I want to get the information to fill the PHP stored in my database.

Here is my code in javascript function:

        <title>My Application</title>

        <meta charset="UTF-8">

Here is my PHP code I can not make it work

<?php
require_once("php-sdk/facebook.php");

$config = array();
$config['appId'] = 'myAppId';
$config['secret'] = 'myCodeSecret';
$config['fileUpload'] = false; // optional

$facebook = new Facebook($config);

$user = $facebook->getUser();

$user_profile = $facebook->api('/me','GET');
echo "Name: " . $user_profile['name'];
?>

If I display the variable $user, I get my user id. But then I can not get other information.

I looked more in detail and this may be a problem in the configuration of the application in Facebook. Could you explain the steps to create an application on Facebook?

Body:
From here:

$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',
  ]);

try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['name'];
// OR
// echo 'Name: ' . $user->getName();


问:
NHibernate MappingException
I have been interested in learning NHibernate, so i search a course, and i found one in Pluralsight, but when i go to follow the examples i get this exception and i don't know why i get this exception... and it's kind of annoying because where i search i can't find more info about the exception or an up-to-date guide of NHibernate. So my question is:

a) for the exception itself, why it occurs

b) if you can recommend me a site or a course or anything up to date to learn NHibernate.

Thanks in advance.

I leave the code here:

Customer.cs:

```<code>namespace NHibernateDemo
{
    public class Customer
    {
        public virtual int Id { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
    }
}
</code>```

Customer.hbm.xml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:hibernate-mapping-2.2"
                   assembly="NHibernateDemo"
                   namespace="NHibernateDemo">
  <class name="Customer">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="FirstName"/>
    <property name="LastName"/>
  </class>
</hibernate-mapping>
</code>```

Program.cs:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace NHibernateDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
            {
                x.ConnectionString = "Server=localhost;Database=NHibernateDemo;Integrated Security=SSPI;";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSql2008Dialect>();
            });

            // Here is where i get the MappingException. It says that it can't compile the Customer.hbm.xml file.
            cfg.AddAssembly(Assembly.GetExecutingAssembly());

            var sessionFactory = cfg.BuildSessionFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    var customers = session.CreateCriteria<Customer>()
                                           .List<Customer>();
                    foreach (var customer in customers)
                    {
                        Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
                    }
                    tx.Commit();
                }
                Console.WriteLine("Press <ENTER> to exit...");
                Console.ReadLine();
            }
        }
    }
}
</code>```

Message of the exception:

```<code>"Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml"
</code>```

StackTrace:

```<code>    NHibernate.MappingException: Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml ---> System.InvalidOperationException: Error en el documento XML (1, 2). ---> System.InvalidOperationException: No se esperaba <hibernate-mapping xmlns='urn:hibernate-mapping-2.2'>.
   en Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderHbmMapping.Read109_hibernatemapping()
   --- Fin del seguimiento de la pila de la excepción interna ---
   en System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   en System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document, XmlSerializer serializer)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   --- Fin del seguimiento de la pila de la excepción interna ---
   en NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   en NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
   en NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
   en NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
   en NHibernateDemo.Program.Main(String[] args) en d:\Sistema\Documents\Visual Studio 2015\Projects\NHibernateDemo\NHibernateDemo\Program.cs:línea 28
</code>```

答:
I found (thanks to Fréderic) that the problem was a line in the hbm.xml file. This line was the one that have make the problem occur: <hibernate-mapping xmlns="urn:hibernate-mapping-2.2".
 I forgot a 'n' in front of the 'hibernate' word and because of that it can't parse the file.

Thanks to Taki and Fréderic for the time.

Title: NHibernate MappingException

Body:
I have been interested in learning NHibernate, so i search a course, and i found one in Pluralsight, but when i go to follow the examples i get this exception and i don't know why i get this exception... and it's kind of annoying because where i search i can't find more info about the exception or an up-to-date guide of NHibernate. So my question is:

a) for the exception itself, why it occurs

b) if you can recommend me a site or a course or anything up to date to learn NHibernate.

Thanks in advance.

I leave the code here:

Customer.cs:

namespace NHibernateDemo
{
    public class Customer
    {
        public virtual int Id { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
    }
}

Customer.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:hibernate-mapping-2.2"
                   assembly="NHibernateDemo"
                   namespace="NHibernateDemo">
  <class name="Customer">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="FirstName"/>
    <property name="LastName"/>
  </class>
</hibernate-mapping>

Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace NHibernateDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
            {
                x.ConnectionString = "Server=localhost;Database=NHibernateDemo;Integrated Security=SSPI;";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSql2008Dialect>();
            });

            // Here is where i get the MappingException. It says that it can't compile the Customer.hbm.xml file.
            cfg.AddAssembly(Assembly.GetExecutingAssembly());

            var sessionFactory = cfg.BuildSessionFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    var customers = session.CreateCriteria<Customer>()
                                           .List<Customer>();
                    foreach (var customer in customers)
                    {
                        Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
                    }
                    tx.Commit();
                }
                Console.WriteLine("Press <ENTER> to exit...");
                Console.ReadLine();
            }
        }
    }
}

Message of the exception:

"Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml"

StackTrace:

    NHibernate.MappingException: Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml ---> System.InvalidOperationException: Error en el documento XML (1, 2). ---> System.InvalidOperationException: No se esperaba <hibernate-mapping xmlns='urn:hibernate-mapping-2.2'>.
   en Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderHbmMapping.Read109_hibernatemapping()
   --- Fin del seguimiento de la pila de la excepción interna ---
   en System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   en System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document, XmlSerializer serializer)
   en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   --- Fin del seguimiento de la pila de la excepción interna ---
   en NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
   en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
   en NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
   en NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
   en NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
   en NHibernateDemo.Program.Main(String[] args) en d:\Sistema\Documents\Visual Studio 2015\Projects\NHibernateDemo\NHibernateDemo\Program.cs:línea 28


问:
reading file using istringstream, unexpected output
I have a .txt file with tab separated data(several rows):

```<code>    42  2   62
    2   2   42
    2   2   62
</code>```

I tried to use istringstream to read the data from the file, and then use each column's data for each respective row as locations for adding 1's into a 2-D array.

This was to loop until the 2-D array was filled with 1's for each position designated by the loop(rows) and the file data(columns).

Note: the second column is not used, but is put in since this is how the .txt file appears.

I print out each row one by one, and expect there to be three 1's in each row, for all of the rows.

However when I print my output for the 2-D array(code block near bottom), I get unexpected results. For some rows, there will be only two 1's within the row, and for some there will be four 1's.

I am not a very good coder, so any advice would be appreciated, the code is posted below.

```<code>#include "stdafx.h"
using namespace std;

//prints the diagonal of array
void printarray(int arg[][300], int length) {
    for (int n = 0; n<length; ++n)
        cout << arg[n][n] << ' ';
    cout << '\n';
}

//makes 2d array values all 0
void zeros(int a[][300], int size)
{
    cout << "Setting all elements of array to zero...." << endl;
    for (int k = 0; k < (size*size); k++)
    {
        for (int i = 0; i<size; i++)
        {
            for (int j = 0; j<size; j++)
            {
                a[i][j] = 0;
            }
        }
    }
}

int main()
{
    //2D array of 300by300
    int adMatrix [300][300];

    zeros(adMatrix, 300);

    int counter = 0;

    string line;

    int firstVar,secondVar,thirdVar; // variables to hold the bond neighbors while looping

    // Read sample file
    ifstream infile("myTestFile.txt");

    while (counter  < 300 ) {
        getline(infile, line);
        istringstream stream(line);
        stream >> firstVar >> secondVar >> thirdVar;
        adMatrix[counter][firstVar] = 1;
        adMatrix[counter][thirdVar] = 1;
        stream.str("");
        stream.clear();

        getline(infile, line);
        istringstream stream2(line);
        stream2 >> firstVar >> secondVar >> thirdVar;
        adMatrix[counter][firstVar] = 1;
        adMatrix[counter][thirdVar] = 1;
        stream2.str("");
        stream2.clear();

        getline(infile, line);
        istringstream stream3(line);
        stream3 >> firstVar >> secondVar >> thirdVar;
        adMatrix[counter][firstVar] = 1;
        adMatrix[counter][thirdVar] = 1;
        stream3.str("");
        stream3.clear();
        counter++;
    }
      // iterates through entire matrix, prints values, also tallys sum of each row, should equal 3 for each row.
    int var = 0;
    for (int i = 0; i < 300; ++i)
    {
        int sum = 0;
        for (int i = 0; i < 300; ++i)
        {
            cout << adMatrix[var][i];
            sum = adMatrix[var][i] + sum;
        }
        var++;
        cout << endl << "sum is : " << sum << endl;
    }
    return 0;
}
</code>```

Here is the data for .txt file I used:

```<code>43  1   61
2   1   43
2   1   61
1   2   3
1   2   11
3   2   11
2   3   45
4   3   45
2   3   4
3   4   13
5   4   13
3   4   5
4   5   6
6   5   162
4   5   162
15  6   123
5   6   15
5   6   123
59  7   77
8   7   59
8   7   77
7   8   9
7   8   21
9   8   21
8   9   61
10  9   61
8   9   10
9   10  23
11  10  23
9   10  11
2   11  12
10  11  12
2   11  10
13  12  25
11  12  25
11  12  13
12  13  14
4   13  14
4   13  12
15  14  27
13  14  27
13  14  15
14  15  16
6   15  16
6   15  14
29  16  133
15  16  29
15  16  133
75  17  93
18  17  75
18  17  93
17  18  19
17  18  34
19  18  34
18  19  77
20  19  77
18  19  20
19  20  36
21  20  36
19  20  21
8   21  22
20  21  22
8   21  20
23  22  38
21  22  38
21  22  23
22  23  24
10  23  24
10  23  22
25  24  40
23  24  40
23  24  25
24  25  26
12  25  26
12  25  24
27  26  42
25  26  42
25  26  27
26  27  28
14  27  28
14  27  26
27  28  29
29  28  44
27  28  44
16  29  28
28  29  158
16  29  158
91  30  109
31  30  91
31  30  109
30  31  32
30  31  50
32  31  50
31  32  93
33  32  93
31  32  33
32  33  52
34  33  52
32  33  34
18  34  35
33  34  35
18  34  33
36  35  54
34  35  54
34  35  36
35  36  37
20  36  37
20  36  35
38  37  56
36  37  56
36  37  38
37  38  39
22  38  39
22  38  37
40  39  58
38  39  58
38  39  40
39  40  41
24  40  41
24  40  39
40  41  42
42  41  60
40  41  60
26  42  41
41  42  43
26  42  43
42  43  44
1   43  42
1   43  44
28  44  43
28  44  45
43  44  45
3   45  44
44  45  157
3   45  157
107 46  122
47  46  107
47  46  122
46  47  48
46  47  66
48  47  66
47  48  109
49  48  109
47  48  49
48  49  68
50  49  68
48  49  50
31  50  51
49  50  51
31  50  49
52  51  70
50  51  70
50  51  52
51  52  53
33  52  53
33  52  51
54  53  72
52  53  72
52  53  54
53  54  55
35  54  55
35  54  53
56  55  74
54  55  74
54  55  56
55  56  57
37  56  57
37  56  55
56  57  58
58  57  76
56  57  76
39  58  57
57  58  59
39  58  59
58  59  60
7   59  58
7   59  60
41  60  59
41  60  61
59  60  61
1   61  60
9   61  60
1   61  9
120 62  132
63  62  120
63  62  132
62  63  64
62  63  82
64  63  82
63  64  122
65  64  122
63  64  65
64  65  84
66  65  84
64  65  66
47  66  67
47  66  65
65  66  67
68  67  86
66  67  86
66  67  68
67  68  69
49  68  69
49  68  67
70  69  88
68  69  88
68  69  70
69  70  71
51  70  71
51  70  69
72  71  90
70  71  90
70  71  72
71  72  73
53  72  73
53  72  71
72  73  74
74  73  92
72  73  92
73  74  75
55  74  73
55  74  75
74  75  76
17  75  74
17  75  76
57  76  75
57  76  77
75  76  77
7   77  76
19  77  76
7   77  19
130 78  138
79  78  130
79  78  138
78  79  80
78  79  98
80  79  98
79  80  132
81  80  132
79  80  81
80  81  100
80  81  82
82  81  100
63  82  83
63  82  81
81  82  83
84  83  102
82  83  102
82  83  84
83  84  85
65  84  85
65  84  83
86  85  104
84  85  104
84  85  86
85  86  87
67  86  87
67  86  85
88  87  106
86  87  106
86  87  88
87  88  89
69  88  89
69  88  87
90  89  108
88  89  90
88  89  108
71  90  89
89  90  91
71  90  91
90  91  92
30  91  90
30  91  92
73  92  91
73  92  93
91  92  93
17  93  92
32  93  92
17  93  32
95  94  136
136 94  160
95  94  160
94  95  96
94  95  111
96  95  111
95  96  138
97  96  138
95  96  97
96  97  113
96  97  98
98  97  113
79  98  99
79  98  97
97  98  99
100 99  115
98  99  115
98  99  100
99  100 101
81  100 101
81  100 99
102 101 117
100 101 117
100 101 102
101 102 103
83  102 103
83  102 101
104 103 119
102 103 119
102 103 104
103 104 105
85  104 105
85  104 103
106 105 121
104 105 106
104 105 121
105 106 107
87  106 105
87  106 107
106 107 108
46  107 106
46  107 108
89  108 107
89  108 109
107 108 109
30  109 108
48  109 108
30  109 48
111 110 123
123 110 161
111 110 161
95  111 112
95  111 110
110 111 112
113 112 125
111 112 125
111 112 113
112 113 114
97  113 114
97  113 112
115 114 127
113 114 127
113 114 115
114 115 116
99  115 116
99  115 114
117 116 129
115 116 129
115 116 117
116 117 118
101 117 118
101 117 116
119 118 131
117 118 119
117 118 131
103 119 118
118 119 120
103 119 120
119 120 121
62  120 119
62  120 121
105 121 120
105 121 122
120 121 122
46  122 121
64  122 121
46  122 64
6   123 124
110 123 124
6   123 110
125 124 133
123 124 133
123 124 125
124 125 126
112 125 126
112 125 124
127 126 135
125 126 135
125 126 127
126 127 128
114 127 128
114 127 126
127 128 129
129 128 137
127 128 137
128 129 130
116 129 128
116 129 130
129 130 131
78  130 129
78  130 131
118 131 130
118 131 132
130 131 132
62  132 131
80  132 131
62  132 80
16  133 134
124 133 134
16  133 124
133 134 135
135 134 159
133 134 159
126 135 134
134 135 136
126 135 136
135 136 137
94  136 135
94  136 137
128 137 136
128 137 138
136 137 138
78  138 137
96  138 137
78  138 96
141 139 156
141 139 220
156 139 220
141 140 157
141 140 158
157 140 158
139 141 142
140 141 142
139 141 140
141 142 144
141 142 283
144 142 283
144 143 158
144 143 159
158 143 159
142 144 145
142 144 143
143 144 145
144 145 147
147 145 284
144 145 284
147 146 159
147 146 160
159 146 160
145 147 148
146 147 148
145 147 146
147 148 150
147 148 215
150 148 215
150 149 160
150 149 161
160 149 161
148 150 151
149 150 151
148 150 149
150 151 153
153 151 164
150 151 164
153 152 161
153 152 162
161 152 162
151 153 154
151 153 152
152 153 154
153 154 156
153 154 163
156 154 163
156 155 157
156 155 162
157 155 162
139 156 154
154 156 155
139 156 155
140 157 155
45  157 155
45  157 140
140 158 143
29  158 143
29  158 140
143 159 146
134 159 143
134 159 146
146 160 149
94  160 149
94  160 146
149 161 152
110 161 149
110 161 152
152 162 155
5   162 155
5   162 152
165 163 184
154 163 165
154 163 184
166 164 185
151 164 166
151 164 185
163 165 181
163 165 187
181 165 187
164 166 182
164 166 188
182 166 188
169 167 183
169 167 189
183 167 189
170 168 186
170 168 190
186 168 190
167 169 191
167 169 193
191 169 193
168 170 192
168 170 194
192 170 194
173 171 195
173 171 196
195 171 196
174 172 197
174 172 198
197 172 198
171 173 199
171 173 201
199 173 201
172 174 200
172 174 203
200 174 203
177 175 202
177 175 205
202 175 205
178 176 204
178 176 206
204 176 206
175 177 207
175 177 211
207 177 211
176 178 208
176 178 212
208 178 212
180 179 209
180 179 213
209 179 213
179 180 210
179 180 214
210 180 214
165 181 183
183 181 220
165 181 220
166 182 186
186 182 215
166 182 215
167 183 181
181 183 216
167 183 216
163 184 185
185 184 218
163 184 218
164 185 184
184 185 219
164 185 219
168 186 182
182 186 217
168 186 217
165 187 189
189 187 221
165 187 221
166 188 190
190 188 222
166 188 222
167 189 187
187 189 225
167 189 225
168 190 188
188 190 226
168 190 226
169 191 195
169 191 223
195 191 223
170 192 197
197 192 224
170 192 224
169 193 196
196 193 227
169 193 227
170 194 198
198 194 228
170 194 228
171 195 191
191 195 231
171 195 231
171 196 193
193 196 229
171 196 229
172 197 192
192 197 232
172 197 232
172 198 194
194 198 230
172 198 230
173 199 202
202 199 233
173 199 233
174 200 204
204 200 234
174 200 234
173 201 205
205 201 235
173 201 235
175 202 199
199 202 237
175 202 237
174 203 206
206 203 236
174 203 236
176 204 200
200 204 238
176 204 238
175 205 201
201 205 243
175 205 243
176 206 203
203 206 244
176 206 244
177 207 209
177 207 239
209 207 239
178 208 210
210 208 240
178 208 240
179 209 207
207 209 241
179 209 241
180 210 208
208 210 242
180 210 242
177 211 213
177 211 245
213 211 245
178 212 214
214 212 246
178 212 246
179 213 211
211 213 247
179 213 247
180 214 212
212 214 248
180 214 248
182 215 250
148 215 182
148 215 250
183 216 223
183 216 251
223 216 251
186 217 224
224 217 254
186 217 254
184 218 221
184 218 252
221 218 252
185 219 222
222 219 253
185 219 253
181 220 249
139 220 181
139 220 249
187 221 218
218 221 255
187 221 255
188 222 219
219 222 256
188 222 256
191 223 216
216 223 259
191 223 259
192 224 217
217 224 260
192 224 260
189 225 227
227 225 257
189 225 257
190 226 228
228 226 258
190 226 258
193 227 225
225 227 261
193 227 261
194 228 226
226 228 262
194 228 262
196 229 233
196 229 264
233 229 264
198 230 234
234 230 266
198 230 266
195 231 235
195 231 263
235 231 263
197 232 236
236 232 265
197 232 265
199 233 229
229 233 267
199 233 267
200 234 230
230 234 268
200 234 268
201 235 231
231 235 269
201 235 269
203 236 232
232 236 271
203 236 271
202 237 239
239 237 270
202 237 270
204 238 240
204 238 272
240 238 272
207 239 237
237 239 275
207 239 275
208 240 238
238 240 276
208 240 276
209 241 242
209 241 277
242 241 277
210 242 241
241 242 278
210 242 278
205 243 245
205 243 273
245 243 273
206 244 246
246 244 274
206 244 274
211 245 243
243 245 279
211 245 279
212 246 244
244 246 280
212 246 280
213 247 248
213 247 281
248 247 281
214 248 247
247 248 282
214 248 282
220 249 251
251 249 285
220 249 285
215 250 254
215 250 286
254 250 286
216 251 249
249 251 287
216 251 287
218 252 253
218 252 283
253 252 283
219 253 252
252 253 284
219 253 284
217 254 250
250 254 288
217 254 288
221 255 257
221 255 285
257 255 285
222 256 258
222 256 286
258 256 286
225 257 255
255 257 287
225 257 287
226 258 256
256 258 288
226 258 288
223 259 263
223 259 289
263 259 289
224 260 265
265 260 290
224 260 290
227 261 264
227 261 289
264 261 289
228 262 266
228 262 290
266 262 290
231 263 259
259 263 291
231 263 291
229 264 261
261 264 291
229 264 291
232 265 260
260 265 292
232 265 292
230 266 262
262 266 292
230 266 292
233 267 270
270 267 293
233 267 293
234 268 272
234 268 294
272 268 294
235 269 273
235 269 293
273 269 293
237 270 267
267 270 295
237 270 295
236 271 274
236 271 294
274 271 294
238 272 268
268 272 296
238 272 296
243 273 269
269 273 295
243 273 295
244 274 271
271 274 296
244 274 296
239 275 277
277 275 297
239 275 297
240 276 278
278 276 298
240 276 298
241 277 275
275 277 299
241 277 299
242 278 276
276 278 300
242 278 300
245 279 281
245 279 297
281 279 297
246 280 282
282 280 298
246 280 298
247 281 279
279 281 299
247 281 299
248 282 280
280 282 300
248 282 300
252 283 285
142 283 252
142 283 285
253 284 286
145 284 253
145 284 286
255 285 283
249 285 283
249 285 255
256 286 284
250 286 284
250 286 256
251 287 257
257 287 289
251 287 289
258 288 290
254 288 290
254 288 258
259 289 287
261 289 287
259 289 261
262 290 288
260 290 288
260 290 262
263 291 264
263 291 293
264 291 293
265 292 266
266 292 294
265 292 294
267 293 291
269 293 291
267 293 269
268 294 292
271 294 292
268 294 271
270 295 273
273 295 297
270 295 297
274 296 298
272 296 298
272 296 274
279 297 295
275 297 295
275 297 279
276 298 296
280 298 296
276 298 280
281 299 300
277 299 300
277 299 281
278 300 299
282 300 299
278 300 282
</code>```

Here is a picture of the weird output I have been getting. (The output of sums of 2 and 4, when I want sum of 3.) (Also Note there is more than one instance of these sums of 2 and 4 appearing.)

答:
The format of the file looks a bit weird and surely redundant (even without considering the symmetry of the resulting matrix).
The choice of a 2D array of ints to represent a symmetric sparse (1% of non-zero elements, all of value 1) matrix may be a waste of space too, but the question doesn't specify the underlying problem, so I will not speculate any further.

It seems that in the input file rows and column are indexed starting by 1, while in C++ array indeces start by 0, so when a line like

```<code>281 299 300
</code>```

is read by OP's code:

```<code>stream >> firstVar >> secondVar >> thirdVar;
adMatrix[counter][firstVar] = 1;
adMatrix[counter][thirdVar] = 1;
</code>```

The value 300 is off by one and being 2D arrays contiguous in memory, instead of the last element of the row (the second value represent the row number, apparently) the first element of next row is set to 1.

Given a well formatted input file, like the one presented, is also easier to read the values directly from the file stream using operator>>, without using a string stream.

The same snippet can be rewritten and "simplified" like this:

```<code>#include <iostream>
#include <fstream>

template <size_t Dim>
bool is_symmetric(int (&arr)[Dim][Dim]);

template <size_t Dim>
bool are_there_exactly_3_nonzeroes_each_row(int (&arr)[Dim][Dim]);

template <size_t Dim>
int nonzeroes_on_diagonal(int (&arr)[Dim][Dim]);

const size_t size = 300;

int main()
{
    // Declares a 2D array of 300 by 300 int and initializes it to zero:
    int adMatrix [size][size] = {};

    std::ifstream infile("myTestFile.txt");
    if ( !infile )
    {
        std::cerr << "Unable to open input file.\n";
        return EXIT_FAILURE;
    }

    // The value in the second column is the line number.
    // All the the values in the file are indeces in the range 1 - 300
    int first_col, row, second_col;
    // This will read all the file, if it is well formatted.
    while ( infile >> first_col >> row >> second_col )
    {
        if (     first_col < 1   or  first_col > size
             or  row < 1         or  row > size
             or  second_col < 1  or  second_col > size )
        {
            std::cerr << "Wrong file format.\n The line with data: "
                      << first_col << ' ' << row << ' ' << second_col
                      << " have out of range indeces.\n";
                      return EXIT_FAILURE;
        }
        adMatrix[row - 1][first_col - 1] = 1;
        adMatrix[row - 1][second_col - 1] = 1;
    }

    // Print values or ...
    if ( is_symmetric(adMatrix) == false )
    {
        std::cerr << "The matrix isn't symmetric.\n";
    }

    if ( are_there_exactly_3_nonzeroes_each_row(adMatrix) == false )
    {
        std::cerr << "There aren't exactly three non zero elements each row.\n";
    }

    std::cout << "Number of non zero elements in the main diagonal: "
              << nonzeroes_on_diagonal(adMatrix) << '\n';
}

template <size_t Dim>
bool is_symmetric(int (&arr)[Dim][Dim])
{
    for ( size_t i = 0; i < Dim; ++i )
    {
        for ( size_t j = i + 1; j < Dim; ++j )
        {
            if ( arr[i][j] != arr[j][i] )
                return false;
        }
    }
    return true;
}

template <size_t Dim>
bool are_there_exactly_3_nonzeroes_each_row(int (&arr)[Dim][Dim])
{
    for ( size_t i = 0; i < Dim; ++i )
    {
        int count = 0;
        for ( size_t j = 0; j < Dim; ++j )
        {
            if ( arr[i][j] != 0 )
                ++count;
        }
        if ( count != 3 )
            return false;
    }
    return true;
}

template <size_t Dim>
int nonzeroes_on_diagonal(int (&arr)[Dim][Dim])
{
    int count = 0;
    for ( size_t i = 0; i < Dim; ++i )
    {
        if ( arr[i][i] != 0 )
        {
            ++count;
        }
    }
    return count;
}
</code>```

This will fix the issue, but for a more general solution and to really improve your language knowledge it would be far more useful to start learning about classes, the C++ Standard Library, its containers and generic functions.

Body:
I have a .txt file with tab separated data(several rows):

    42  2   62
    2   2   42
    2   2   62

I tried to use istringstream to read the data from the file, and then use each column's data for each respective row as locations for adding 1's into a 2-D array.

This was to loop until the 2-D array was filled with 1's for each position designated by the loop(rows) and the file data(columns).

Note: the second column is not used, but is put in since this is how the .txt file appears.

I print out each row one by one, and expect there to be three 1's in each row, for all of the rows.

However when I print my output for the 2-D array(code block near bottom), I get unexpected results. For some rows, there will be only two 1's within the row, and for some there will be four 1's.

I am not a very good coder, so any advice would be appreciated, the code is posted below.

#include "stdafx.h"
using namespace std;

//prints the diagonal of array
void printarray(int arg[][300], int length) {
    for (int n = 0; n<length; ++n)
        cout << arg[n][n] << ' ';
    cout << '\n';
}

//makes 2d array values all 0
void zeros(int a[][300], int size)
{
    cout << "Setting all elements of array to zero...." << endl;
    for (int k = 0; k < (size*size); k++)
    {
        for (int i = 0; i<size; i++)
        {
            for (int j = 0; j<size; j++)
            {
                a[i][j] = 0;
            }
        }
    }
}

int main()
{
    //2D array of 300by300
    int adMatrix [300][300];

    zeros(adMatrix, 300);

    int counter = 0;

    string line;

    int firstVar,secondVar,thirdVar; // variables to hold the bond neighbors while looping

    // Read sample file
    ifstream infile("myTestFile.txt");

    while (counter  < 300 ) {
        getline(infile, line);
        istringstream stream(line);
        stream >> firstVar >> secondVar >> thirdVar;
        adMatrix[counter][firstVar] = 1;
        adMatrix[counter][thirdVar] = 1;
        stream.str("");
        stream.clear();

        getline(infile, line);
        istringstream stream2(line);
        stream2 >> firstVar >> secondVar >> thirdVar;
        adMatrix[counter][firstVar] = 1;
        adMatrix[counter][thirdVar] = 1;
        stream2.str("");
        stream2.clear();

        getline(infile, line);
        istringstream stream3(line);
        stream3 >> firstVar >> secondVar >> thirdVar;
        adMatrix[counter][firstVar] = 1;
        adMatrix[counter][thirdVar] = 1;
        stream3.str("");
        stream3.clear();
        counter++;
    }
      // iterates through entire matrix, prints values, also tallys sum of each row, should equal 3 for each row.
    int var = 0;
    for (int i = 0; i < 300; ++i)
    {
        int sum = 0;
        for (int i = 0; i < 300; ++i)
        {
            cout << adMatrix[var][i];
            sum = adMatrix[var][i] + sum;
        }
        var++;
        cout << endl << "sum is : " << sum << endl;
    }
    return 0;
}

Here is the data for .txt file I used:

43  1   61
2   1   43
2   1   61
1   2   3
1   2   11
3   2   11
2   3   45
4   3   45
2   3   4
3   4   13
5   4   13
3   4   5
4   5   6
6   5   162
4   5   162
15  6   123
5   6   15
5   6   123
59  7   77
8   7   59
8   7   77
7   8   9
7   8   21
9   8   21
8   9   61
10  9   61
8   9   10
9   10  23
11  10  23
9   10  11
2   11  12
10  11  12
2   11  10
13  12  25
11  12  25
11  12  13
12  13  14
4   13  14
4   13  12
15  14  27
13  14  27
13  14  15
14  15  16
6   15  16
6   15  14
29  16  133
15  16  29
15  16  133
75  17  93
18  17  75
18  17  93
17  18  19
17  18  34
19  18  34
18  19  77
20  19  77
18  19  20
19  20  36
21  20  36
19  20  21
8   21  22
20  21  22
8   21  20
23  22  38
21  22  38
21  22  23
22  23  24
10  23  24
10  23  22
25  24  40
23  24  40
23  24  25
24  25  26
12  25  26
12  25  24
27  26  42
25  26  42
25  26  27
26  27  28
14  27  28
14  27  26
27  28  29
29  28  44
27  28  44
16  29  28
28  29  158
16  29  158
91  30  109
31  30  91
31  30  109
30  31  32
30  31  50
32  31  50
31  32  93
33  32  93
31  32  33
32  33  52
34  33  52
32  33  34
18  34  35
33  34  35
18  34  33
36  35  54
34  35  54
34  35  36
35  36  37
20  36  37
20  36  35
38  37  56
36  37  56
36  37  38
37  38  39
22  38  39
22  38  37
40  39  58
38  39  58
38  39  40
39  40  41
24  40  41
24  40  39
40  41  42
42  41  60
40  41  60
26  42  41
41  42  43
26  42  43
42  43  44
1   43  42
1   43  44
28  44  43
28  44  45
43  44  45
3   45  44
44  45  157
3   45  157
107 46  122
47  46  107
47  46  122
46  47  48
46  47  66
48  47  66
47  48  109
49  48  109
47  48  49
48  49  68
50  49  68
48  49  50
31  50  51
49  50  51
31  50  49
52  51  70
50  51  70
50  51  52
51  52  53
33  52  53
33  52  51
54  53  72
52  53  72
52  53  54
53  54  55
35  54  55
35  54  53
56  55  74
54  55  74
54  55  56
55  56  57
37  56  57
37  56  55
56  57  58
58  57  76
56  57  76
39  58  57
57  58  59
39  58  59
58  59  60
7   59  58
7   59  60
41  60  59
41  60  61
59  60  61
1   61  60
9   61  60
1   61  9
120 62  132
63  62  120
63  62  132
62  63  64
62  63  82
64  63  82
63  64  122
65  64  122
63  64  65
64  65  84
66  65  84
64  65  66
47  66  67
47  66  65
65  66  67
68  67  86
66  67  86
66  67  68
67  68  69
49  68  69
49  68  67
70  69  88
68  69  88
68  69  70
69  70  71
51  70  71
51  70  69
72  71  90
70  71  90
70  71  72
71  72  73
53  72  73
53  72  71
72  73  74
74  73  92
72  73  92
73  74  75
55  74  73
55  74  75
74  75  76
17  75  74
17  75  76
57  76  75
57  76  77
75  76  77
7   77  76
19  77  76
7   77  19
130 78  138
79  78  130
79  78  138
78  79  80
78  79  98
80  79  98
79  80  132
81  80  132
79  80  81
80  81  100
80  81  82
82  81  100
63  82  83
63  82  81
81  82  83
84  83  102
82  83  102
82  83  84
83  84  85
65  84  85
65  84  83
86  85  104
84  85  104
84  85  86
85  86  87
67  86  87
67  86  85
88  87  106
86  87  106
86  87  88
87  88  89
69  88  89
69  88  87
90  89  108
88  89  90
88  89  108
71  90  89
89  90  91
71  90  91
90  91  92
30  91  90
30  91  92
73  92  91
73  92  93
91  92  93
17  93  92
32  93  92
17  93  32
95  94  136
136 94  160
95  94  160
94  95  96
94  95  111
96  95  111
95  96  138
97  96  138
95  96  97
96  97  113
96  97  98
98  97  113
79  98  99
79  98  97
97  98  99
100 99  115
98  99  115
98  99  100
99  100 101
81  100 101
81  100 99
102 101 117
100 101 117
100 101 102
101 102 103
83  102 103
83  102 101
104 103 119
102 103 119
102 103 104
103 104 105
85  104 105
85  104 103
106 105 121
104 105 106
104 105 121
105 106 107
87  106 105
87  106 107
106 107 108
46  107 106
46  107 108
89  108 107
89  108 109
107 108 109
30  109 108
48  109 108
30  109 48
111 110 123
123 110 161
111 110 161
95  111 112
95  111 110
110 111 112
113 112 125
111 112 125
111 112 113
112 113 114
97  113 114
97  113 112
115 114 127
113 114 127
113 114 115
114 115 116
99  115 116
99  115 114
117 116 129
115 116 129
115 116 117
116 117 118
101 117 118
101 117 116
119 118 131
117 118 119
117 118 131
103 119 118
118 119 120
103 119 120
119 120 121
62  120 119
62  120 121
105 121 120
105 121 122
120 121 122
46  122 121
64  122 121
46  122 64
6   123 124
110 123 124
6   123 110
125 124 133
123 124 133
123 124 125
124 125 126
112 125 126
112 125 124
127 126 135
125 126 135
125 126 127
126 127 128
114 127 128
114 127 126
127 128 129
129 128 137
127 128 137
128 129 130
116 129 128
116 129 130
129 130 131
78  130 129
78  130 131
118 131 130
118 131 132
130 131 132
62  132 131
80  132 131
62  132 80
16  133 134
124 133 134
16  133 124
133 134 135
135 134 159
133 134 159
126 135 134
134 135 136
126 135 136
135 136 137
94  136 135
94  136 137
128 137 136
128 137 138
136 137 138
78  138 137
96  138 137
78  138 96
141 139 156
141 139 220
156 139 220
141 140 157
141 140 158
157 140 158
139 141 142
140 141 142
139 141 140
141 142 144
141 142 283
144 142 283
144 143 158
144 143 159
158 143 159
142 144 145
142 144 143
143 144 145
144 145 147
147 145 284
144 145 284
147 146 159
147 146 160
159 146 160
145 147 148
146 147 148
145 147 146
147 148 150
147 148 215
150 148 215
150 149 160
150 149 161
160 149 161
148 150 151
149 150 151
148 150 149
150 151 153
153 151 164
150 151 164
153 152 161
153 152 162
161 152 162
151 153 154
151 153 152
152 153 154
153 154 156
153 154 163
156 154 163
156 155 157
156 155 162
157 155 162
139 156 154
154 156 155
139 156 155
140 157 155
45  157 155
45  157 140
140 158 143
29  158 143
29  158 140
143 159 146
134 159 143
134 159 146
146 160 149
94  160 149
94  160 146
149 161 152
110 161 149
110 161 152
152 162 155
5   162 155
5   162 152
165 163 184
154 163 165
154 163 184
166 164 185
151 164 166
151 164 185
163 165 181
163 165 187
181 165 187
164 166 182
164 166 188
182 166 188
169 167 183
169 167 189
183 167 189
170 168 186
170 168 190
186 168 190
167 169 191
167 169 193
191 169 193
168 170 192
168 170 194
192 170 194
173 171 195
173 171 196
195 171 196
174 172 197
174 172 198
197 172 198
171 173 199
171 173 201
199 173 201
172 174 200
172 174 203
200 174 203
177 175 202
177 175 205
202 175 205
178 176 204
178 176 206
204 176 206
175 177 207
175 177 211
207 177 211
176 178 208
176 178 212
208 178 212
180 179 209
180 179 213
209 179 213
179 180 210
179 180 214
210 180 214
165 181 183
183 181 220
165 181 220
166 182 186
186 182 215
166 182 215
167 183 181
181 183 216
167 183 216
163 184 185
185 184 218
163 184 218
164 185 184
184 185 219
164 185 219
168 186 182
182 186 217
168 186 217
165 187 189
189 187 221
165 187 221
166 188 190
190 188 222
166 188 222
167 189 187
187 189 225
167 189 225
168 190 188
188 190 226
168 190 226
169 191 195
169 191 223
195 191 223
170 192 197
197 192 224
170 192 224
169 193 196
196 193 227
169 193 227
170 194 198
198 194 228
170 194 228
171 195 191
191 195 231
171 195 231
171 196 193
193 196 229
171 196 229
172 197 192
192 197 232
172 197 232
172 198 194
194 198 230
172 198 230
173 199 202
202 199 233
173 199 233
174 200 204
204 200 234
174 200 234
173 201 205
205 201 235
173 201 235
175 202 199
199 202 237
175 202 237
174 203 206
206 203 236
174 203 236
176 204 200
200 204 238
176 204 238
175 205 201
201 205 243
175 205 243
176 206 203
203 206 244
176 206 244
177 207 209
177 207 239
209 207 239
178 208 210
210 208 240
178 208 240
179 209 207
207 209 241
179 209 241
180 210 208
208 210 242
180 210 242
177 211 213
177 211 245
213 211 245
178 212 214
214 212 246
178 212 246
179 213 211
211 213 247
179 213 247
180 214 212
212 214 248
180 214 248
182 215 250
148 215 182
148 215 250
183 216 223
183 216 251
223 216 251
186 217 224
224 217 254
186 217 254
184 218 221
184 218 252
221 218 252
185 219 222
222 219 253
185 219 253
181 220 249
139 220 181
139 220 249
187 221 218
218 221 255
187 221 255
188 222 219
219 222 256
188 222 256
191 223 216
216 223 259
191 223 259
192 224 217
217 224 260
192 224 260
189 225 227
227 225 257
189 225 257
190 226 228
228 226 258
190 226 258
193 227 225
225 227 261
193 227 261
194 228 226
226 228 262
194 228 262
196 229 233
196 229 264
233 229 264
198 230 234
234 230 266
198 230 266
195 231 235
195 231 263
235 231 263
197 232 236
236 232 265
197 232 265
199 233 229
229 233 267
199 233 267
200 234 230
230 234 268
200 234 268
201 235 231
231 235 269
201 235 269
203 236 232
232 236 271
203 236 271
202 237 239
239 237 270
202 237 270
204 238 240
204 238 272
240 238 272
207 239 237
237 239 275
207 239 275
208 240 238
238 240 276
208 240 276
209 241 242
209 241 277
242 241 277
210 242 241
241 242 278
210 242 278
205 243 245
205 243 273
245 243 273
206 244 246
246 244 274
206 244 274
211 245 243
243 245 279
211 245 279
212 246 244
244 246 280
212 246 280
213 247 248
213 247 281
248 247 281
214 248 247
247 248 282
214 248 282
220 249 251
251 249 285
220 249 285
215 250 254
215 250 286
254 250 286
216 251 249
249 251 287
216 251 287
218 252 253
218 252 283
253 252 283
219 253 252
252 253 284
219 253 284
217 254 250
250 254 288
217 254 288
221 255 257
221 255 285
257 255 285
222 256 258
222 256 286
258 256 286
225 257 255
255 257 287
225 257 287
226 258 256
256 258 288
226 258 288
223 259 263
223 259 289
263 259 289
224 260 265
265 260 290
224 260 290
227 261 264
227 261 289
264 261 289
228 262 266
228 262 290
266 262 290
231 263 259
259 263 291
231 263 291
229 264 261
261 264 291
229 264 291
232 265 260
260 265 292
232 265 292
230 266 262
262 266 292
230 266 292
233 267 270
270 267 293
233 267 293
234 268 272
234 268 294
272 268 294
235 269 273
235 269 293
273 269 293
237 270 267
267 270 295
237 270 295
236 271 274
236 271 294
274 271 294
238 272 268
268 272 296
238 272 296
243 273 269
269 273 295
243 273 295
244 274 271
271 274 296
244 274 296
239 275 277
277 275 297
239 275 297
240 276 278
278 276 298
240 276 298
241 277 275
275 277 299
241 277 299
242 278 276
276 278 300
242 278 300
245 279 281
245 279 297
281 279 297
246 280 282
282 280 298
246 280 298
247 281 279
279 281 299
247 281 299
248 282 280
280 282 300
248 282 300
252 283 285
142 283 252
142 283 285
253 284 286
145 284 253
145 284 286
255 285 283
249 285 283
249 285 255
256 286 284
250 286 284
250 286 256
251 287 257
257 287 289
251 287 289
258 288 290
254 288 290
254 288 258
259 289 287
261 289 287
259 289 261
262 290 288
260 290 288
260 290 262
263 291 264
263 291 293
264 291 293
265 292 266
266 292 294
265 292 294
267 293 291
269 293 291
267 293 269
268 294 292
271 294 292
268 294 271
270 295 273
273 295 297
270 295 297
274 296 298
272 296 298
272 296 274
279 297 295
275 297 295
275 297 279
276 298 296
280 298 296
276 298 280
281 299 300
277 299 300
277 299 281
278 300 299
282 300 299
278 300 282

Here is a picture of the weird output I have been getting. (The output of sums of 2 and 4, when I want sum of 3.) (Also Note there is more than one instance of these sums of 2 and 4 appearing.)

Body:
The format of the file looks a bit weird and surely redundant (even without considering the symmetry of the resulting matrix).
The choice of a 2D array of ints to represent a symmetric sparse (1% of non-zero elements, all of value 1) matrix may be a waste of space too, but the question doesn't specify the underlying problem, so I will not speculate any further.

It seems that in the input file rows and column are indexed starting by 1, while in C++ array indeces start by 0, so when a line like

281 299 300

is read by OP's code:

stream >> firstVar >> secondVar >> thirdVar;
adMatrix[counter][firstVar] = 1;
adMatrix[counter][thirdVar] = 1;

The value 300 is off by one and being 2D arrays contiguous in memory, instead of the last element of the row (the second value represent the row number, apparently) the first element of next row is set to 1.

Given a well formatted input file, like the one presented, is also easier to read the values directly from the file stream using operator>>, without using a string stream.

The same snippet can be rewritten and "simplified" like this:

#include <iostream>
#include <fstream>

template <size_t Dim>
bool is_symmetric(int (&arr)[Dim][Dim]);

template <size_t Dim>
bool are_there_exactly_3_nonzeroes_each_row(int (&arr)[Dim][Dim]);

template <size_t Dim>
int nonzeroes_on_diagonal(int (&arr)[Dim][Dim]);

const size_t size = 300;

int main()
{
    // Declares a 2D array of 300 by 300 int and initializes it to zero:
    int adMatrix [size][size] = {};

    std::ifstream infile("myTestFile.txt");
    if ( !infile )
    {
        std::cerr << "Unable to open input file.\n";
        return EXIT_FAILURE;
    }

    // The value in the second column is the line number.
    // All the the values in the file are indeces in the range 1 - 300
    int first_col, row, second_col;
    // This will read all the file, if it is well formatted.
    while ( infile >> first_col >> row >> second_col )
    {
        if (     first_col < 1   or  first_col > size
             or  row < 1         or  row > size
             or  second_col < 1  or  second_col > size )
        {
            std::cerr << "Wrong file format.\n The line with data: "
                      << first_col << ' ' << row << ' ' << second_col
                      << " have out of range indeces.\n";
                      return EXIT_FAILURE;
        }
        adMatrix[row - 1][first_col - 1] = 1;
        adMatrix[row - 1][second_col - 1] = 1;
    }

    // Print values or ...
    if ( is_symmetric(adMatrix) == false )
    {
        std::cerr << "The matrix isn't symmetric.\n";
    }

    if ( are_there_exactly_3_nonzeroes_each_row(adMatrix) == false )
    {
        std::cerr << "There aren't exactly three non zero elements each row.\n";
    }

    std::cout << "Number of non zero elements in the main diagonal: "
              << nonzeroes_on_diagonal(adMatrix) << '\n';
}

template <size_t Dim>
bool is_symmetric(int (&arr)[Dim][Dim])
{
    for ( size_t i = 0; i < Dim; ++i )
    {
        for ( size_t j = i + 1; j < Dim; ++j )
        {
            if ( arr[i][j] != arr[j][i] )
                return false;
        }
    }
    return true;
}

template <size_t Dim>
bool are_there_exactly_3_nonzeroes_each_row(int (&arr)[Dim][Dim])
{
    for ( size_t i = 0; i < Dim; ++i )
    {
        int count = 0;
        for ( size_t j = 0; j < Dim; ++j )
        {
            if ( arr[i][j] != 0 )
                ++count;
        }
        if ( count != 3 )
            return false;
    }
    return true;
}

template <size_t Dim>
int nonzeroes_on_diagonal(int (&arr)[Dim][Dim])
{
    int count = 0;
    for ( size_t i = 0; i < Dim; ++i )
    {
        if ( arr[i][i] != 0 )
        {
            ++count;
        }
    }
    return count;
}

This will fix the issue, but for a more general solution and to really improve your language knowledge it would be far more useful to start learning about classes, the C++ Standard Library, its containers and generic functions.


问:
is using eval() to run the contents of an html attribute safe?
So i'm simply trying to mimic some angular syntax and create some functionality of my own where I can add an html attribute: m-click="navigate('/signup')" and then evaluate the javascript inside.

var $scope = {};

$scope.navigate = function(url) {
  console.log('go to: "' + url + '"');
};

$('[m-click]').on('click', function(item) {
  eval('$scope.' + $(this).attr('m-click'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button m-click="navigate('/signup');">
  Sign Up
</button></code>```

What I'm wondering is:

is this how this is done with Angular and ng-click?

Is there another way to do this?

Is this safe, or is it prone to attacks?

答:
To write m-click as a custom directive:

```<code>app.directive("mClick", function() {
    return {
        link: function postLink(scope, elem, attrs) {
            elem.on("click", function(event) {
                scope.$eval(attrs.mClick);
                scope.$apply();
            });
        }
     };
});
</code>```

If you like the functionality and convenience of using Angular's syntax, read AngularJS Developer Guide - Creating Custom Directives. Most anything you want to do can be done in a safe way without using the evil eval.

Body:
So i'm simply trying to mimic some angular syntax and create some functionality of my own where I can add an html attribute: m-click="navigate('/signup')" and then evaluate the javascript inside.

var $scope = {};

$scope.navigate = function(url) {
  console.log('go to: "' + url + '"');
};

$('[m-click]').on('click', function(item) {
  eval('$scope.' + $(this).attr('m-click'));
});

<button m-click="navigate('/signup');">
  Sign Up
</button>

What I'm wondering is:

is this how this is done with Angular and ng-click?

Is there another way to do this?

Is this safe, or is it prone to attacks?

Body:
To write m-click as a custom directive:

app.directive("mClick", function() {
    return {
        link: function postLink(scope, elem, attrs) {
            elem.on("click", function(event) {
                scope.$eval(attrs.mClick);
                scope.$apply();
            });
        }
     };
});

If you like the functionality and convenience of using Angular's syntax, read AngularJS Developer Guide - Creating Custom Directives. Most anything you want to do can be done in a safe way without using the evil eval.


问:
How to specify a specific column value to regress in Python?
I'm conducting some linear regressions using Python.  I have a fairly large data file I'm working with, and one of the columns I'm looking at is titled "male" which points to a the gender of a subject.  Column values can be 1 = male, 0 = female.  "rgroupx" is the treatment variable (0 = control, 6 = high status treatment) and "log_mm" is the outcome variable.

One of the questions I need to answer is: How much does the high status treatment affect the number of traffic violations post intervention for male drivers? Is there a significant treatment effect for female drivers?

I have below my current Python statement.  My problem is for both questions, how would I specify a column value to include in the regression?  If the question is asking for male drivers, how do I tell Python to include only 1s?  Thanks in advance!

```<code>model3 = smf.ols('log_mm ~ rgroupx + male', data=Traffic).fit()
</code>```

答:
If the structure of your data is in a dataframe, than a combination of indexing and dropping data while assigning it to a new variable 'male' would work.

Example:

```<code>males_df = data.drop(data[data.gender != 1].index)
</code>```

variable for regression:

```<code>males = males_df.gender
</code>```

Body:
I'm conducting some linear regressions using Python.  I have a fairly large data file I'm working with, and one of the columns I'm looking at is titled "male" which points to a the gender of a subject.  Column values can be 1 = male, 0 = female.  "rgroupx" is the treatment variable (0 = control, 6 = high status treatment) and "log_mm" is the outcome variable.

One of the questions I need to answer is: How much does the high status treatment affect the number of traffic violations post intervention for male drivers? Is there a significant treatment effect for female drivers?

I have below my current Python statement.  My problem is for both questions, how would I specify a column value to include in the regression?  If the question is asking for male drivers, how do I tell Python to include only 1s?  Thanks in advance!

model3 = smf.ols('log_mm ~ rgroupx + male', data=Traffic).fit()

Body:
If the structure of your data is in a dataframe, than a combination of indexing and dropping data while assigning it to a new variable 'male' would work.

Example:

males_df = data.drop(data[data.gender != 1].index)

variable for regression:

males = males_df.gender


问:
Confirmation dialog with HTML5 button element
I have a button element like so:

```<code><button name="command" type="submit" form="frmLandUnits" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">
      <span class="glyphicon glyphicon-trash" aria-hidden="true">
    </span></button>
</code>```

It's part of a data entry grid in a table which is inside a form. On each row are other buttons like Update, and there's a new row with an Insert button. The problem is that when clicking OK the form is not submitted. A google search on this turned up nothing that I could find.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form name="frmLandUnits" method="POST" action="https://httpbin.org/post">

<button name="command" type="submit" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">

    </button>

</form>```

The behavior is different than for onclick with an input. That is why in my opinion this is not a duplicate.

答:
Just remove the form attribute from your button.

```<code><button name="command" type="submit" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">
      <span class="glyphicon glyphicon-trash" aria-hidden="true">
    </span></button>
</code>```

Checkout this demo

Body:
I have a button element like so:

<button name="command" type="submit" form="frmLandUnits" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">

    </button>

It's part of a data entry grid in a table which is inside a form. On each row are other buttons like Update, and there's a new row with an Insert button. The problem is that when clicking OK the form is not submitted. A google search on this turned up nothing that I could find.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form name="frmLandUnits" method="POST" action="https://httpbin.org/post">

<button name="command" type="submit" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">

    </button>

</form>

The behavior is different than for onclick with an input. That is why in my opinion this is not a duplicate.

Body:
Just remove the form attribute from your button.

<button name="command" type="submit" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">
      <span class="glyphicon glyphicon-trash" aria-hidden="true">
    </span></button>

Checkout this demo


问:
Replace words keeping original case
I am making a program that replaces words in an MS Word document. I want to keep the original case of the words.

Let's say, there's an expression: "Broken Glass". I want to modify it to "Cristal Roto".

I have two textboxes, Input and Output.

Input is where the term to replace goes, and output is the word with which the input term will be replaced.

For this example, I would put "Broken Glass" in the (Input) textbox, and "Cristal Roto" in the (Output) textbox.

The result in the Word document will be "Cristal roto". The second word's first letter gets lowercased.

Dim rng As Word.Range
rng = objWordS.ActiveDocument.Content
    With rng.Find
        .ClearFormatting()
        .Execute(FindText:=Input.Text, _
          ReplaceWith:=Output.Text, _
          MatchWholeWord:=True, _
          Replace:=Word.WdReplace.wdReplaceAll)
    End With
```
<p>I only care about the original case of the first letter of each word.</p>
<p><strong>EDIT</strong><br />
The reason "Broken Glass" ended up "Cristal roto" was that I missed adding this:</p>
```.Replacement.ClearFormatting()
```

Which I added just between .ClearFormatting and .Execute.

Now the text in the Word File is replaced with the case I use in the Output textbox.

Still, I would like to know if there is a way to detect the case of the original word in the Word File, to automatically adapt the Output Textbox's text without using Proper Case. So:

To Replace: "Broken Glass" - Replace text: "cristal roto" - Desired result: "Cristal Roto".

答:
I ended up doing what I wanted like this:

```<code>Dim rng As Word.Range
        rng = objWordS.ActiveDocument.Content
        With rng.Find
            .ClearFormatting()
            .Replacement.ClearFormatting()
            .Execute(FindText:=InputText)
            If rng.Text = rng.Text.Substring(0, 1).ToLower() + rng.Text.Substring(1) Then
                .Execute(ReplaceWith:=Output.Text.Substring(0, 1).ToLower() + Output.Text.Substring(1).ToLower, _
                         MatchWholeWord:=True, _
                         Replace:=Word.WdReplace.wdReplaceAll)
            End If
            If rng.Text = rng.Text.Substring(0, 1).ToUpper() + rng.Text.Substring(1) Then
                .Execute(ReplaceWith:=Output.Text, _
                         MatchWholeWord:=True, _
                         Replace:=Word.WdReplace.wdReplaceAll)
            End If
        End With
</code>```

This way, I don't have to manually change the casing every single time, what this will do is replace the word based on if its first character is an Uppercase or a Lowercase letter. In case it's an uppercase, the text will be replaced with the casing used in Output (ex. BroKeN WindoW).

If it's a lowercase, then it will replace the words lowercasing the content of output (ex. broken window). With this method, I may be able to implement new conditions in the future, like "If first word's first letter is uppercase, but second word's first letter is lowercase, then...". I hope this will be useful for someone else too.

Actually, I may even implement a condition with Proper Casing to achieve what I asked under EDIT in the main question.

Thanks for your time and help!

Title: Replace words keeping original case

Body:
I am making a program that replaces words in an MS Word document. I want to keep the original case of the words.

Let's say, there's an expression: "Broken Glass". I want to modify it to "Cristal Roto".

I have two textboxes, Input and Output.

Input is where the term to replace goes, and output is the word with which the input term will be replaced.

For this example, I would put "Broken Glass" in the (Input) textbox, and "Cristal Roto" in the (Output) textbox.

The result in the Word document will be "Cristal roto". The second word's first letter gets lowercased.

Dim rng As Word.Range
rng = objWordS.ActiveDocument.Content
    With rng.Find
        .ClearFormatting()
        .Execute(FindText:=Input.Text, _
          ReplaceWith:=Output.Text, _
          MatchWholeWord:=True, _
          Replace:=Word.WdReplace.wdReplaceAll)
    End With

I only care about the original case of the first letter of each word.

EDIT

The reason "Broken Glass" ended up "Cristal roto" was that I missed adding this:

.Replacement.ClearFormatting()

Which I added just between .ClearFormatting and .Execute.

Now the text in the Word File is replaced with the case I use in the Output textbox.

Still, I would like to know if there is a way to detect the case of the original word in the Word File, to automatically adapt the Output Textbox's text without using Proper Case. So:

To Replace: "Broken Glass" - Replace text: "cristal roto" - Desired result: "Cristal Roto".

Body:
I ended up doing what I wanted like this:

Dim rng As Word.Range
        rng = objWordS.ActiveDocument.Content
        With rng.Find
            .ClearFormatting()
            .Replacement.ClearFormatting()
            .Execute(FindText:=InputText)
            If rng.Text = rng.Text.Substring(0, 1).ToLower() + rng.Text.Substring(1) Then
                .Execute(ReplaceWith:=Output.Text.Substring(0, 1).ToLower() + Output.Text.Substring(1).ToLower, _
                         MatchWholeWord:=True, _
                         Replace:=Word.WdReplace.wdReplaceAll)
            End If
            If rng.Text = rng.Text.Substring(0, 1).ToUpper() + rng.Text.Substring(1) Then
                .Execute(ReplaceWith:=Output.Text, _
                         MatchWholeWord:=True, _
                         Replace:=Word.WdReplace.wdReplaceAll)
            End If
        End With

This way, I don't have to manually change the casing every single time, what this will do is replace the word based on if its first character is an Uppercase or a Lowercase letter. In case it's an uppercase, the text will be replaced with the casing used in Output (ex. BroKeN WindoW).

If it's a lowercase, then it will replace the words lowercasing the content of output (ex. broken window). With this method, I may be able to implement new conditions in the future, like "If first word's first letter is uppercase, but second word's first letter is lowercase, then...". I hope this will be useful for someone else too.

Actually, I may even implement a condition with Proper Casing to achieve what I asked under EDIT in the main question.

Thanks for your time and help!


问:
Button text is cut and not centered
I create a button using a storyboard, which is assigned the cornerRadius, borderWidth, textAlignment, and clipsToBounds properties. And by code I assigned the following text to fit the width of the button. But when executing it isn't vertical center and also it is visualized cut.

```<code>añadirOtrosCursos.titleLabel?.minimumScaleFactor = 0.5
añadirOtrosCursos.titleLabel?.numberOfLines = 1
añadirOtrosCursos.titleLabel?.adjustsFontSizeToFitWidth = true
añadirOtrosCursos.contentVerticalAlignment = .center
</code>```

答: Try clicking on the UIButton in Main.storyboard, going to the attributes inspector, scrolling down to the "control" category, and making sure that the vertical alignment is set to center. This is what you should see.</p>

Title: Button text is cut and not centered

Body:
I create a button using a storyboard, which is assigned the cornerRadius, borderWidth, textAlignment, and clipsToBounds properties. And by code I assigned the following text to fit the width of the button. But when executing it isn't vertical center and also it is visualized cut.

añadirOtrosCursos.titleLabel?.minimumScaleFactor = 0.5
añadirOtrosCursos.titleLabel?.numberOfLines = 1
añadirOtrosCursos.titleLabel?.adjustsFontSizeToFitWidth = true
añadirOtrosCursos.contentVerticalAlignment = .center


问:
Error and warning while installing CodeIgniter through Composer
I tried to install CodeIgniter through composer using this:

```<code>composer require bcit-ci/CodeIgniter
</code>```

And it installed successfully I got a warning, see screenshot

And then I tried to install with this:

```<code>composer require codeigniter/framework
</code>```

and I got a fatal error, see screenshot here

I don't know what I am doing wrong.

See all screenshots here: http://imgur.com/a/zsnER

答: I just removed the cache of Composer and tried to install again and I got success.</p>

Body:
I tried to install CodeIgniter through composer using this:

composer require bcit-ci/CodeIgniter

And it installed successfully I got a warning, see screenshot

And then I tried to install with this:

composer require codeigniter/framework

and I got a fatal error, see screenshot here

I don't know what I am doing wrong.

See all screenshots here: http://imgur.com/a/zsnER


问:
Counting rows in Vertica table per JDBC
How can I get the number of lines in a ResultSet, plugged on a Vertica 8 database, knowing every ResultSet is forward only when using Vertica? I'm trying to adapt an existing software, originally developped for Oracle, so if I could find a way to avoid rewritting everything using calls to SELECT count(*)... queries, it would really make my life easier...

答:
Your question is a bit tricky ! Because you mention "JDBC", which point ot the fact that only jdbc connections should be monitored for this !

Now ! in regards to your question and this might not be what you are looking for.

In order for you to know where or from which JDBC connection your query`s come you need to label your JDBC (good practice), this way you can point to your "bad/heavy" users and know to whom you need to explain how Vertica works.

1- Label JDBC

2 - Use the sessions table to identify from where the connections come from.

SELECT
        ss.session_id,
        qp.query_type,
        qp.processed_row_count,
        qp.user_name
    FROM
        query_profiles qp
    JOIN
        sessions ss
    ON
        ss.session_id=qp.session_id
    WHERE
        ss.client_label=''
    AND qp.error_code IS NULL
    AND qp.is_executing='false'
    ORDER BY
        qp.processed_row_count DESC

The Column PROCESSED_ROW_COUNT in query_profile shows the number of rows returned by the query.
Vertica Doc reference

I think this is half of the answers but i hope it helped.

Title: Counting rows in Vertica table per JDBC


问:
adjacency as an operator - can any lexer handle it?
Say a language defines adjacency of two mathematical unicode alphanumerical symbols as an operator. Say, +1 means  %adj  + 1, where %adj stands for whatever operator adjacency defines, multiplication in this case. I was wondering, can any existing lexical analysis tool handle this? </p>

答:
Here is one example using pyparsing in Python:

```<code>import pyparsing as pp

integer = pp.pyparsing_common.integer()
variable = pp.oneOf(list("abcdefghijklmnopqrstuvwxyz"))

base_operand = integer | variable

implied_multiplication = pp.Empty().addParseAction(lambda: "*")
expr = pp.infixNotation(base_operand,
                [
                    ("**", 2, pp.opAssoc.LEFT),
                    (implied_multiplication, 2, pp.opAssoc.LEFT),
                    (pp.oneOf("+ -"), 1, pp.opAssoc.RIGHT),
                    (pp.oneOf("* /"), 2, pp.opAssoc.LEFT),
                    (pp.oneOf("+ -"), 2, pp.opAssoc.LEFT),
                ])
</code>```

This assumes that variables are just single characters. There is also some fudging of precedence of operations to make adjacency, exponentiation, and leading signs work. The parse action added to the implied_multiplication expression is there to show the insertion of the multiplication operator.

Here is some test output:

```<code>tests = """
    x-4
    ax**2 + bx +c
    ax**2-bx+c
    mx+b
    """
expr.runTests(tests, fullDump=False)
</code>```

prints:

```<code>x-4
[['x', '-', 4]]

ax**2 + bx +c
[[['a', '*', ['x', '**', 2]], '+', ['b', '*', 'x'], '+', 'c']]

ax**2-bx+c
[[['a', '*', ['x', '**', 2]], '-', ['b', '*', 'x'], '+', 'c']]

mx+b
[[['m', '*', 'x'], '+', 'b']]
</code>```

Body:
Here is one example using pyparsing in Python:

import pyparsing as pp

integer = pp.pyparsing_common.integer()
variable = pp.oneOf(list("abcdefghijklmnopqrstuvwxyz"))

base_operand = integer | variable

implied_multiplication = pp.Empty().addParseAction(lambda: "*")
expr = pp.infixNotation(base_operand,
                [
                    ("**", 2, pp.opAssoc.LEFT),
                    (implied_multiplication, 2, pp.opAssoc.LEFT),
                    (pp.oneOf("+ -"), 1, pp.opAssoc.RIGHT),
                    (pp.oneOf("* /"), 2, pp.opAssoc.LEFT),
                    (pp.oneOf("+ -"), 2, pp.opAssoc.LEFT),
                ])

This assumes that variables are just single characters. There is also some fudging of precedence of operations to make adjacency, exponentiation, and leading signs work. The parse action added to the implied_multiplication expression is there to show the insertion of the multiplication operator.

Here is some test output:

tests = """
    x-4
    ax**2 + bx +c
    ax**2-bx+c
    mx+b
    """
expr.runTests(tests, fullDump=False)

prints:

x-4
[['x', '-', 4]]

ax**2 + bx +c
[[['a', '*', ['x', '**', 2]], '+', ['b', '*', 'x'], '+', 'c']]

ax**2-bx+c
[[['a', '*', ['x', '**', 2]], '-', ['b', '*', 'x'], '+', 'c']]

mx+b
[[['m', '*', 'x'], '+', 'b']]


问:
Using $_POST to get select option value from HTML
I use select as below:

```<code><select name="taskOption">
    <option>First</option>
    <option>Second</option>
    <option>Third</option>
</select>
</code>```

How do I get the value from the select option and store it into a variable for future use, in PHP?

答:
```<code><select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
</code>```

try this

```<code><?php
if(isset($_POST['button_name'])){
$var = $_POST['taskOption']
if($var == "1"){
echo"your data here";
}
}?>
</code>```

Body:
I use select as below:

<select name="taskOption">
    <option>First</option>
    <option>Second</option>
    <option>Third</option>
</select>

How do I get the value from the select option and store it into a variable for future use, in PHP?

Body:
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>

try this

<?php
if(isset($_POST['button_name'])){
$var = $_POST['taskOption']
if($var == "1"){
echo"your data here";
}
}?>


问:
C++ - Is it bad practice to have variables that are not class object properties inside a class?
Suppose I have a class Sensor as shown below:

```<code>class Sensor
{
    public:
        Sensor();
        array <float, 3> marker_pos(float, float, float);

    private:
        float range;
        float phi;
        array <float, 3> temp;
        int flag = 0;
};
</code>```

The variables range and phi are properties or variables of the sensor object. But the variables temp and flag are just normal variables that are to be used inside the function marker_pose.

1. Is it bad practice to define/declare temp and flag inside the class ?

2. If I define/declare them inside the function marker_pose, it will be defined every time I call that function. Is that a good idea?

3. What will be the best practice to follow in such situations ?

答:
In C++, you have to declare variables as late as you can (ie: as deep in scope as you can).

Minimize the life span of different variables may enhance the visibility of your code and ease the debug and maintenance of your program.

Body:
Suppose I have a class Sensor as shown below:

class Sensor
{
    public:
        Sensor();
        array <float, 3> marker_pos(float, float, float);

    private:
        float range;
        float phi;
        array <float, 3> temp;
        int flag = 0;
};

The variables range and phi are properties or variables of the sensor object. But the variables temp and flag are just normal variables that are to be used inside the function marker_pose.

1. Is it bad practice to define/declare temp and flag inside the class ?

2. If I define/declare them inside the function marker_pose, it will be defined every time I call that function. Is that a good idea?

3. What will be the best practice to follow in such situations ?