问:
Android: Saving Preferences with multiple editTexts
I am trying to save the values the users put in the 3 editText fiels (editText1, editText2, editText3) so that they show up in the right field after the app restart.
Problem: Only the last value of editText3 gets saved in is filled in into the 3 fields after the restart.
What would be a workaround so that the values of the specific fields get saved and reloaded? </p>

答:
You need to use a different key for each saved text:

```<code>savePreferences("storedName", editText1.getText().toString());
savePreferences("storedName2", editText2.getText().toString());
savePreferences("storedName3", editText3.getText().toString());
</code>```

Then, to retrieve each text

```<code>private void loadSavedPreferences() {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    editText1.setText(sharedPreferences.getString("storedName", "YourName"));
    editText2.setText(sharedPreferences.getString("storedName2", "YourName"));
    editText3.setText(sharedPreferences.getString("storedName3", "YourName"));
}
</code>```

Be careful, because the second parameter ("YourName") in the getString is the default Value in case you have not save any text with the specified key parameter.

Body:
You need to use a different key for each saved text:

savePreferences("storedName", editText1.getText().toString());
savePreferences("storedName2", editText2.getText().toString());
savePreferences("storedName3", editText3.getText().toString());

Then, to retrieve each text

private void loadSavedPreferences() {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    editText1.setText(sharedPreferences.getString("storedName", "YourName"));
    editText2.setText(sharedPreferences.getString("storedName2", "YourName"));
    editText3.setText(sharedPreferences.getString("storedName3", "YourName"));
}

Be careful, because the second parameter ("YourName") in the getString is the default Value in case you have not save any text with the specified key parameter.


来源: stackexchange

问:
Express.js: res.render() does not send data when wrapped in promise chain
I recently started refactoring older callback-hell routes to use promises. (Note: the refactor is not complete so some of the following code is ugly)

Doing so broke my res.render() function.

I am using EJS for my render engine.

Most of my promise chains are built off of MongoDB / Mongoose queries.

The basic app structure is a complex survey / quiz that sorts users into different categories. It stores their info and renders a custom EJS page at the end. Here's how the final call works, basically:

```<code>         mongoose.model('Result')
             .findOne({quizId: req.query.id})
             .then(getPageData)
             .then(renderPage)
             .catch(errorHandler)
</code>```

Simple enough, in theory.

Relevant functions:

```<code>    let getPageData = (mongooseResult) => {

      let resultsPage;
      let analyticsData;

      if (mongooseResult.answers.section1.question1.answer != null && mongooseResult.answers.section1.question1.answer != undefined){
          let resultsPage = WP.getPage(wp_pages_data, 'slug', mongooseResult.coreFit);
          let analyticsData = {
            quizId: mongooseResult.quizId,
            coreFit: mongooseResult.coreFit,
            secondFit: mongooseResult.secondFit,
            degree: mongooseResult.answers.section1.question1.answer,
            year: mongooseResult.answers.section1.question2.answer,
            concentration: mongooseResult.answers.section1.question3.answer,
            views: mongooseResult.views,
          }

        mongooseResult.views++;
        mongooseResult.save();

        return [resultsPage, analyticsData, mongooseResult];
      } else {
        throw new Error('S1Q1 IS UNDEFINED');
      }
    };
    let renderPage = ([resultsPage, analyticsData, mongooseResult]) => {
      if (resultsPage != null && resultsPage != undefined){

        // WHY IS MY RENDER NOT WORKING???
        res.render('templates/' + mongooseResult.coreFit,  Object.assign({}, WP.get_WP_data(resultsPage), getPartials(mongooseResult.modules), analyticsData), (err, html) => {if (err) console.log(err); else res.send(html);});
      } else {
        throw new Error('GETTING PAGE DATA RETURNED UNDEFINED');
      }
    };
</code>```

Incoming requests are first routed to a /submit POST route - which manipulates some data, stores it all in the DB, then does res.redirect() to the /results?id=12345 GET route, which runs the logic above.

What's funky is that the render() actually fires; the callback ( (err, html) => {if (err) console.log(err); else res.send(html);} ) sends rendered HTML to IF YOU HIT THE ROUTE A SECOND TIME.

Completing the survey does NOT generate a response; but it DOES successfully store all our info in the DB and console.logs the ID to which the client request should redirect. Hitting the GET route with this generated ID / URL, literally by copy-pasting it, renders just fine.

Swapping the render for a simple res.send('wtf') works - an actual response is sent to the client. (in this case the string 'wtf' ... )

The response just doesn't send back data. I don't get it. Any ideas?

UPDATE:
Strangely enough, hitting the route manually vs the redirect from my earlier POST request produce different results with a simple res.send('wtf mate').

Hitting the GET route and passing in a previously existing ID to the req.query manually:

Hitting the GET route AFTER the res.redirect() call from the prior POST request:

This might be more an Express request type mismatch issue? Why would a res.redirect('/results?id=someString') call mutate the URL vs sending back a string / HTML?

答:
Let's try to debug issue by testing code parts.

I've few clues, one of them is that 'templates/' + result.coreFit does not have template.

Try to check coreFit value if there is a file in templates folder with same value-name.

Try this code and tell me if it's working:

```<code>const
  _ = require('lodash'),
  mongoose = require('mongoose');

const getQuizResultById = quizId => {
    return new Promise((resolve, reject) => {
        const
            Result = mongoose.model('Result'),
            query = {
                quizId
            };

        Result
            .findOne(query)
            .then(resolve)
            .catch(reject);
    });
};

const getPageData = result => {
    if (_.get(result, 'answers.section1.question1.answer')) {
        let resultsPage = WP.getPage(wp_pages_data, 'slug', result.coreFit);
        let
        analyticsData = _.pick(result, ['quizId', 'coreFit', 'secondFit', 'views']);
        analyticsData.degree = _.get(result, 'answers.section1.question1.answer');
        analyticsData.year = _.get(result, 'answers.section1.question2.answer');
        analyticsData.concentration = _.get(result, 'answers.section1.question3.answer');

        result.views++;
        result.save();

        return [resultsPage, analyticsData, result];
    }

    throw new Error('S1Q1 IS UNDEFINED');
}

const renderPage = ([resultsPage, analyticsData, result], res) => {
    if (resultsPage) {
        return res.render(
            'templates/' + result.coreFit,
            Object.assign({}, WP.get_WP_data(resultsPage), getPartials(result.modules), analyticsData),
            (err, html) => {
                if (err) {
                    console.log(err);
                    return res.status(500).send('Ooopsss...');
                }
                res.send(html);
            });
    }

    throw new Error('GETTING PAGE DATA RETURNED UNDEFINED');
};

router.get('/results', (req, res) => {
    getQuizResultById(req.query.id)
        .then(getPageData)
        .then(data => {
           renderPage(data, res);
        })
        .catch(errorHandler);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I recently started refactoring older callback-hell routes to use promises. (Note: the refactor is not complete so some of the following code is ugly)

Doing so broke my res.render() function.

I am using EJS for my render engine.

Most of my promise chains are built off of MongoDB / Mongoose queries.

The basic app structure is a complex survey / quiz that sorts users into different categories. It stores their info and renders a custom EJS page at the end. Here's how the final call works, basically:

         mongoose.model('Result')
             .findOne({quizId: req.query.id})
             .then(getPageData)
             .then(renderPage)
             .catch(errorHandler)

Simple enough, in theory.

Relevant functions:

    let getPageData = (mongooseResult) => {

      let resultsPage;
      let analyticsData;

      if (mongooseResult.answers.section1.question1.answer != null && mongooseResult.answers.section1.question1.answer != undefined){
          let resultsPage = WP.getPage(wp_pages_data, 'slug', mongooseResult.coreFit);
          let analyticsData = {
            quizId: mongooseResult.quizId,
            coreFit: mongooseResult.coreFit,
            secondFit: mongooseResult.secondFit,
            degree: mongooseResult.answers.section1.question1.answer,
            year: mongooseResult.answers.section1.question2.answer,
            concentration: mongooseResult.answers.section1.question3.answer,
            views: mongooseResult.views,
          }

        mongooseResult.views++;
        mongooseResult.save();

        return [resultsPage, analyticsData, mongooseResult];
      } else {
        throw new Error('S1Q1 IS UNDEFINED');
      }
    };
    let renderPage = ([resultsPage, analyticsData, mongooseResult]) => {
      if (resultsPage != null && resultsPage != undefined){

        // WHY IS MY RENDER NOT WORKING???
        res.render('templates/' + mongooseResult.coreFit,  Object.assign({}, WP.get_WP_data(resultsPage), getPartials(mongooseResult.modules), analyticsData), (err, html) => {if (err) console.log(err); else res.send(html);});
      } else {
        throw new Error('GETTING PAGE DATA RETURNED UNDEFINED');
      }
    };

Incoming requests are first routed to a /submit POST route - which manipulates some data, stores it all in the DB, then does res.redirect() to the /results?id=12345 GET route, which runs the logic above.

What's funky is that the render() actually fires; the callback ( (err, html) => {if (err) console.log(err); else res.send(html);} ) sends rendered HTML to IF YOU HIT THE ROUTE A SECOND TIME.

Completing the survey does NOT generate a response; but it DOES successfully store all our info in the DB and console.logs the ID to which the client request should redirect. Hitting the GET route with this generated ID / URL, literally by copy-pasting it, renders just fine.

Swapping the render for a simple res.send('wtf') works - an actual response is sent to the client. (in this case the string 'wtf' ... )

The response just doesn't send back data. I don't get it. Any ideas?

UPDATE:
Strangely enough, hitting the route manually vs the redirect from my earlier POST request produce different results with a simple res.send('wtf mate').

Hitting the GET route and passing in a previously existing ID to the req.query manually:

Hitting the GET route AFTER the res.redirect() call from the prior POST request:

This might be more an Express request type mismatch issue? Why would a res.redirect('/results?id=someString') call mutate the URL vs sending back a string / HTML?

Body:
Let's try to debug issue by testing code parts.

I've few clues, one of them is that 'templates/' + result.coreFit does not have template.

Try to check coreFit value if there is a file in templates folder with same value-name.

Try this code and tell me if it's working:

const
  _ = require('lodash'),
  mongoose = require('mongoose');

const getQuizResultById = quizId => {
    return new Promise((resolve, reject) => {
        const
            Result = mongoose.model('Result'),
            query = {
                quizId
            };

        Result
            .findOne(query)
            .then(resolve)
            .catch(reject);
    });
};

const getPageData = result => {
    if (_.get(result, 'answers.section1.question1.answer')) {
        let resultsPage = WP.getPage(wp_pages_data, 'slug', result.coreFit);
        let
        analyticsData = _.pick(result, ['quizId', 'coreFit', 'secondFit', 'views']);
        analyticsData.degree = _.get(result, 'answers.section1.question1.answer');
        analyticsData.year = _.get(result, 'answers.section1.question2.answer');
        analyticsData.concentration = _.get(result, 'answers.section1.question3.answer');

        result.views++;
        result.save();

        return [resultsPage, analyticsData, result];
    }

    throw new Error('S1Q1 IS UNDEFINED');
}

const renderPage = ([resultsPage, analyticsData, result], res) => {
    if (resultsPage) {
        return res.render(
            'templates/' + result.coreFit,
            Object.assign({}, WP.get_WP_data(resultsPage), getPartials(result.modules), analyticsData),
            (err, html) => {
                if (err) {
                    console.log(err);
                    return res.status(500).send('Ooopsss...');
                }
                res.send(html);
            });
    }

    throw new Error('GETTING PAGE DATA RETURNED UNDEFINED');
};

router.get('/results', (req, res) => {
    getQuizResultById(req.query.id)
        .then(getPageData)
        .then(data => {
           renderPage(data, res);
        })
        .catch(errorHandler);
});


问:
why passing in a temp variable into const ref in ctor work?
```<code>// Example program
#include <iostream>
#include <string>

struct foo
{
    int d_member;

    foo(const int & in):
    d_member(in){};
};

int main()
{
    foo *p;

    {
        int temp = 5;
        p = new foo(temp);
    }

    std::cout << p->d_member << std::endl;

    return 0;
}
</code>```

Foo takes a const ref in it's ctor to a int, and I passed a temporary int to it.
temp is destroyed after new. Why I am still able to print out d_member?

答: Yes, temp is destroyed, but before that it was copied during d_member(in) initialization. So nothing is wrong here

Body:
// Example program
#include <iostream>
#include <string>

struct foo
{
    int d_member;

    foo(const int & in):
    d_member(in){};
};

int main()
{
    foo *p;

    {
        int temp = 5;
        p = new foo(temp);
    }

    std::cout <
d_member << std::endl;

    return 0;
}

Foo takes a const ref in it's ctor to a int, and I passed a temporary int to it.
temp is destroyed after new. Why I am still able to print out d_member?


问:
program crashes after executing the second case in a switch
I'm writing a Programm that is supposed to combine a few different Programms I wrote before (all of then worked).
My Problem:
After case 'r' has been executed the Programm crashes.
My Programm(Sorry for the Text beeing in german but I guess that doesnt matter too much. If it does just tell me and I will change it to english.):

main.cpp

```<code>#include <iostream>
#include <conio.h>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <fstream>
#include "GameMaster.h"

using namespace std;

int main(int argc, char** argv) {

string vBefehlH = "help";       //vergleichsBefehlX
string vBefehlR = "rdm";
string vBefehlI = "items";
string eBefehl;                 //eingegebener Befehl
char Befehl;

cout << "------Willkommen GameMaster------" << endl <<endl;
cout << "Geben sie *help* ein, um eine Liste der verf\201gbaren Befehle auszugeben." << endl;
while(1)
{
    cin >> Befehl;              //wartet auf die eingabe eines Befehls

    if(eBefehl == vBefehlH)
    {
        Befehl = 'h';
    }

    if(eBefehl == vBefehlR)
    {
        Befehl = 'r';
    }

    switch(Befehl)
    {
        case 'h':       //gibt die Hilfe aus
        {
            cout << "help       -Gibt eine Liste aller verf\201gbaren Befehle im aktuellen Bereich aus." << endl;
            cout << "rdm        -Erstellt einen neuen Charakter." << endl;
            cout << "items      -Geht in den Item Bereich." << endl;

            break;
        }

        case 'r':
        {
            string Name;
            string Geschlecht;
            string Rasse;
            string Beruf;
            string Hautfarbe;
            string Haarfarbe;
            string Augenfarbe;

            cout << "Name: ";
            cin >> Name;            //cin muss aus irgendeinem Grund doppelt sein. Sonst wird es übersprungen.
            cin >> Name;
            cout << "Geschlecht: ";
            cin >> Geschlecht;
            cout << "Rasse: ";
            cin >> Rasse;
            cout << "Beruf: ";
            cin >> Beruf;
            cout << "Hautfarbe: ";
            cin >> Hautfarbe;
            cout << "Haarfarbe: ";
            cin >> Haarfarbe;
            cout << "Augenfarbe: ";
            cin >> Augenfarbe;

            Charakter Charakter1(Name, Geschlecht, Rasse, Beruf, Hautfarbe, Haarfarbe, Augenfarbe);

            Charakter1.Werte();
            Charakter1.grWerte();
            Charakter1.spWerte();
            Charakter1.SchreibCharakter();
            cout << endl << "Der Charakter wurde erfolgreich erstellt und befindet sich in *rdmCharakter.txt*" << endl;
            system ("pause");
            break;
        }
    }
}

return 0;
</code>```

}

Now I dont think there is something wrong with the other sorce files in my Project but I'll just put them in down here just in case.

GameMaster.h

```<code>#ifndef GameMasterH
#define GameMasterH

using namespace std;

class Charakter
{
private:
                        //Die Grundinformationen, welche manuell eingegeben
werden
string Name;
string Geschlecht;
string Rasse;
string Beruf;
string Hautfarbe;
string Haarfarbe;
string Augenfarbe;
                        //Die Werte, welche durch RNG bestimmt werden
int Wert[9];
int spWert[58];         //Spezialwerte
int grWert[3];          //Alter/Größe/Gewicht

public:

//Konstruktor
Charakter(string, string, string, string, string, string, string);
//Destruktor
~Charakter();
//mothoden
void Werte();               //bestimmt die Grundwerte
void SchreibCharakter();    //Schreibt den Charakter
void spWerte();             //bestimmt die Spezialwerte
void grWerte();             //bestimmt Alter/Größe/Gewicht
};
</code>```

Charakter.cpp

```<code>#include <iostream>
#include <conio.h>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include "GameMaster.h"

using namespace std;

//Konstruktor: Weist Die Grundinfos zu.
Charakter::Charakter(string N, string G, string R, string B, string HAU,     string HAA, string A)
{
Name = N;
Geschlecht = G;
Rasse = R;
Beruf = B;
Hautfarbe = HAU;
Haarfarbe = HAA;
Augenfarbe = A;
}

//Destruktor
Charakter::~Charakter()
{

}

void Charakter::Werte()                     //Weist die Grundwerte zu
{
srand(time(0));

for(int i = 1; i < 9; i++)
{
    Wert[i] = 8+(rand()%7);
}
}

void Charakter::grWerte()                   //Weist Alter, Größe und Gewicht zu
{
srand(time(0));

grWert[1] = 18+(rand()%43);
grWert[2] = 160+(rand()%41);
grWert[3] = 70+(rand()%41);
}

void Charakter::spWerte()                   //Weist Die spezifischen Werte zu
{
srand(time(0));

for(int i = 1; i < 58; i++)
{
    spWert[i] = (rand()%6);
}
}

void Charakter::SchreibCharakter()          //Schreibt die Textdatei
{
FILE* CharakterFile;

CharakterFile = fopen("rdmCharakter.txt", "w");

if(CharakterFile != NULL)
{
    fprintf(CharakterFile, "Name: %s \n", Name.c_str());
    fprintf(CharakterFile, "Geschlecht: %s \n", Geschlecht.c_str());
    fprintf(CharakterFile, "Rasse: %s \n", Rasse.c_str());
    fprintf(CharakterFile, "Beruf: %s \n", Beruf.c_str());
    fprintf(CharakterFile, "Alter: %d \n", grWert[1]);
    fprintf(CharakterFile, "Hautfarbe: %s \n", Hautfarbe.c_str());
    fprintf(CharakterFile, "Haarfarbe: %s \n", Haarfarbe.c_str());
    fprintf(CharakterFile, "Augenfarbe: %s \n", Augenfarbe.c_str());
    fprintf(CharakterFile, "Größe: %d \n", grWert[2]);
    fprintf(CharakterFile, "Gewicht: %d \n", grWert[3]);
    fprintf(CharakterFile, "Persönlichkeit: \n\n\n\n");

    fprintf(CharakterFile, "        Eigenschaften \n \n");
    fprintf(CharakterFile, "MU: %d \n", Wert[1]);
    fprintf(CharakterFile, "KL: %d \n", Wert[2]);
    fprintf(CharakterFile, "IN: %d \n", Wert[3]);
    fprintf(CharakterFile, "CH: %d \n", Wert[4]);
    fprintf(CharakterFile, "FF: %d \n", Wert[5]);
    fprintf(CharakterFile, "GE: %d \n", Wert[6]);
    fprintf(CharakterFile, "KO: %d \n", Wert[7]);
    fprintf(CharakterFile, "KK: %d \n\n\n", Wert[8]);

    fprintf(CharakterFile, "VORTEILE:           NACHTEILE:\n\n\n\n\n\n\n\n\n\n");

    fprintf(CharakterFile, "        HANDWERKSTALENTE\n\n");

    fprintf(CharakterFile, "ALCHEMIE        (KL/KL/IN): %d \n", spWert[1]);
    fprintf(CharakterFile, "HANDEL          (KL/IN/CH): %d \n", spWert[2]);
    fprintf(CharakterFile, "HEILKUNDE-GIFT      (MU/KL/IN): %d \n", spWert[3]);
    fprintf(CharakterFile, "HEILKUNDE-KRANK     (MU/KL/IN): %d \n", spWert[4]);
    fprintf(CharakterFile, "HEILKUNDE-SEELE     (KL/IN/CH): %d \n", spWert[5]);
    fprintf(CharakterFile, "HEILKUNDE-WUNDEN    (KL/FF/FF): %d \n", spWert[6]);
    fprintf(CharakterFile, "HOLZBEARBEITUNG     (KL/KK/FF): %d \n", spWert[7]);
    fprintf(CharakterFile, "LEDERBEARBEITUNG    (KL/FF/FF): %d \n", spWert[8]);
    fprintf(CharakterFile, "METALLBEARBEITUNG   (KL/FF/KK): %d \n", spWert[9]);
    fprintf(CharakterFile, "STEINBEARBEITUNG    (FF/FF/KK): %d \n", spWert[10]);
    fprintf(CharakterFile, "STOFFBEARBEITUNG    (KL/FF/FF): %d \n", spWert[11]);
    fprintf(CharakterFile, "KOCHEN&BACKEN       (KL/IN/FF): %d \n", spWert[12]);
    fprintf(CharakterFile, "SCHLÖSSERKNACKEN    (IN/FF/FF): %d \n", spWert[13]);
    fprintf(CharakterFile, "MALEN&ZEICHNEN      (KL/IN/FF): %d \n\n", spWert[14]);

    fprintf(CharakterFile, "        WISSENSTALENTE\n\n");

    fprintf(CharakterFile, "BRETT&GLÜCKSSPIEL   (KL/KL/IN): %d \n", spWert[15]);
    fprintf(CharakterFile, "GEOGRAPHIE      (KL/IN/IN): %d \n", spWert[16]);
    fprintf(CharakterFile, "GESCHICHTSWISSEN    (KL/KL/IN): %d \n", spWert[17]);
    fprintf(CharakterFile, "RELIGION        (KL/KL/CH): %d \n", spWert[18]);
    fprintf(CharakterFile, "MECHANIK        (KL/KL/FF): %d \n", spWert[19]);
    fprintf(CharakterFile, "RECHNEN         (KL/KL/KL): %d \n", spWert[20]);
    fprintf(CharakterFile, "SAGEN&LEGENDEN      (KL/KL/IN): %d \n", spWert[21]);
    fprintf(CharakterFile, "RECHTSKUNDE     (KL/IN/IN): %d \n", spWert[22]);
    fprintf(CharakterFile, "STRATEGIE       (KL/IN/IN): %d \n", spWert[23]);
    fprintf(CharakterFile, "MEDIZIN         (KL/KL/IN): %d \n", spWert[24]);
    fprintf(CharakterFile, "SEEFAHRT        (KL/IN/MU): %d \n\n", spWert[25]);

    fprintf(CharakterFile, "        NATURTALENTE\n\n");

    fprintf(CharakterFile, "FÄHRTENSUCHE        (KL/IN/IN): %d \n", spWert[26]);
    fprintf(CharakterFile, "FESSELN         (KL/FF/KK): %d \n", spWert[27]);
    fprintf(CharakterFile, "FISCHEN&ANGELN      (IN/FF/KO): %d \n", spWert[28]);
    fprintf(CharakterFile, "ORIENTIRUNG     (KL/IN/IN): %d \n", spWert[29]);
    fprintf(CharakterFile, "PFLANZENKUNDE       (KL/IN/FF): %d \n", spWert[30]);
    fprintf(CharakterFile, "TIERKUNDE       (MU/KL/IN): %d \n", spWert[31]);
    fprintf(CharakterFile, "WILDNISLEBEN        (IN/GE/KO): %d \n", spWert[32]);
    fprintf(CharakterFile, "JAGEN           (IN/KL/GE): %d \n", spWert[33]);
    fprintf(CharakterFile, "STERNKUNDE      (KL/KL/IN): %d \n\n", spWert[34]);

    fprintf(CharakterFile, "        KÖRPERTALENTE\n\n");

    fprintf(CharakterFile, "KLETTERN        (MU/GE/KK): %d \n", spWert[35]);
    fprintf(CharakterFile, "BALANCIEREN     (GE/GE/KO): %d \n", spWert[36]);
    fprintf(CharakterFile, "REITEN          (IN/GE/KO): %d \n", spWert[37]);
    fprintf(CharakterFile, "SCHWIMMEN       (GE/KO/KK): %d \n", spWert[38]);
    fprintf(CharakterFile, "SELBSTBEHERRSCHUNG  (MU/IN/KO): %d \n", spWert[39]);
    fprintf(CharakterFile, "SINGEN          (IN/CH/KL): %d \n", spWert[40]);
    fprintf(CharakterFile, "SINNESSCHÄRFE       (KL/IN/IN): %d \n", spWert[41]);
    fprintf(CharakterFile, "TANZEN          (CH/GE/GE): %d \n", spWert[42]);
    fprintf(CharakterFile, "TASCHENDIEBSTAHL    (MU/IN/FF): %d \n", spWert[43]);
    fprintf(CharakterFile, "VERBERGEN       (MU/IN/GE): %d \n", spWert[44]);
    fprintf(CharakterFile, "ZECHEN          (IN/KO/KK): %d \n", spWert[45]);
    fprintf(CharakterFile, "SCHLEICHEN      (GE/GE/KO): %d \n", spWert[46]);
    fprintf(CharakterFile, "MUSIKINSTRUMENTE    (KL/IN/KO): %d \n", spWert[47]);
    fprintf(CharakterFile, "REFLEXE         (GE/GE/FF): %d \n\n", spWert[48]);

    fprintf(CharakterFile, "        GESELLSCHAFTSTALENTE\n\n");

    fprintf(CharakterFile, "PREDIGEN        (MU/KL/IN): %d \n", spWert[49]);
    fprintf(CharakterFile, "ÜBERZEUGEN      (MU/IN/CH): %d \n", spWert[50]);
    fprintf(CharakterFile, "BETÖREN         (MU/CH/CH): %d \n", spWert[51]);
    fprintf(CharakterFile, "EINSCHÜCHTERN       (MU/KK/KK): %d \n", spWert[52]);
    fprintf(CharakterFile, "ETIKETTE        (KL/IN/CH): %d \n", spWert[53]);
    fprintf(CharakterFile, "GASSENWISSEN        (KL/IN/IN): %d \n", spWert[54]);
    fprintf(CharakterFile, "MENSCHENKENNTNIS    (KL/IN/CH): %d \n", spWert[55]);
    fprintf(CharakterFile, "ÜBERREDEN       (MU/KL/CH): %d \n", spWert[56]);
    fprintf(CharakterFile, "VERKLEIDEN      (IN/CH/GE): %d \n", spWert[57]);
    fprintf(CharakterFile, "WILLENSKRAFT        (MU/MU/IN): %d \n\n", spWert[58]);

    fprintf(CharakterFile, "        KAMPFTECHNIKEN\n\n");

    fprintf(CharakterFile, "ARMBRÜSTE       FF: \n");
    fprintf(CharakterFile, "BÖGEN           FF: \n");
    fprintf(CharakterFile, "MESSER          GE: \n");
    fprintf(CharakterFile, "HIEBWAFFEN      KK: \n");
    fprintf(CharakterFile, "KETTENWAFFEN        KK: \n");
    fprintf(CharakterFile, "RAUFEN          GE: \n");
    fprintf(CharakterFile, "SCHILDE         KK: \n");
    fprintf(CharakterFile, "SCHWERTER       KK: \n");
    fprintf(CharakterFile, "WURFWAFFEN      FF: \n");
    fprintf(CharakterFile, "SCHUSSWAFFEN L      FF: \n");
    fprintf(CharakterFile, "SCHUSSWAFFEN M      GE: \n");
    fprintf(CharakterFile, "SCHUSSWAFFEN S      KK: \n\n");

    fprintf(CharakterFile, "NAHKAMPFWAFFEN:\n\n\n\n\n\n");

    fprintf(CharakterFile, "FERNKAMPFWAFFEN:\n\n\n\n\n\n");

    fprintf(CharakterFile, "INVENTAR:\n\n\n\n\n\n");

    fclose(CharakterFile);
}
else
{
    cout << "Error: Die Datei kann nicht geoeffnet werden.";        //Gibt eine Fehlermeldung aus, falls die Text datei nicht geöffnet werden kann
}
}
</code>```

答:
This is not correct

```<code>grWert[3] = 70+(rand()%41);
</code>```

your array is 3 is in size, but index is then 0-2, 3 will go past end of array.

Body:
I'm writing a Programm that is supposed to combine a few different Programms I wrote before (all of then worked).
My Problem:
After case 'r' has been executed the Programm crashes.
My Programm(Sorry for the Text beeing in german but I guess that doesnt matter too much. If it does just tell me and I will change it to english.):

main.cpp

#include <iostream>
#include <conio.h>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <fstream>
#include "GameMaster.h"

using namespace std;

int main(int argc, char** argv) {

string vBefehlH = "help";       //vergleichsBefehlX
string vBefehlR = "rdm";
string vBefehlI = "items";
string eBefehl;                 //eingegebener Befehl
char Befehl;

cout << "------Willkommen GameMaster------" << endl <<endl;
cout << "Geben sie *help* ein, um eine Liste der verf\201gbaren Befehle auszugeben." << endl;
while(1)
{
    cin >> Befehl;              //wartet auf die eingabe eines Befehls

    if(eBefehl == vBefehlH)
    {
        Befehl = 'h';
    }

    if(eBefehl == vBefehlR)
    {
        Befehl = 'r';
    }

    switch(Befehl)
    {
        case 'h':       //gibt die Hilfe aus
        {
            cout << "help       -Gibt eine Liste aller verf\201gbaren Befehle im aktuellen Bereich aus." << endl;
            cout << "rdm        -Erstellt einen neuen Charakter." << endl;
            cout << "items      -Geht in den Item Bereich." << endl;

            break;
        }

        case 'r':
        {
            string Name;
            string Geschlecht;
            string Rasse;
            string Beruf;
            string Hautfarbe;
            string Haarfarbe;
            string Augenfarbe;

            cout << "Name: ";
            cin >> Name;            //cin muss aus irgendeinem Grund doppelt sein. Sonst wird es übersprungen.
            cin >> Name;
            cout << "Geschlecht: ";
            cin >> Geschlecht;
            cout << "Rasse: ";
            cin >> Rasse;
            cout << "Beruf: ";
            cin >> Beruf;
            cout << "Hautfarbe: ";
            cin >> Hautfarbe;
            cout << "Haarfarbe: ";
            cin >> Haarfarbe;
            cout << "Augenfarbe: ";
            cin >> Augenfarbe;

            Charakter Charakter1(Name, Geschlecht, Rasse, Beruf, Hautfarbe, Haarfarbe, Augenfarbe);

            Charakter1.Werte();
            Charakter1.grWerte();
            Charakter1.spWerte();
            Charakter1.SchreibCharakter();
            cout << endl << "Der Charakter wurde erfolgreich erstellt und befindet sich in *rdmCharakter.txt*" << endl;
            system ("pause");
            break;
        }
    }
}

return 0;

}

Now I dont think there is something wrong with the other sorce files in my Project but I'll just put them in down here just in case.

GameMaster.h

#ifndef GameMasterH
#define GameMasterH

using namespace std;

class Charakter
{
private:
                        //Die Grundinformationen, welche manuell eingegeben
werden
string Name;
string Geschlecht;
string Rasse;
string Beruf;
string Hautfarbe;
string Haarfarbe;
string Augenfarbe;
                        //Die Werte, welche durch RNG bestimmt werden
int Wert[9];
int spWert[58];         //Spezialwerte
int grWert[3];          //Alter/Größe/Gewicht

public:

//Konstruktor
Charakter(string, string, string, string, string, string, string);
//Destruktor
~Charakter();
//mothoden
void Werte();               //bestimmt die Grundwerte
void SchreibCharakter();    //Schreibt den Charakter
void spWerte();             //bestimmt die Spezialwerte
void grWerte();             //bestimmt Alter/Größe/Gewicht
};

Charakter.cpp

#include <iostream>
#include <conio.h>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include "GameMaster.h"

using namespace std;

//Konstruktor: Weist Die Grundinfos zu.
Charakter::Charakter(string N, string G, string R, string B, string HAU,     string HAA, string A)
{
Name = N;
Geschlecht = G;
Rasse = R;
Beruf = B;
Hautfarbe = HAU;
Haarfarbe = HAA;
Augenfarbe = A;
}

//Destruktor
Charakter::~Charakter()
{

}

void Charakter::Werte()                     //Weist die Grundwerte zu
{
srand(time(0));

for(int i = 1; i < 9; i++)
{
    Wert[i] = 8+(rand()%7);
}
}

void Charakter::grWerte()                   //Weist Alter, Größe und Gewicht zu
{
srand(time(0));

grWert[1] = 18+(rand()%43);
grWert[2] = 160+(rand()%41);
grWert[3] = 70+(rand()%41);
}

void Charakter::spWerte()                   //Weist Die spezifischen Werte zu
{
srand(time(0));

for(int i = 1; i < 58; i++)
{
    spWert[i] = (rand()%6);
}
}

void Charakter::SchreibCharakter()          //Schreibt die Textdatei
{
FILE* CharakterFile;

CharakterFile = fopen("rdmCharakter.txt", "w");

if(CharakterFile != NULL)
{
    fprintf(CharakterFile, "Name: %s \n", Name.c_str());
    fprintf(CharakterFile, "Geschlecht: %s \n", Geschlecht.c_str());
    fprintf(CharakterFile, "Rasse: %s \n", Rasse.c_str());
    fprintf(CharakterFile, "Beruf: %s \n", Beruf.c_str());
    fprintf(CharakterFile, "Alter: %d \n", grWert[1]);
    fprintf(CharakterFile, "Hautfarbe: %s \n", Hautfarbe.c_str());
    fprintf(CharakterFile, "Haarfarbe: %s \n", Haarfarbe.c_str());
    fprintf(CharakterFile, "Augenfarbe: %s \n", Augenfarbe.c_str());
    fprintf(CharakterFile, "Größe: %d \n", grWert[2]);
    fprintf(CharakterFile, "Gewicht: %d \n", grWert[3]);
    fprintf(CharakterFile, "Persönlichkeit: \n\n\n\n");

    fprintf(CharakterFile, "        Eigenschaften \n \n");
    fprintf(CharakterFile, "MU: %d \n", Wert[1]);
    fprintf(CharakterFile, "KL: %d \n", Wert[2]);
    fprintf(CharakterFile, "IN: %d \n", Wert[3]);
    fprintf(CharakterFile, "CH: %d \n", Wert[4]);
    fprintf(CharakterFile, "FF: %d \n", Wert[5]);
    fprintf(CharakterFile, "GE: %d \n", Wert[6]);
    fprintf(CharakterFile, "KO: %d \n", Wert[7]);
    fprintf(CharakterFile, "KK: %d \n\n\n", Wert[8]);

    fprintf(CharakterFile, "VORTEILE:           NACHTEILE:\n\n\n\n\n\n\n\n\n\n");

    fprintf(CharakterFile, "        HANDWERKSTALENTE\n\n");

    fprintf(CharakterFile, "ALCHEMIE        (KL/KL/IN): %d \n", spWert[1]);
    fprintf(CharakterFile, "HANDEL          (KL/IN/CH): %d \n", spWert[2]);
    fprintf(CharakterFile, "HEILKUNDE-GIFT      (MU/KL/IN): %d \n", spWert[3]);
    fprintf(CharakterFile, "HEILKUNDE-KRANK     (MU/KL/IN): %d \n", spWert[4]);
    fprintf(CharakterFile, "HEILKUNDE-SEELE     (KL/IN/CH): %d \n", spWert[5]);
    fprintf(CharakterFile, "HEILKUNDE-WUNDEN    (KL/FF/FF): %d \n", spWert[6]);
    fprintf(CharakterFile, "HOLZBEARBEITUNG     (KL/KK/FF): %d \n", spWert[7]);
    fprintf(CharakterFile, "LEDERBEARBEITUNG    (KL/FF/FF): %d \n", spWert[8]);
    fprintf(CharakterFile, "METALLBEARBEITUNG   (KL/FF/KK): %d \n", spWert[9]);
    fprintf(CharakterFile, "STEINBEARBEITUNG    (FF/FF/KK): %d \n", spWert[10]);
    fprintf(CharakterFile, "STOFFBEARBEITUNG    (KL/FF/FF): %d \n", spWert[11]);
    fprintf(CharakterFile, "KOCHEN&BACKEN       (KL/IN/FF): %d \n", spWert[12]);
    fprintf(CharakterFile, "SCHLÖSSERKNACKEN    (IN/FF/FF): %d \n", spWert[13]);
    fprintf(CharakterFile, "MALEN&ZEICHNEN      (KL/IN/FF): %d \n\n", spWert[14]);

    fprintf(CharakterFile, "        WISSENSTALENTE\n\n");

    fprintf(CharakterFile, "BRETT&GLÜCKSSPIEL   (KL/KL/IN): %d \n", spWert[15]);
    fprintf(CharakterFile, "GEOGRAPHIE      (KL/IN/IN): %d \n", spWert[16]);
    fprintf(CharakterFile, "GESCHICHTSWISSEN    (KL/KL/IN): %d \n", spWert[17]);
    fprintf(CharakterFile, "RELIGION        (KL/KL/CH): %d \n", spWert[18]);
    fprintf(CharakterFile, "MECHANIK        (KL/KL/FF): %d \n", spWert[19]);
    fprintf(CharakterFile, "RECHNEN         (KL/KL/KL): %d \n", spWert[20]);
    fprintf(CharakterFile, "SAGEN&LEGENDEN      (KL/KL/IN): %d \n", spWert[21]);
    fprintf(CharakterFile, "RECHTSKUNDE     (KL/IN/IN): %d \n", spWert[22]);
    fprintf(CharakterFile, "STRATEGIE       (KL/IN/IN): %d \n", spWert[23]);
    fprintf(CharakterFile, "MEDIZIN         (KL/KL/IN): %d \n", spWert[24]);
    fprintf(CharakterFile, "SEEFAHRT        (KL/IN/MU): %d \n\n", spWert[25]);

    fprintf(CharakterFile, "        NATURTALENTE\n\n");

    fprintf(CharakterFile, "FÄHRTENSUCHE        (KL/IN/IN): %d \n", spWert[26]);
    fprintf(CharakterFile, "FESSELN         (KL/FF/KK): %d \n", spWert[27]);
    fprintf(CharakterFile, "FISCHEN&ANGELN      (IN/FF/KO): %d \n", spWert[28]);
    fprintf(CharakterFile, "ORIENTIRUNG     (KL/IN/IN): %d \n", spWert[29]);
    fprintf(CharakterFile, "PFLANZENKUNDE       (KL/IN/FF): %d \n", spWert[30]);
    fprintf(CharakterFile, "TIERKUNDE       (MU/KL/IN): %d \n", spWert[31]);
    fprintf(CharakterFile, "WILDNISLEBEN        (IN/GE/KO): %d \n", spWert[32]);
    fprintf(CharakterFile, "JAGEN           (IN/KL/GE): %d \n", spWert[33]);
    fprintf(CharakterFile, "STERNKUNDE      (KL/KL/IN): %d \n\n", spWert[34]);

    fprintf(CharakterFile, "        KÖRPERTALENTE\n\n");

    fprintf(CharakterFile, "KLETTERN        (MU/GE/KK): %d \n", spWert[35]);
    fprintf(CharakterFile, "BALANCIEREN     (GE/GE/KO): %d \n", spWert[36]);
    fprintf(CharakterFile, "REITEN          (IN/GE/KO): %d \n", spWert[37]);
    fprintf(CharakterFile, "SCHWIMMEN       (GE/KO/KK): %d \n", spWert[38]);
    fprintf(CharakterFile, "SELBSTBEHERRSCHUNG  (MU/IN/KO): %d \n", spWert[39]);
    fprintf(CharakterFile, "SINGEN          (IN/CH/KL): %d \n", spWert[40]);
    fprintf(CharakterFile, "SINNESSCHÄRFE       (KL/IN/IN): %d \n", spWert[41]);
    fprintf(CharakterFile, "TANZEN          (CH/GE/GE): %d \n", spWert[42]);
    fprintf(CharakterFile, "TASCHENDIEBSTAHL    (MU/IN/FF): %d \n", spWert[43]);
    fprintf(CharakterFile, "VERBERGEN       (MU/IN/GE): %d \n", spWert[44]);
    fprintf(CharakterFile, "ZECHEN          (IN/KO/KK): %d \n", spWert[45]);
    fprintf(CharakterFile, "SCHLEICHEN      (GE/GE/KO): %d \n", spWert[46]);
    fprintf(CharakterFile, "MUSIKINSTRUMENTE    (KL/IN/KO): %d \n", spWert[47]);
    fprintf(CharakterFile, "REFLEXE         (GE/GE/FF): %d \n\n", spWert[48]);

    fprintf(CharakterFile, "        GESELLSCHAFTSTALENTE\n\n");

    fprintf(CharakterFile, "PREDIGEN        (MU/KL/IN): %d \n", spWert[49]);
    fprintf(CharakterFile, "ÜBERZEUGEN      (MU/IN/CH): %d \n", spWert[50]);
    fprintf(CharakterFile, "BETÖREN         (MU/CH/CH): %d \n", spWert[51]);
    fprintf(CharakterFile, "EINSCHÜCHTERN       (MU/KK/KK): %d \n", spWert[52]);
    fprintf(CharakterFile, "ETIKETTE        (KL/IN/CH): %d \n", spWert[53]);
    fprintf(CharakterFile, "GASSENWISSEN        (KL/IN/IN): %d \n", spWert[54]);
    fprintf(CharakterFile, "MENSCHENKENNTNIS    (KL/IN/CH): %d \n", spWert[55]);
    fprintf(CharakterFile, "ÜBERREDEN       (MU/KL/CH): %d \n", spWert[56]);
    fprintf(CharakterFile, "VERKLEIDEN      (IN/CH/GE): %d \n", spWert[57]);
    fprintf(CharakterFile, "WILLENSKRAFT        (MU/MU/IN): %d \n\n", spWert[58]);

    fprintf(CharakterFile, "        KAMPFTECHNIKEN\n\n");

    fprintf(CharakterFile, "ARMBRÜSTE       FF: \n");
    fprintf(CharakterFile, "BÖGEN           FF: \n");
    fprintf(CharakterFile, "MESSER          GE: \n");
    fprintf(CharakterFile, "HIEBWAFFEN      KK: \n");
    fprintf(CharakterFile, "KETTENWAFFEN        KK: \n");
    fprintf(CharakterFile, "RAUFEN          GE: \n");
    fprintf(CharakterFile, "SCHILDE         KK: \n");
    fprintf(CharakterFile, "SCHWERTER       KK: \n");
    fprintf(CharakterFile, "WURFWAFFEN      FF: \n");
    fprintf(CharakterFile, "SCHUSSWAFFEN L      FF: \n");
    fprintf(CharakterFile, "SCHUSSWAFFEN M      GE: \n");
    fprintf(CharakterFile, "SCHUSSWAFFEN S      KK: \n\n");

    fprintf(CharakterFile, "NAHKAMPFWAFFEN:\n\n\n\n\n\n");

    fprintf(CharakterFile, "FERNKAMPFWAFFEN:\n\n\n\n\n\n");

    fprintf(CharakterFile, "INVENTAR:\n\n\n\n\n\n");

    fclose(CharakterFile);
}
else
{
    cout << "Error: Die Datei kann nicht geoeffnet werden.";        //Gibt eine Fehlermeldung aus, falls die Text datei nicht geöffnet werden kann
}
}

Body:
This is not correct

grWert[3] = 70+(rand()%41);

your array is 3 is in size, but index is then 0-2, 3 will go past end of array.


问:
Running Tensorflow Classifier Model in C++/Obj-C++ results in different result than Python
Ive retrained an InceptionV3 model via the Tensorflow for Poets tutorials and can successfully run label_image.py on my trained data and on new data and get correct labels with good accuracy. Awesome!

If I run my model through my Mac Obj-C++ app my resulting labels are wildly different.

For example - my training is to classify which 'shot type' a frame of video is, (extreme close up, close up, medium, long, extreme long) for classifying video editing content.

label_image.py classifies a frame from a video as 85% likely close up.
My C++ / Obj-C App run with the same frame classifies it as Extreme Long with 60%

Both are running the same version of Tensorflow (1.1) on Mac OS X CPU compiled with AVX/SIMD/FMA optimizations.

My Apps pipeline :

I have a BGR ordered OpenCV Mat image which I can use successfully elsewhere and get sane results from. I create this CV Mat from an OS X CVPixelBufferRef mapped to a BGRA CV MAT like so:

```<code>cv::cvtColor(BGRAImage, frameMat, cv::COLOR_BGRA2BGR);
</code>```

I feed that BGR CV Mat (named frameMat) into a Tensor via code borrowed from the iOS contrib example, like so :

```<code> void* baseAddress = (void*)frameMat.datastart;
 size_t width = (size_t) frameMat.cols;
 size_t height = (size_t) frameMat.rows;
 size_t bytesPerRow =  (size_t) frameMat.cols * 3; // (BGR)

 const int wanted_input_width = 299;
 const int wanted_input_height = 299;
 const int wanted_input_channels = 3;
 const float input_mean = 128.0f;
 const float input_std = 128.0f;

 resized_tensor = tensorflow::Tensor( tensorflow::DT_FLOAT, tensorflow::TensorShape({1, wanted_input_height, wanted_input_width, wanted_input_channels}));

auto image_tensor_mapped = resized_tensor.tensor<float, 4>();
tensorflow::uint8 *in = sourceStartAddr;
float *out = image_tensor_mapped.data();
for (int y = 0; y < wanted_input_height; ++y)
{
    float *out_row = out + (y * wanted_input_width * wanted_input_channels);
    for (int x = 0; x < wanted_input_width; ++x)
    {
        const int in_x = (y * (int)width) / wanted_input_width;
        const int in_y = (x * image_height) / wanted_input_height;

        tensorflow::uint8 *in_pixel = in + (in_y * width * (image_channels)) + (in_x * (image_channels));
        float *out_pixel = out_row + (x * wanted_input_channels);

        // Interestingly the iOS example uses BGRA and DOES NOT re-order tensor channels to RGB <-> BGR
        // Matching that.
        out_pixel[0] = ((float)in_pixel[0] - (float)input_mean) / (float)input_std;
        out_pixel[1] = ((float)in_pixel[1] - (float)input_mean) / (float)input_std;
        out_pixel[2] = ((float)in_pixel[2] - (float)input_mean) / (float)input_std;
    }
}
</code>```

My session creation code:

```<code> tensorflow::Status load_graph_status = ReadBinaryProto(tensorflow::Env::Default(), [inception2015GraphPath cStringUsingEncoding:NSUTF8StringEncoding], &inceptionGraphDef);

 if (load_graph_status.ok())
 {
      tensorflow::SessionOptions options;
      inceptionSession = std::unique_ptr<tensorflow::Session>(tensorflow::NewSession(options));
      tensorflow::Status session_create_status = inceptionSession->Create(inceptionGraphDef);
 }
</code>```

Running the graph:

```<code>    tensorflow::Status run_status = inceptionSession->Run({ {input_layer, resized_tensor} }, {feature_layer, final_layer}, {}, &outputs);
</code>```

And pulling out the labels / feature vector (penultimate layer)

```<code>    NSMutableArray* outputLabels = [NSMutableArray arrayWithCapacity:self.labelsArray.count];
NSMutableArray* outputScores = [NSMutableArray arrayWithCapacity:self.labelsArray.count];

// 1 = labels and scores
auto predictions = outputs[1].flat<float>();

for (int index = 0; index < predictions.size(); index += 1)
{
    const float predictionValue = predictions(index);

    NSString* labelKey  = self.labelsArray[index % predictions.size()];

    NSNumber* currentLabelScore = self.averageLabelScores[labelKey];

    NSNumber* incrementedScore = @([currentLabelScore floatValue] + predictionValue );
    self.averageLabelScores[labelKey] = incrementedScore;

    [outputLabels addObject:labelKey];
    [outputScores addObject:@(predictionValue)];
}

// 0 is feature vector
tensorflow::Tensor feature = outputs[0];
int64_t numElements = feature.NumElements();
tensorflow::TTypes<float>::Flat featureVec = feature.flat<float>();

NSMutableArray* featureElements = [NSMutableArray arrayWithCapacity:numElements];

for(int i = 0; i < numElements; i++)
{
    [featureElements addObject:@( featureVec(i) ) ];
}

if(self.averageFeatureVec == nil)
{
    self.averageFeatureVec = featureElements;
}
else
{
    // average each vector element with the prior
    for(int i = 0; i < featureElements.count; i++)
    {
        float  a = [featureElements[i] floatValue];
        float  b = [self.averageFeatureVec[i] floatValue];

        self.averageFeatureVec[i] = @( MAX(a,b)) ;
    }
}

return @{ kSynopsisStandardMetadataFeatureVectorDictKey : featureElements ,
          @"Labels" : outputLabels,
          @"Scores" : outputScores,
          };
</code>```

I've attempted to look into the tensor ordering (NHWC), and have checked the tensor creation code but I might be missing something obvious to others. Ive also tried changing channel order, to no avail.

Any insight would be greatly helpful. Thank you!

答:
So this one is tricky.

I failed to mention I was running the graph_transform tool on my retrained graph - and was running quantize weights to lower my graphs size. In the past, I've not had an issue with this messing up classification scores at all, but apparently that caused an issue.

Running the above code with a graph transform call without quantize weights fixed the issue.

Body:
Ive retrained an InceptionV3 model via the Tensorflow for Poets tutorials and can successfully run label_image.py on my trained data and on new data and get correct labels with good accuracy. Awesome!

If I run my model through my Mac Obj-C++ app my resulting labels are wildly different.

For example - my training is to classify which 'shot type' a frame of video is, (extreme close up, close up, medium, long, extreme long) for classifying video editing content.

label_image.py classifies a frame from a video as 85% likely close up.
My C++ / Obj-C App run with the same frame classifies it as Extreme Long with 60%

Both are running the same version of Tensorflow (1.1) on Mac OS X CPU compiled with AVX/SIMD/FMA optimizations.

My Apps pipeline :

I have a BGR ordered OpenCV Mat image which I can use successfully elsewhere and get sane results from. I create this CV Mat from an OS X CVPixelBufferRef mapped to a BGRA CV MAT like so:

cv::cvtColor(BGRAImage, frameMat, cv::COLOR_BGRA2BGR);

I feed that BGR CV Mat (named frameMat) into a Tensor via code borrowed from the iOS contrib example, like so :

 void* baseAddress = (void*)frameMat.datastart;
 size_t width = (size_t) frameMat.cols;
 size_t height = (size_t) frameMat.rows;
 size_t bytesPerRow =  (size_t) frameMat.cols * 3; // (BGR)

 const int wanted_input_width = 299;
 const int wanted_input_height = 299;
 const int wanted_input_channels = 3;
 const float input_mean = 128.0f;
 const float input_std = 128.0f;

 resized_tensor = tensorflow::Tensor( tensorflow::DT_FLOAT, tensorflow::TensorShape({1, wanted_input_height, wanted_input_width, wanted_input_channels}));

auto image_tensor_mapped = resized_tensor.tensor<float, 4>();
tensorflow::uint8 *in = sourceStartAddr;
float *out = image_tensor_mapped.data();
for (int y = 0; y < wanted_input_height; ++y)
{
    float *out_row = out + (y * wanted_input_width * wanted_input_channels);
    for (int x = 0; x < wanted_input_width; ++x)
    {
        const int in_x = (y * (int)width) / wanted_input_width;
        const int in_y = (x * image_height) / wanted_input_height;

        tensorflow::uint8 *in_pixel = in + (in_y * width * (image_channels)) + (in_x * (image_channels));
        float *out_pixel = out_row + (x * wanted_input_channels);

        // Interestingly the iOS example uses BGRA and DOES NOT re-order tensor channels to RGB <-> BGR
        // Matching that.
        out_pixel[0] = ((float)in_pixel[0] - (float)input_mean) / (float)input_std;
        out_pixel[1] = ((float)in_pixel[1] - (float)input_mean) / (float)input_std;
        out_pixel[2] = ((float)in_pixel[2] - (float)input_mean) / (float)input_std;
    }
}

My session creation code:

 tensorflow::Status load_graph_status = ReadBinaryProto(tensorflow::Env::Default(), [inception2015GraphPath cStringUsingEncoding:NSUTF8StringEncoding], &inceptionGraphDef);

 if (load_graph_status.ok())
 {
      tensorflow::SessionOptions options;
      inceptionSession = std::unique_ptr<tensorflow::Session>(tensorflow::NewSession(options));
      tensorflow::Status session_create_status = inceptionSession->Create(inceptionGraphDef);
 }

Running the graph:

    tensorflow::Status run_status = inceptionSession->Run({ {input_layer, resized_tensor} }, {feature_layer, final_layer}, {}, &outputs);

And pulling out the labels / feature vector (penultimate layer)

    NSMutableArray* outputLabels = [NSMutableArray arrayWithCapacity:self.labelsArray.count];
NSMutableArray* outputScores = [NSMutableArray arrayWithCapacity:self.labelsArray.count];

// 1 = labels and scores
auto predictions = outputs[1].flat<float>();

for (int index = 0; index < predictions.size(); index += 1)
{
    const float predictionValue = predictions(index);

    NSString* labelKey  = self.labelsArray[index % predictions.size()];

    NSNumber* currentLabelScore = self.averageLabelScores[labelKey];

    NSNumber* incrementedScore = @([currentLabelScore floatValue] + predictionValue );
    self.averageLabelScores[labelKey] = incrementedScore;

    [outputLabels addObject:labelKey];
    [outputScores addObject:@(predictionValue)];
}

// 0 is feature vector
tensorflow::Tensor feature = outputs[0];
int64_t numElements = feature.NumElements();
tensorflow::TTypes<float>::Flat featureVec = feature.flat<float>();

NSMutableArray* featureElements = [NSMutableArray arrayWithCapacity:numElements];

for(int i = 0; i < numElements; i++)
{
    [featureElements addObject:@( featureVec(i) ) ];
}

if(self.averageFeatureVec == nil)
{
    self.averageFeatureVec = featureElements;
}
else
{
    // average each vector element with the prior
    for(int i = 0; i < featureElements.count; i++)
    {
        float  a = [featureElements[i] floatValue];
        float  b = [self.averageFeatureVec[i] floatValue];

        self.averageFeatureVec[i] = @( MAX(a,b)) ;
    }
}

return @{ kSynopsisStandardMetadataFeatureVectorDictKey : featureElements ,
          @"Labels" : outputLabels,
          @"Scores" : outputScores,
          };

I've attempted to look into the tensor ordering (NHWC), and have checked the tensor creation code but I might be missing something obvious to others. Ive also tried changing channel order, to no avail.

Any insight would be greatly helpful. Thank you!


问:
mongodb collection fetch information with criteria
I'm facing the following issue:

I have this data in a collection in mongoDB

```<code>   { Node: '2', Type: 'temperature', Value: '25.9', _id: 5936f90c81c543363d42f598 },
   { Node: '3', Type: 'temperature', Value: '31.0', _id: 5936f90c81c543363d42f599 },
   { Node: '1', Type: 'humidity', Value: '45.2', _id: 5936f90c81c543363d42f59a },
   { Node: '2', Type: 'humidity', Value: '55.3', _id: 5936f90c81c543363d42f59b }
</code>```

I want to fetch it by type.

Can't find what I'm doing wrong in my code...

```<code>var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  if (err) throw err;
  var collection = db.collection('readings');
  collection.find({}).toArray(function(err, result) {
    if (err) throw err;
    //console.log(result); //mostrar os resultados
    var numTemps = 0;
    result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });
    console.log("Temps: " + numTemps);
    console.log("Hums: " + numHums);
    db.close();
  });
});
</code>```

答:
I'm not sure what is going on there but it looks all wrong.  To get counts for the various types try this:</p>

```<code>db.readings.count({temperature: $exists: true}})
db.readings.count({humidity: $exists: true}})
</code>```

Body:
I'm facing the following issue:

I have this data in a collection in mongoDB

   { Node: '2', Type: 'temperature', Value: '25.9', _id: 5936f90c81c543363d42f598 },
   { Node: '3', Type: 'temperature', Value: '31.0', _id: 5936f90c81c543363d42f599 },
   { Node: '1', Type: 'humidity', Value: '45.2', _id: 5936f90c81c543363d42f59a },
   { Node: '2', Type: 'humidity', Value: '55.3', _id: 5936f90c81c543363d42f59b }

I want to fetch it by type.

Can't find what I'm doing wrong in my code...

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  if (err) throw err;
  var collection = db.collection('readings');
  collection.find({}).toArray(function(err, result) {
    if (err) throw err;
    //console.log(result); //mostrar os resultados
    var numTemps = 0;
    result.forEach(function(err,doc){
      if ("temperature" in result) {
        numTemps = numTemps + 1;
      };
    });
    var numHums = 0;
    result.forEach(function(err,doc){
      if ("humidity" in result) {
        numHums = numHums + 1;
      };
    });
    console.log("Temps: " + numTemps);
    console.log("Hums: " + numHums);
    db.close();
  });
});

Body:
I'm not sure what is going on there but it looks all wrong.  To get counts for the various types try this:

db.readings.count({temperature: $exists: true}})
db.readings.count({humidity: $exists: true}})


问:
Cut JS string present in an array at every occurrance of a particular substring and append to same array
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

```<code>var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
</code>```

What I need:

```<code>["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
</code>```

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

```<code>difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
</code>```

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

```<code>for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);
</code>```

答:
A functional single liner could be;

var array  = ["authentication.$.order", "difference.$.user.$.otherinformation"],
    result = array.reduce((r,s) => r.concat(s.split(".").reduce((p,c,i) => p.concat(i ? p[p.length-1] + "." + c : c), [])), []);
console.log(result);```

Body:
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]

What I need:

["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);


问:
How could I get CGContextRef from UIImage?
```<code>    CGContextRef context = ??; // get from UIImage *oldImage

    CGContextSaveGState(context);
    CGRect drawRect = CGRectMake(0, 0, 320, 480);
    CGContextConcatCTM(context, transform);
    UIImage *newImage = [[UIImage alloc] init];
    CGContextDrawImage(context, drawRect, newImage.CGImage);
    [newImage drawInRect:CGRectMake(0, 0, 320, 480)];

    CGContextRestoreGState(context);</code>```

In short, what I want to do is [ UIImage -> make some transform -> transformed UIImage].

Any ideas? Big thanks!!

答:
I think what you need is this:

```<code>UIGraphicsBeginImageContextWithOptions(newImageSize, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// drawing commands go here
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code>```

Note that UIGraphicsGetImageFromCurrentImageContext() returns an autoreleased UIImage instance.

ContentLicense: CC BY-SA 2.5

Body:
    CGContextRef context = ??; // get from UIImage *oldImage

    CGContextSaveGState(context);
    CGRect drawRect = CGRectMake(0, 0, 320, 480);
    CGContextConcatCTM(context, transform);
    UIImage *newImage = [[UIImage alloc] init];
    CGContextDrawImage(context, drawRect, newImage.CGImage);
    [newImage drawInRect:CGRectMake(0, 0, 320, 480)];

    CGContextRestoreGState(context);

In short, what I want to do is [ UIImage -> make some transform -> transformed UIImage].

Any ideas? Big thanks!!

Body:
I think what you need is this:

UIGraphicsBeginImageContextWithOptions(newImageSize, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// drawing commands go here
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Note that UIGraphicsGetImageFromCurrentImageContext() returns an autoreleased UIImage instance.


问:
Marker with label google map
i want to place a label below the marker (my marker is a circle). Now it is in the middle and it is not what I want, my code:

```<code>            var circle = new google.maps.Marker({
            position: circle,
            map: map,
            icon: '<?php echo get_stylesheet_directory_uri().'/images/circle.png'; ?>',
            label: "My city"
        });
</code>```

答:
Set the labelOrigin property of the Icon appropriately for your icon.

from the documentation:

labelOrigin   | Type:  Point

  The origin of the label relative to the top-left corner of the icon image, if a label is supplied by the marker. By default, the origin is located in the center point of the image.

Title: Marker with label google map

Body:
i want to place a label below the marker (my marker is a circle). Now it is in the middle and it is not what I want, my code:

            var circle = new google.maps.Marker({
            position: circle,
            map: map,
            icon: '<?php echo get_stylesheet_directory_uri().'/images/circle.png'; ?>',
            label: "My city"
        });


问:
Change jQuery depending on where user is on page
I'm trying to make a navigation where the background comes in after the user scrolls down. However, when the user is in the middle of the page, and refreshes, the background disappears and they need to scroll again for it to reappear. I'm trying to make it so whenever the user has scrolled past the header, the navigation background colour will be there no matter what.

Any help would be appreciated!

Code:

Jquery:

```<code>    $(document).ready(function(){
  var targetOffset = $('header').offset().top + $('header').height();

  var $w = $(window).scroll(function(){
      if ( $w.scrollTop() > targetOffset ) {
          $("#nav").css('background-color', 'rgba(35,46,63,1)');
      } else {
        $('#nav').css('background-color', 'rgba(35,46,63,0)');
      }
  });
});
</code>```

CSS:

```<code>nav {
    background-color: rgba(35,46,63,0);
    transition: background-color 200ms linear;
    position: fixed;
    left: 0;
    right: 0;
    padding: 25px;
    z-index: 1;
    box-shadow: 0px 0px 0px rgba(0,0,0,0);
}

nav > .wrapper {
    overflow: hidden;
}

nav > .wrapper > li.nav-logo {
    list-style: none;
    font-weight: 600;
    padding: 0px;
    border-top: 1px solid rgba(0,0,0,0);
}

nav > .wrapper > li.nav-logo > a {
    color: #DDDDDD;
    text-decoration: none;
}

nav > .wrapper > li.nav-logo > a > img.left {
    width: 5%;
    display: inline-block;
    float: left;
}

nav > .wrapper > ul.right {
    list-style: none;
    float: right;
}

nav > .wrapper > ul > li {
    display: inline-block;
    list-style: none;
    font-weight: 400;
    font-size: 0.9em;
    padding: 15px;
    border-bottom: 1px solid rgba(0,0,0,0);
    border-radius: 6px;
    vertical-align: middle;
    transition: all 0.3s ease;
}

nav > .wrapper > ul > li > a {
    color: #FFFFFF;
    text-decoration: none;
    transition: all .3s ease;
}

nav > .wrapper > ul > li > a:hover {
    color: white;
    text-decoration: none;
}
</code>```

HTML:

```<code><nav id="nav">
    <div class="wrapper">
        <li class="nav-logo"><a href="#"><img class="left" src="assets/images/ugn-logos/single-ugn-logo.png" alt="ugn-logo"></a></li>
        <span class="nav-btn"><i class="icon-menu"></i></span>
        <ul class="right">
            <li><a href="index.html">Home</a></li>
            <li><a href="shared-hosting.html">Shared Hosting</a></li>
            <li><a href="vps.html">VPS</a></li>
            <li><a href="minecraft.html">Minecraft</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </div>
</nav>
</code>```

答:
This is because $(window).scroll() will only activate once a scroll has occurred. The same script needs to happen on $(document).ready(). So you can create a function and call it on window resize and document ready.

```<code>$(document).ready(function(){
  function changeBG() {
    var targetOffset = $('header').offset().top + $('header').height();

    if ( $w.scrollTop() > targetOffset ) {
      $("#nav").css('background-color', 'rgba(35,46,63,1)');
    } else {
      $('#nav').css('background-color', 'rgba(35,46,63,0)');
    }
  }

  changeBG();

  $(window).scroll(changeBG);

});
</code>```

Body:
I'm trying to make a navigation where the background comes in after the user scrolls down. However, when the user is in the middle of the page, and refreshes, the background disappears and they need to scroll again for it to reappear. I'm trying to make it so whenever the user has scrolled past the header, the navigation background colour will be there no matter what.

Any help would be appreciated!

Code:

Jquery:

    $(document).ready(function(){
  var targetOffset = $('header').offset().top + $('header').height();

  var $w = $(window).scroll(function(){
      if ( $w.scrollTop() > targetOffset ) {
          $("#nav").css('background-color', 'rgba(35,46,63,1)');
      } else {
        $('#nav').css('background-color', 'rgba(35,46,63,0)');
      }
  });
});

CSS:

nav {
    background-color: rgba(35,46,63,0);
    transition: background-color 200ms linear;
    position: fixed;
    left: 0;
    right: 0;
    padding: 25px;
    z-index: 1;
    box-shadow: 0px 0px 0px rgba(0,0,0,0);
}

nav > .wrapper {
    overflow: hidden;
}

nav > .wrapper > li.nav-logo {
    list-style: none;
    font-weight: 600;
    padding: 0px;
    border-top: 1px solid rgba(0,0,0,0);
}

nav > .wrapper > li.nav-logo > a {
    color: #DDDDDD;
    text-decoration: none;
}

nav > .wrapper > li.nav-logo > a > img.left {
    width: 5%;
    display: inline-block;
    float: left;
}

nav > .wrapper > ul.right {
    list-style: none;
    float: right;
}

nav > .wrapper > ul > li {
    display: inline-block;
    list-style: none;
    font-weight: 400;
    font-size: 0.9em;
    padding: 15px;
    border-bottom: 1px solid rgba(0,0,0,0);
    border-radius: 6px;
    vertical-align: middle;
    transition: all 0.3s ease;
}

nav > .wrapper > ul > li > a {
    color: #FFFFFF;
    text-decoration: none;
    transition: all .3s ease;
}

nav > .wrapper > ul > li > a:hover {
    color: white;
    text-decoration: none;
}

HTML:

Home

Shared Hosting

VPS

Minecraft

Contact

Body:
This is because $(window).scroll() will only activate once a scroll has occurred. The same script needs to happen on $(document).ready(). So you can create a function and call it on window resize and document ready.

$(document).ready(function(){
  function changeBG() {
    var targetOffset = $('header').offset().top + $('header').height();

    if ( $w.scrollTop() > targetOffset ) {
      $("#nav").css('background-color', 'rgba(35,46,63,1)');
    } else {
      $('#nav').css('background-color', 'rgba(35,46,63,0)');
    }
  }

  changeBG();

  $(window).scroll(changeBG);

});


问:
Output once if both xml tags occur at the same time
If both xml tags exist I only want the output of the transform to occur once. Is that possible?

xsl

```<code><xsl:template match="latitude | longitude">
   <generate_once>for both tags below</generate_once>
</xsl:template>
</code>```

xml

```<code><doc>
<latitude /><longitude />
</doc>
</code>```

答:
Will this template do the trick...?

```<code><xsl:template match="latitude | longitude[not(../latitude)]">
   <generate_once>for both tags below</generate_once>
</xsl:template>
</code>```

This works by matching latitude if it exists (regardless of whether there is a longitude or not). It will only match longitude if there is no latitude though. So, in the case of both being present, only the latitude is matched.

Body:
If both xml tags exist I only want the output of the transform to occur once. Is that possible?

xsl

<xsl:template match="latitude | longitude">
   <generate_once>for both tags below</generate_once>
</xsl:template>

xml

<doc>
<latitude /><longitude />
</doc>

Body:
Will this template do the trick...?

<xsl:template match="latitude | longitude[not(../latitude)]">
   <generate_once>for both tags below</generate_once>
</xsl:template>

This works by matching latitude if it exists (regardless of whether there is a longitude or not). It will only match longitude if there is no latitude though. So, in the case of both being present, only the latitude is matched.


问:
What is a binary safe string?
What is a binary safe string ?  Is it just a string with length attached in the string itself ? Why are they called binary safe then ? Not sure that I should tag redis, but read this term while reading redis doc.</p>

答:
A binary safe string is one that can consist of any characters (bytes).

For example, many programming languages use the 0x00 character as an end-of-string marker, so in that sense a binary safe string is one that can consist of these.

Title: What is a binary safe string?


问:
Why is System.out.println so slow?
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

```<code>package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}
</code>```

答:
println is not slow, it's the underlying PrintStream that is connected with the console, provided by the hosting operating system.

You can check it yourself: compare dumping a large text file to the console with piping the same textfile into another file:

```<code>cat largeTextFile.txt
cat largeTextFile.txt > temp.txt
</code>```

Reading and writing are similiar and proportional to the size of the file (O(n)), the only difference is, that the destination is different (console compared to file). And that's basically the same with System.out.

The underlying OS operation (displaying chars on a console window) is slow because

The bytes have to be sent to the console application (should be quite fast)

Each char has to be rendered using (usually) a true type font (that's pretty slow, switching off anti aliasing could improve performance, btw)

The displayed area may have to be scrolled in order to append a new line to the visible area (best case: bit block transfer operation, worst case: re-rendering of the complete text area)

Title: Why is System.out.println so slow?

Body:
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}

Body:
println is not slow, it's the underlying PrintStream that is connected with the console, provided by the hosting operating system.

You can check it yourself: compare dumping a large text file to the console with piping the same textfile into another file:

cat largeTextFile.txt
cat largeTextFile.txt > temp.txt

Reading and writing are similiar and proportional to the size of the file (O(n)), the only difference is, that the destination is different (console compared to file). And that's basically the same with System.out.

The underlying OS operation (displaying chars on a console window) is slow because

The bytes have to be sent to the console application (should be quite fast)

Each char has to be rendered using (usually) a true type font (that's pretty slow, switching off anti aliasing could improve performance, btw)

The displayed area may have to be scrolled in order to append a new line to the visible area (best case: bit block transfer operation, worst case: re-rendering of the complete text area)


问:
Error when creating a NGINX reverse proxy on docker and sending a request to website in another container
I am currently trying to create a NGINX reverse proxy server using docker that will accept a request from the web to the proxy server, then redirect the request to a container with the website I want to be online. So i currently have 2 containers, one for the Nginx reverse proxy, and another that contains Nginx with LEMP and my website files. For some reason I am continuously getting a 502 Bad Gateway Error. I've tested the website container separately (directly connecting to the web rather than passing through the proxy) and the website properly showed. In addition I've used 'wget' to test for connectivity in the terminal, and the website container connects properly from everywhere, but when trying to access the Nginx proxy container using 'wget' it also displays a 502 Bad Gateway Error. I'm pretty new to web dev so I appreciate any help, as I might have just missed something simple.

Nginx Reverse Proxy Configuration file

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # include snippets/snakeoil.conf;

root /var/www/html;

index index.html index.php index.htm index.nginx-debian.html;

server_name 138.197.67.44;

location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_pass http://172.17.0.2:80;
    }
 }
</code>```

DockerFile for Reverse Proxy

```<code>#############################################################
#Dockerfile for creating and configuring a Nginx Reverse Proxy
#Based in Ubuntu 16.04
##############################################################

#Set base image as existing image with nginx configuration (one shown above)
FROM nginxproxyr

#FileName + Author
MAINTAINER NginxProxy Javier

# Update the repository sources lsit RUN apt-get update
#NOTE EVERYTHING IS ALREADY INSTALLED IN BASE IMAGE USED; just required to       configure the image

#EXPOSE AND ASSIGN PORTS

#Expose default port
EXPOSE 80

#Give access to the system to reach the script that runs the entrypoint
RUN chmod +x /usr/bin/startup.sh

#Default port to excecute entrypoint
CMD service nginx start
</code>```

Command to run a container from image created by Dockerfile

```<code>sudo docker run -it -p 80:80 -d NginxReverseProxy
</code>```

答:
When you have two containers I advise you to use docker-compose and make references through service not by ip. Now if you want to make a redirection you are advised to use this image which is quite simple to see how it works.

https://github.com/jwilder/nginx-proxy

Body:
I am currently trying to create a NGINX reverse proxy server using docker that will accept a request from the web to the proxy server, then redirect the request to a container with the website I want to be online. So i currently have 2 containers, one for the Nginx reverse proxy, and another that contains Nginx with LEMP and my website files. For some reason I am continuously getting a 502 Bad Gateway Error. I've tested the website container separately (directly connecting to the web rather than passing through the proxy) and the website properly showed. In addition I've used 'wget' to test for connectivity in the terminal, and the website container connects properly from everywhere, but when trying to access the Nginx proxy container using 'wget' it also displays a 502 Bad Gateway Error. I'm pretty new to web dev so I appreciate any help, as I might have just missed something simple.

Nginx Reverse Proxy Configuration file

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # include snippets/snakeoil.conf;

root /var/www/html;

index index.html index.php index.htm index.nginx-debian.html;

server_name 138.197.67.44;

location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_pass http://172.17.0.2:80;
    }
 }

DockerFile for Reverse Proxy

#############################################################
#Dockerfile for creating and configuring a Nginx Reverse Proxy
#Based in Ubuntu 16.04
##############################################################

#Set base image as existing image with nginx configuration (one shown above)
FROM nginxproxyr

#FileName + Author
MAINTAINER NginxProxy Javier

# Update the repository sources lsit RUN apt-get update
#NOTE EVERYTHING IS ALREADY INSTALLED IN BASE IMAGE USED; just required to       configure the image

#EXPOSE AND ASSIGN PORTS

#Expose default port
EXPOSE 80

#Give access to the system to reach the script that runs the entrypoint
RUN chmod +x /usr/bin/startup.sh

#Default port to excecute entrypoint
CMD service nginx start

Command to run a container from image created by Dockerfile

sudo docker run -it -p 80:80 -d NginxReverseProxy