问:
How can I get node.js to return data once all operations are complete
I am just learning server-side JavaScript so please bear with any glaring mistakes I've made.

I am trying to write a file parser that operates on HTML files in a directory and returns a JSON string once all files have been parsed. I started it with a single file and it works fine. it loads the resource from Apache running on the same machine, injects jquery, does the parsing and returns my JSON.

```<code>var request = require('request'),
    jsdom = require('jsdom'),
    sys = require('sys'),
    http = require('http');

http.createServer(function (req, res) {
    request({uri:'http://localhost/tfrohe/Car3E.html'}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var window = jsdom.jsdom(body).createWindow();
            jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
              // jQuery is now loaded on the jsdom window created from 'body'
                var emps = {};
                jquery("tr td img").parent().parent().each(function(){
                    var step = 0;
                    jquery(this).children().each(function(index){
                        if (jquery(this).children('img').attr('src') !== undefined) {
                            step++;
                            var name = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                            var name_parts = name.split(",");
                            var last = name_parts[0];
                            var name_parts = name_parts[1].split(/\u00a0/g);
                            var first = name_parts[2];
                            emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                        }
                    });
                });
                emps = JSON.stringify(emps);
                //console.log(emps);
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end(emps);

            });
        } else {
            res.writeHead(200, {"Content-Type": "text/plain"});
            res.end("empty");
            //console.log(response.statusCode);
        }
    });
}).listen(8124);
</code>```

Now I am trying to extend this to using the regular file system (fs) and get all HTML files in the directory and parse them the same way and return a single combined JSON object once all files have been parsed. Here is what I have so far but it does not work.

```<code>var sys = require("sys"),
    fs = require("fs"),
    jsdom = require("jsdom"),
    emps = {};
    //path = '/home/inet/www/media/employees/';

readDirectory = function(path) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step++;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                });
            });
        });
    });
}

readDirectory('/home/inet/www/media/employees/', function() {
    console.log(emps);
});
</code>```

In this particular case, there are 2 html files in the directory. If i console.log(emps) during the htmlfiles.forEach() it shows me the results from the first file then the results for both files together the way I expect. how do I get emps to be returned to readDirectory so i can output it as desired?

Completed Script

After the answers below, here is the completed script with a httpServer to serve up the detail.

```<code>var sys = require('sys'),
    fs = require("fs"),
    http = require('http'),
    jsdom = require('jsdom'),
    emps = {};

    var timed = setInterval(function() {
        emps = {};
        readDirectory('/home/inet/www/media/employees/', function(emps) {
        });
    }, 3600000);

readDirectory = function(path, callback) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    var imagecount = jquery("tr td img").length;
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step += 1;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                    count -= 1;
                    if (count <= 0) {
                        callback(JSON.stringify(emps));
                    }
                });
            });

        });
    });
}

var init = readDirectory('/home/inet/www/media/employees/', function(emps) {

        });

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(emps));
}).listen(8124);
</code>```

答:
That sure is a lot of code a couple of mistakes.

You're never calling the callback function you supply to readDirectory

You need to keep track of the files you have parsed, when you parsed all of them, call the callback and supply the emps

This should work:

```<code>var sys = require("sys"),
    fs = require("fs"),
    jsdom = require("jsdom"),
    //path = '/home/inet/www/media/employees/';

// This is a nicer way
function readDirectory(path, callback) {
    fs.readdir(path, function(err, files) {

        // make this local
        var emps = {};
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });

        // Keep track of the number of files we have parsed
        var count = htmlfiles.length;
        var done = 0;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step++;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                    // As soon as all have finished call the callback and supply emps
                    done++;
                    if (done === count) {
                        callback(emps);
                    }
                });
            });
        });
    });
}

readDirectory('/home/inet/www/media/employees/', function(emps) {
    console.log(emps);
});
</code>```

Body:
I am just learning server-side JavaScript so please bear with any glaring mistakes I've made.

I am trying to write a file parser that operates on HTML files in a directory and returns a JSON string once all files have been parsed. I started it with a single file and it works fine. it loads the resource from Apache running on the same machine, injects jquery, does the parsing and returns my JSON.

var request = require('request'),
    jsdom = require('jsdom'),
    sys = require('sys'),
    http = require('http');

http.createServer(function (req, res) {
    request({uri:'http://localhost/tfrohe/Car3E.html'}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var window = jsdom.jsdom(body).createWindow();
            jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
              // jQuery is now loaded on the jsdom window created from 'body'
                var emps = {};
                jquery("tr td img").parent().parent().each(function(){
                    var step = 0;
                    jquery(this).children().each(function(index){
                        if (jquery(this).children('img').attr('src') !== undefined) {
                            step++;
                            var name = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                            var name_parts = name.split(",");
                            var last = name_parts[0];
                            var name_parts = name_parts[1].split(/\u00a0/g);
                            var first = name_parts[2];
                            emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                        }
                    });
                });
                emps = JSON.stringify(emps);
                //console.log(emps);
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end(emps);

            });
        } else {
            res.writeHead(200, {"Content-Type": "text/plain"});
            res.end("empty");
            //console.log(response.statusCode);
        }
    });
}).listen(8124);

Now I am trying to extend this to using the regular file system (fs) and get all HTML files in the directory and parse them the same way and return a single combined JSON object once all files have been parsed. Here is what I have so far but it does not work.

var sys = require("sys"),
    fs = require("fs"),
    jsdom = require("jsdom"),
    emps = {};
    //path = '/home/inet/www/media/employees/';

readDirectory = function(path) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step++;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                });
            });
        });
    });
}

readDirectory('/home/inet/www/media/employees/', function() {
    console.log(emps);
});

In this particular case, there are 2 html files in the directory. If i console.log(emps) during the htmlfiles.forEach() it shows me the results from the first file then the results for both files together the way I expect. how do I get emps to be returned to readDirectory so i can output it as desired?

Completed Script

After the answers below, here is the completed script with a httpServer to serve up the detail.

var sys = require('sys'),
    fs = require("fs"),
    http = require('http'),
    jsdom = require('jsdom'),
    emps = {};

    var timed = setInterval(function() {
        emps = {};
        readDirectory('/home/inet/www/media/employees/', function(emps) {
        });
    }, 3600000);

readDirectory = function(path, callback) {
    fs.readdir(path, function(err, files) {
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });
        var count = htmlfiles.length;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    var imagecount = jquery("tr td img").length;
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step += 1;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                    count -= 1;
                    if (count <= 0) {
                        callback(JSON.stringify(emps));
                    }
                });
            });

        });
    });
}

var init = readDirectory('/home/inet/www/media/employees/', function(emps) {

        });

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(emps));
}).listen(8124);

Body:
That sure is a lot of code a couple of mistakes.

You're never calling the callback function you supply to readDirectory

You need to keep track of the files you have parsed, when you parsed all of them, call the callback and supply the emps

This should work:

var sys = require("sys"),
    fs = require("fs"),
    jsdom = require("jsdom"),
    //path = '/home/inet/www/media/employees/';

// This is a nicer way
function readDirectory(path, callback) {
    fs.readdir(path, function(err, files) {

        // make this local
        var emps = {};
        var htmlfiles = [];
        files.forEach(function(name) {
            if(name.substr(-4) === "html") {
                htmlfiles.push(name);
            }
        });

        // Keep track of the number of files we have parsed
        var count = htmlfiles.length;
        var done = 0;
        htmlfiles.forEach(function(filename) {
            fs.readFile(path + filename, "binary", function(err, data) {
                if(err) throw err;
                window = jsdom.jsdom(data).createWindow();
                jsdom.jQueryify(window, 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function (window, jquery) {
                    jquery("tr td img").parent().parent().each(function(){
                        var step = 0;
                        jquery(this).children().each(function(index){
                            if (jquery(this).children('img').attr('src') !== undefined) {
                                step++;
                                var empname = jquery(this).parent().next().next().children('td:nth-child('+step+')').children().children().text();
                                var name_parts = empname.split(",");
                                var last = name_parts[0];
                                var name_parts = name_parts[1].split(/\u00a0/g);
                                var first = name_parts[2]
                                emps[last + ",_" + first] = jquery(this).children('img').attr('src');
                            }
                        });
                    });
                    // As soon as all have finished call the callback and supply emps
                    done++;
                    if (done === count) {
                        callback(emps);
                    }
                });
            });
        });
    });
}

readDirectory('/home/inet/www/media/employees/', function(emps) {
    console.log(emps);
});


来源: stackexchange

问:
Map table names of a database with values in another table
I have some table names in test database in MySQL. I have a table called mapping in database renamed that has information of tables that have been renamed.

Now I want to have a list of the tables that are in test database and their renamed name in the mapping table.

Tables in test

```<code>123_abc
124_abc
235_test
</code>```

Information in mapping table

```<code>table       renamed

123_abc     123_abc_test
235_test    235_testing
abc_test    abc_test1
</code>```

Now I want a list that contains table names that are in test database and their renamed names in the mapping table in renamed database

The expected result is

```<code>123_abc     123_abc_test
235_test    235_testing
</code>```

How can I achieve that?

答:
You could use the information_schema database that's part of MySQL and which contains all of MySQL's meta-information (including table names) like this:

```<code>select t1.TABLE_NAME, t2.table_name
from information_schema.`TABLES` t1
where table_schema = 'test'
inner join renamed.mapping t2 on
    t1.table_name = t2.table_name
</code>```

Granted, with an inner join, you'll only get the tables that are actually renamed. If you want all the tables in your test schema, do a left join instead.

ContentLicense: CC BY-SA 3.0

Body:
I have some table names in test database in MySQL. I have a table called mapping in database renamed that has information of tables that have been renamed.

Now I want to have a list of the tables that are in test database and their renamed name in the mapping table.

Tables in test

123_abc
124_abc
235_test

Information in mapping table

table       renamed

123_abc     123_abc_test
235_test    235_testing
abc_test    abc_test1

Now I want a list that contains table names that are in test database and their renamed names in the mapping table in renamed database

The expected result is

123_abc     123_abc_test
235_test    235_testing

How can I achieve that?

Body:
You could use the information_schema database that's part of MySQL and which contains all of MySQL's meta-information (including table names) like this:

select t1.TABLE_NAME, t2.table_name
from information_schema.`TABLES` t1
where table_schema = 'test'
inner join renamed.mapping t2 on
    t1.table_name = t2.table_name

Granted, with an inner join, you'll only get the tables that are actually renamed. If you want all the tables in your test schema, do a left join instead.


问:
Remove objects from array of objects swift
I have an issue and need your help.
I have array of objects

```<code>var arrayDirection: [Directions]
</code>```

every object has properties:

```<code>var name: String?
var uniqueId: Int?
</code>```

I need find and leave only one object whose values of properties duplicate values of properties of another objects from that array.

For example I print in console:

```<code>for object in arrayDirection {
    print(object.name, object.uniqueId)
}
</code>```

and see:

Optional("name1") Optional(833)

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name4") Optional(833)

Optional("name1") Optional(833)

Optional("name1") Optional(862)

So, I need remove Optional("name1") Optional(833) because there are 3 in array and leave only one as result I'd like to see:

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name3") Optional(833)

Optional("name1") Optional(862)

答:
You could reduce the array:

```<code>let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0.uniqueId == direction.uniqueId }) ? result : result + [direction]
}
</code>```

Obviously this piece of code assumes that you only want to check if the IDs duplicate, if you want to check whether whole objects duplicate you could either implement the Equatable protocol for your Directions type, or do it like that:

```<code>let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0.uniqueId == direction.uniqueId && $0.name == direction.name }) ? result : result + [direction]
}
</code>```

And with Equatable protocol implemented it gets actually really simple:

```<code>let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0 == direction }) ? result : result + [direction]
}
</code>```

Body:
I have an issue and need your help.
I have array of objects

var arrayDirection: [Directions]

every object has properties:

var name: String?
var uniqueId: Int?

I need find and leave only one object whose values of properties duplicate values of properties of another objects from that array.

For example I print in console:

for object in arrayDirection {
    print(object.name, object.uniqueId)
}

and see:

Optional("name1") Optional(833)

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name4") Optional(833)

Optional("name1") Optional(833)

Optional("name1") Optional(862)

So, I need remove Optional("name1") Optional(833) because there are 3 in array and leave only one as result I'd like to see:

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name3") Optional(833)

Optional("name1") Optional(862)

Body:
You could reduce the array:

let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0.uniqueId == direction.uniqueId }) ? result : result + [direction]
}

Obviously this piece of code assumes that you only want to check if the IDs duplicate, if you want to check whether whole objects duplicate you could either implement the Equatable protocol for your Directions type, or do it like that:

let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0.uniqueId == direction.uniqueId && $0.name == direction.name }) ? result : result + [direction]
}

And with Equatable protocol implemented it gets actually really simple:

let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0 == direction }) ? result : result + [direction]
}


问:
JPEG corrupted after sending via HTTP
I'm trying to build a simple HTTP Java server from scratch.
Right now I am trying to get my browser to download a .jpg-file on my PC,
that's why
The foimage/jpeg is hardcoded into the method. The following is the method printing the HTTP-response to my browser. desiredFile a .jpg file called "Image.jpg" stored on my Computer.

Everything works great and my broser downloads the file, but I cannot open it. The Windows Image Program just tells me that it's "probably damaged". When I view the image's details I can see that it has the same byte-size, but details such as resolution are lost.  `

```<code>        byte[] bytes = Files.readAllBytes(desiredFile.toPath());

        System.out.println("Attempting to print to client|" + bytes.length

        output.write("HTTP/1.1 200 OK" + "\r\n"
                        + "Content-type: image/jpeg" + "\r\n"
                        + "Content-length: " + bytes.length + "\r\n"
                        + "Content-Disposition: attachment; filename=Imae.jpg" + "\r\n"
                        + "\r\n");

        for (byte currentByte : bytes)
            output.write(currentByte);

        output.flush();
        output.close();

        System.out.println("Printing finished.");
        `
</code>```

Is there something wrong with the way I am transmitting the bytes? Sending bytesas a whole array did not work, that is why I am sending every byte after the other.

Thanks!

答:
The problem is that you're using an OutputWriter.

Your bytes will be interpreted as characters, which in turn are encoded as different bytes. For example, with UTF-8, sending the byte 0x80 will result in the two bytes 0xC2 0x80. This trashes the image.

The fact that you weren't able to send the full array directly is a huge red flag: this should obviously work. If it doesn't, you should find out why. The error message probably mentioned that it expected char[] instead of byte[], indicating that your source is character based instead of byte based.

To fix it, switch to a PrintStream. It allows you to both output String for the header and byte[] for the body.

Title: JPEG corrupted after sending via HTTP

Body:
I'm trying to build a simple HTTP Java server from scratch.
Right now I am trying to get my browser to download a .jpg-file on my PC,
that's why
The foimage/jpeg is hardcoded into the method. The following is the method printing the HTTP-response to my browser. desiredFile a .jpg file called "Image.jpg" stored on my Computer.

Everything works great and my broser downloads the file, but I cannot open it. The Windows Image Program just tells me that it's "probably damaged". When I view the image's details I can see that it has the same byte-size, but details such as resolution are lost.  `

        byte[] bytes = Files.readAllBytes(desiredFile.toPath());

        System.out.println("Attempting to print to client|" + bytes.length

        output.write("HTTP/1.1 200 OK" + "\r\n"
                        + "Content-type: image/jpeg" + "\r\n"
                        + "Content-length: " + bytes.length + "\r\n"
                        + "Content-Disposition: attachment; filename=Imae.jpg" + "\r\n"
                        + "\r\n");

        for (byte currentByte : bytes)
            output.write(currentByte);

        output.flush();
        output.close();

        System.out.println("Printing finished.");
        `

Is there something wrong with the way I am transmitting the bytes? Sending bytesas a whole array did not work, that is why I am sending every byte after the other.

Thanks!


问:
AsyncTask threads never die
I'm using AsyncTasks to fetch data in response to the user pressing a button. This works well and keeps the interface responsive while fetching the data, but when I checked out what was going on in the Eclipse debugger, I found out that every time a new AsyncTask was created (which is quite often, because they can only be used once), a new thread was being created but never terminated.

The result is a large number of AsyncTask threads just sitting there. I'm not sure if this is a problem in practice or not, but I'd really like to get rid of those extra threads.

How can I kill these threads?

答:
In addition to CommonsWare's response:

Currently I'm using Android 2.2, and my application uses no more than one AsyncTask at any time, but I'm creating a new one every x minutes. At first new AsyncTask Threads start to appear (a new Thread for a new AsyncTask) but after 5 threads (as mentioned by CommonsWare) they just stay visible in the debug window, and get re-used when new AsyncTask threads are needed. They just stay there until the debugger disconnects.

Title: AsyncTask threads never die

ContentLicense: CC BY-SA 2.5


问:
Where to start with teaching an AI to play SNES games?
I have had an infatuation with a certain concept regarding machine learning that Sethbling proved with his Mar.io program: https://youtu.be/qv6UVOQ0F44

I have a decent amount of logical programming experience in a number of different languages and have read around a lot about machine learning and neural networking.

What I'm looking for is a good set of references that could teach me how to apply neural networks in code, rather than just as a mathematical teaching like most of what I have seen thus far.

Thanks in advance!

答:
You might want to check out the JavaScript library Neataptic to check out how they implemented neural networks in Agar.IO for example.

You might also want to check out the NeuroEvolution of Augmenting Topologies paper for a basic understanding of neuro-evolution.


问:
What is $model in Yii2?
I'm new to MVC and Yii Framework. The $model variable seems very confusing to me.

Where is it declared in the fist place? Where does it come from?

When I work with GridView I see that some functions take $model as a parameter. Neither model nor model search of this GridView declares $model variable anywhere. Yet it is widely used in all sorts of data management. It just doesn't make sense to me.

So I need a simple, straight forward, "for dummies" explanation of $model variable in Yii Framework v2. Help in clarifying these questions is much appreciated:
1. What is the origin of $model variable?
2. How to identify what model of the app is the $model variable representing when it's used in view files?
3. There are sometimes multiple $model variables in a single view file. Do all of them represent one model class? How to distinguish them when used for multiple classes?

Thanks.

答:
If you are unsure where $model, $searchModel and other variables come from, you are most likely searching for them on the view file where they are used.

They are created on the controller that renders said view, just like any other object/variable.

From the controller, you can render a view and pass objects/variables the following way:

```<code>// MyController.php
...
public function actionMyAction($id) {
    // Create and manipulate $model and $searchModel
    ...
    /*
     * First param is the name of the view to be rendered
     * Second param is an Associative Array with params
     * that will be made available to the view.
     */
    return $this->render('my-view-name', [
        'model' => $model,
        'searchModel' => $searchModel,
    ]);
}
</code>```

Title: What is $model in Yii2?

Body:
If you are unsure where $model, $searchModel and other variables come from, you are most likely searching for them on the view file where they are used.

They are created on the controller that renders said view, just like any other object/variable.

From the controller, you can render a view and pass objects/variables the following way:

// MyController.php
...
public function actionMyAction($id) {
    // Create and manipulate $model and $searchModel
    ...
    /*
     * First param is the name of the view to be rendered
     * Second param is an Associative Array with params
     * that will be made available to the view.
     */
    return $this->render('my-view-name', [
        'model' => $model,
        'searchModel' => $searchModel,
    ]);
}


答:
You can issue a MySQL statement like,

select * from renamed.mapping inner join information_schema.tables on renamed.mapping.table_name = information_schema.tables.TABLE_NAME where information_schema.tables.TABLE_SCHEMA='test'

Title: Map table names of a database with values in another table


问:
AWS: How is CPU utilization calculated for auto scaling group
I created an Auto Scaling group, with an Application Load Balancer attached, with a policy that when CPU utilization rate is greater than 75% add one more instance. It seems working.

When I have four instances running, how is that CPU Utilization rate calculated? Average of the four instances? Minimum among the four?

答:
You created an Auto Scaling Policy and that policy executes when the alarm you had configured is triggered.

You can see Average selected in the dropdown list. Various option that can be selected are Average, Minimum, Maximum, Sum and SampleCount.

You can also refer to Scaling Based on Metrics.


问:
residual network cell content reference error on matconvnet
I am using mathconvnet 1.0 beta24. I can install and compile the toolbox correctly. When I follow the quickstart on the website(http://www.vlfeat.org/matconvnet/quick/);
I start with;

```<code>untar('http://www.vlfeat.org/matconvnet/download/matconvnet-1.0-beta24.tar.gz') ;
cd matconvnet-1.0-beta24
run matlab/vl_compilenn ;
</code>```

After that instead of imagenet-vgg-f model I want to use one of the resnet models so I continue with;

```<code>urlwrite(...
  'http://www.vlfeat.org/matconvnet/models/imagenet-resnet-50-dag.mat', ...
  'imagenet-resnet-50-dag.mat') ;
run matlab/vl_setupnn ;
net = load('imagenet-resnet-50-dag.mat') ;
</code>```

It works fine up to this part, but when I run the following command;

```<code>net = vl_simplenn_tidy(net) ;
</code>```

I get the following error;

Cell contents reference from a non-cell array object.

```<code>Error in vl_simplenn_tidy (line 47)
layer = net.layers{l} ;
</code>```

imagenet-vgg-f model works fine but when I try to use the resnet model I get the error. I don't know how to solve this issue. This is very important for me as I am a novice at topic.

Any ideas are appreciated

Thanks in advance

答: If I remember correctly, ResNet uses DAGNN (i.e., the network is a directed acyclic graph). VGG is simplenn. So you can't use vl_simplenn_tidy for ResNet. The error is caused by accessing net.layers using {}. In DAGNN, you can only access layers by (), since it is a matlab struct array, instead of a cell array. That said, there are other differences between dagNN and simplenn. So you can't use vl_simplenn_tidy() on dagNN.</p>

Body:
I am using mathconvnet 1.0 beta24. I can install and compile the toolbox correctly. When I follow the quickstart on the website(http://www.vlfeat.org/matconvnet/quick/);
I start with;

untar('http://www.vlfeat.org/matconvnet/download/matconvnet-1.0-beta24.tar.gz') ;
cd matconvnet-1.0-beta24
run matlab/vl_compilenn ;

After that instead of imagenet-vgg-f model I want to use one of the resnet models so I continue with;

urlwrite(...
  'http://www.vlfeat.org/matconvnet/models/imagenet-resnet-50-dag.mat', ...
  'imagenet-resnet-50-dag.mat') ;
run matlab/vl_setupnn ;
net = load('imagenet-resnet-50-dag.mat') ;

It works fine up to this part, but when I run the following command;

net = vl_simplenn_tidy(net) ;

I get the following error;

Cell contents reference from a non-cell array object.

Error in vl_simplenn_tidy (line 47)
layer = net.layers{l} ;

imagenet-vgg-f model works fine but when I try to use the resnet model I get the error. I don't know how to solve this issue. This is very important for me as I am a novice at topic.

Any ideas are appreciated

Thanks in advance


问:
Automapper doesn't fill destination object
I use Automapper with CreateMissingTypeMaps option set to true. If I try to fill an existing object of the same type, it doesn't work.

```<code>class A
{
    public string X { get; set; }
}

var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();
var a1 = new A { X = "sample" };
var a2 = new A();
mapper.Map(a1, a2); // a2.X was not set
</code>```

If I create a new object of the same type, it works fine

```<code>var a3 = mapper.Map<A>(a1); // a3.X is set
</code>```

If I fill an existing object of a different type, it also works

```<code>class B
{
    public string X { get; set; }
}

var b = new B();
mapper.Map(a1, b); // b.X is set
</code>```

But if I try to fill an existing object of the same type, it doesn't. Is it a bug in Automapper or am I missing something?

答:
For some reasons, this is an expected behaviour https://github.com/AutoMapper/AutoMapper/issues/2129. CreateMissingTypeMaps is not supported for mapping to the same type. The only way to get it work is to configure the mapping explicitly:

```<code>var config = new MapperConfiguration(cfg => cfg.CreateMap<A, A>());
</code>```

Body:
I use Automapper with CreateMissingTypeMaps option set to true. If I try to fill an existing object of the same type, it doesn't work.

class A
{
    public string X { get; set; }
}

var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();
var a1 = new A { X = "sample" };
var a2 = new A();
mapper.Map(a1, a2); // a2.X was not set

If I create a new object of the same type, it works fine

var a3 = mapper.Map(a1); // a3.X is set

If I fill an existing object of a different type, it also works

class B
{
    public string X { get; set; }
}

var b = new B();
mapper.Map(a1, b); // b.X is set

But if I try to fill an existing object of the same type, it doesn't. Is it a bug in Automapper or am I missing something?

Body:
For some reasons, this is an expected behaviour https://github.com/AutoMapper/AutoMapper/issues/2129. CreateMissingTypeMaps is not supported for mapping to the same type. The only way to get it work is to configure the mapping explicitly:

var config = new MapperConfiguration(cfg => cfg.CreateMap<A, A>());


问:
Code 503 in Flask with Embedded Bokeh Server App fetching jsonified data through requests.get()
I'm in the process of parameterizing my bokeh apps by having my Flask app expose model data via a route dedicated to jsonifying the requested data passed via query string arguments. I know the data sending route works since when I use it as a url to AjaxDataSource I get the expected data plotted. However when I attempt the equivalent operation using the requests.get api I get a 503 response code which makes me think I'm violating something fundamental here I can't quite grasp with my limited webdev experience. What am I doing wrong and or violating?

I actually need a bit more data retrieving flexibility than the AjaxDataSource provides with its columnar limitations. I was hoping to lean on the requests module to pass arbitrary class instances and what not around by serializing and deserializing Json.

Here's the minimal example I have demonstrating the failure derived from  flask_embed.html...

```<code>import requests
from flask import Flask, jsonify, render_template
import pandas
from tornado.ioloop import IOLoop

from bokeh.application          import Application
from bokeh.application.handlers import FunctionHandler
from bokeh.embed                import server_document
from bokeh.layouts              import column
from bokeh.models               import AjaxDataSource,ColumnDataSource
from bokeh.plotting             import figure
from bokeh.server.server        import Server

flask_app = Flask(__name__)

# Populate some model maintained by the flask application
modelDf = pandas.DataFrame()
nData = 100
modelDf[ 'c1_x' ] = range(nData)
modelDf[ 'c1_y' ] = [ x*x for x in range(nData) ]
modelDf[ 'c2_x' ] = range(nData)
modelDf[ 'c2_y' ] = [ 2*x for x in range(nData) ]

def modify_doc1(doc):
    # get colum name from query string
    args      = doc.session_context.request.arguments
    paramName = str( args['colName'][0].decode('utf-8') )

    # get model data from Flask
    url    = "http://localhost:8080/sendModelData/%s" % paramName
    source = AjaxDataSource( data             = dict( x=[] , y=[] ) ,
                            data_url         = url       ,
                            polling_interval = 5000      ,
                            mode             = 'replace' ,
                            method           = 'GET'     )
    # plot the model data
    plot = figure( )
    plot.circle( 'x' , 'y' , source=source , size=2 )
    doc.add_root(column(plot))

def modify_doc2(doc):
    # get column name from query string
    args    = doc.session_context.request.arguments
    colName = str( args['colName'][0].decode('utf-8') )

    # get model data from Flask
    url = "http://localhost:8080/sendModelData/%s" % colName
    #pdb.set_trace()
    res = requests.get( url , timeout=None , verify=False )
    print( "CODE %s" % res.status_code )
    print( "ENCODING %s" % res.encoding )
    print( "TEXT %s" % res.text )
    data = res.json()

    # plot the model data
    plot = figure()
    plot.circle( 'x' , 'y' , source=data , size=2 )
    doc.add_root(column(plot))

bokeh_app1 = Application(FunctionHandler(modify_doc1))
bokeh_app2 = Application(FunctionHandler(modify_doc2))

io_loop = IOLoop.current()

server = Server({'/bkapp1': bokeh_app1 , '/bkapp2' : bokeh_app2 }, io_loop=io_loop, allow_websocket_origin=["localhost:8080"])
server.start()

@flask_app.route('/', methods=['GET'] )
def index():
    res =  "<table>"
    res += "<tr><td><a href=\"http://localhost:8080/app1/c1\">APP1 C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/app1/c2\">APP1 C2</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/app2/c1\">APP2 C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/app2/c2\">APP2 C2</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/sendModelData/c1\">DATA C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/sendModelData/c2\">DATA C2</a></td></tr>"
    res += "</table>"
    return res

@flask_app.route( '/app1/<colName>' , methods=['GET'] )
def bkapp1_page( colName ) :
    script = server_document( url='http://localhost:5006/bkapp1' , arguments={'colName' : colName } )
    return render_template("embed.html", script=script)

@flask_app.route( '/app2/<colName>' , methods=['GET'] )
def bkapp2_page( colName ) :
    script = server_document( url='http://localhost:5006/bkapp2', arguments={'colName' : colName } )
    return render_template("embed.html", script=script)

@flask_app.route('/sendModelData/<colName>' , methods=['GET'] )
def sendModelData( colName ) :
    x = modelDf[ colName + "_x" ].tolist()
    y = modelDf[ colName + "_y" ].tolist()
    return jsonify( x=x , y=y )

if __name__ == '__main__':
    from tornado.httpserver import HTTPServer
    from tornado.wsgi import WSGIContainer
    from bokeh.util.browser import view

    print('Opening Flask app with embedded Bokeh application on http://localhost:8080/')

    # This uses Tornado to server the WSGI app that flask provides. Presumably the IOLoop
    # could also be started in a thread, and Flask could server its own app directly
    http_server = HTTPServer(WSGIContainer(flask_app))
    http_server.listen(8080)

    io_loop.add_callback(view, "http://localhost:8080/")
    io_loop.start()
</code>```

Here's the pages rendered...

Here's some debug output...

```<code>C:\TestApp>python flask_embedJSONRoute.py
Opening Flask app with embedded Bokeh application on http://localhost:8080/
> C:\TestApp\flask_embedjsonroute.py(52)modify_doc2()
-> res = requests.get( url , timeout=None , verify=False )
(Pdb) n
> C:\TestApp\flask_embedjsonroute.py(53)modify_doc2()
-> print( "CODE %s" % res.status_code )
(Pdb) n
CODE 503
> C:\TestApp\flask_embedjsonroute.py(54)modify_doc2()
-> print( "ENCODING %s" % res.encoding )
(Pdb) n
ENCODING utf-8
> C:\TestApp\flask_embedjsonroute.py(55)modify_doc2()
-> print( "TEXT %s" % res.text )
(Pdb) n
TEXT
> C:\TestApp\flask_embedjsonroute.py(56)modify_doc2()
-> data = res.json()
(Pdb)

  File "C:\Anaconda3\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

答:
This appears to be not an issue with Bokeh per se but rather an issue with threading and blocking in the server that's running the Flask app.

It's reproducible apart from Bokeh entirely...

```<code>import requests
from flask import Flask, jsonify, request
import pandas
import pdb

flask_app = Flask(__name__)

# Populate some model maintained by the flask application
modelDf = pandas.DataFrame()
nData = 100
modelDf[ 'c1_x' ] = range(nData)
modelDf[ 'c1_y' ] = [ x*x for x in range(nData) ]
modelDf[ 'c2_x' ] = range(nData)
modelDf[ 'c2_y' ] = [ 2*x for x in range(nData) ]

@flask_app.route('/', methods=['GET'] )
def index():
    res =  "<table>"
    res += "<tr><td><a href=\"http://localhost:8080/sendModelData/c1\">SEND C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/sendModelData/c2\">SEND C2</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlaskNoProxy?colName=c1\">REQUEST OVER FLASK NO PROXY C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlaskNoProxy?colName=c2\">REQUEST OVER FLASK NO PROXY C2</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlask?colName=c1\">REQUEST OVER FLASK C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlask?colName=c2\">REQUEST OVER FLASK C2</a></td></tr>"
    res += "</table>"
    return res

@flask_app.route('/RequestsOverFlaskNoProxy')
def requestsOverFlaskNoProxy() :
    print("RequestsOverFlaskNoProxy")
    # get column name from query string
    colName = request.args.get('colName')

    # get model data from Flask
    url = "http://localhost:8080/sendModelData/%s" % colName

    print("Get data from %s" % url )
    session = requests.Session()
    session.trust_env = False
    res = session.get( url , timeout=5000 , verify=False )
    print( "CODE %s" % res.status_code )
    print( "ENCODING %s" % res.encoding )
    print( "TEXT %s" % res.text )
    data = res.json()
    return data

@flask_app.route('/RequestsOverFlask')
def requestsOverFlask() :
    # get column name from query string
    colName = request.args.get('colName')

    # get model data from Flask
    url = "http://localhost:8080/sendModelData/%s" % colName
    res = requests.get( url , timeout=None , verify=False )
    print( "CODE %s" % res.status_code )
    print( "ENCODING %s" % res.encoding )
    print( "TEXT %s" % res.text )
    data = res.json()
    return data

@flask_app.route('/sendModelData/<colName>' , methods=['GET'] )
def sendModelData( colName ) :
    x = modelDf[ colName + "_x" ].tolist()
    y = modelDf[ colName + "_y" ].tolist()
    return jsonify( x=x , y=y )

if __name__ == '__main__':
    print('Opening Flask app on http://localhost:8080/')

    # THIS DOES NOT WORK
    #flask_app.run( host='0.0.0.0' , port=8080 , debug=True )

    # THIS WORKS
    flask_app.run( host='0.0.0.0' , port=8080 , debug=True , threaded=True )
</code>```

One can see from the screen shot that serving data directly from sendModelData renders the JSon appropriately, but when fetched via the requests.get method yields an exception due to a 503 code as reported in the Python Console.

If I make the same attempt trying to eliminate the effect of the proxies which I have enabled via environment variables but this approach never completes and the request leaves the browser spinning indefinitely.

Come to think of it it may be completely unnecessary to even use requests as a middle man and I should be able to just get the json string and go about deserializing it myself. Well, that would work in this setup by in my actual code the Bokeh rendering is done in a completely different python Module than the Flask application so these functions are not even available unless I scramble the layering of the app.

EDIT
As it turns out the fundamental thing I was violating was with Flask's development environment...

You are running your WSGI app with the Flask test server, which by
  default uses a single thread to handle requests. So when your one
  request thread tries to call back into the same server, it is still
  busy trying to handle that one request.
  https://stackoverflow.com/a/22878916/1330381

So then the question becomes how to apply this threaded=True technique in the original Bokeh example? This may not be possible by the flask_embed.py example's reliance on the Tornado WSGI server which from this question suggests Tornado is single threaded by design.
Given the above  findings an even keener question is how does the AjaxDataSource all together avoid these threading issues faced by the requests module?

Update
Some more background on the Bokeh and Tornado coupling...

53:05 so they're actually are not very many, the question is about the
  dependencies for Bokeh and the Bokeh server. The new Bokeh server is
  built on tornado and that's pretty much the main dependency is it uses
  tornado. Beyond that there's not very many dependencies, runtime
  dependencies, for Bokeh. pandas is an optional dependency for
  Bokeh.charts. There's other dependencies, you know numpy is used. But
  there's only, the list of dependencies I think is six or seven. We've
  tried to pare it down greatly over the years and so, but the main
  dependency of the server is tornado. Intro to Data Visualization with
  Bokeh - Part 1 - Strata Hadoop San Jose
  2016

ContentLicense: CC BY-SA 4.0

Body:
I'm in the process of parameterizing my bokeh apps by having my Flask app expose model data via a route dedicated to jsonifying the requested data passed via query string arguments. I know the data sending route works since when I use it as a url to AjaxDataSource I get the expected data plotted. However when I attempt the equivalent operation using the requests.get api I get a 503 response code which makes me think I'm violating something fundamental here I can't quite grasp with my limited webdev experience. What am I doing wrong and or violating?

I actually need a bit more data retrieving flexibility than the AjaxDataSource provides with its columnar limitations. I was hoping to lean on the requests module to pass arbitrary class instances and what not around by serializing and deserializing Json.

Here's the minimal example I have demonstrating the failure derived from  flask_embed.html...

import requests
from flask import Flask, jsonify, render_template
import pandas
from tornado.ioloop import IOLoop

from bokeh.application          import Application
from bokeh.application.handlers import FunctionHandler
from bokeh.embed                import server_document
from bokeh.layouts              import column
from bokeh.models               import AjaxDataSource,ColumnDataSource
from bokeh.plotting             import figure
from bokeh.server.server        import Server

flask_app = Flask(__name__)

# Populate some model maintained by the flask application
modelDf = pandas.DataFrame()
nData = 100
modelDf[ 'c1_x' ] = range(nData)
modelDf[ 'c1_y' ] = [ x*x for x in range(nData) ]
modelDf[ 'c2_x' ] = range(nData)
modelDf[ 'c2_y' ] = [ 2*x for x in range(nData) ]

def modify_doc1(doc):
    # get colum name from query string
    args      = doc.session_context.request.arguments
    paramName = str( args['colName'][0].decode('utf-8') )

    # get model data from Flask
    url    = "http://localhost:8080/sendModelData/%s" % paramName
    source = AjaxDataSource( data             = dict( x=[] , y=[] ) ,
                            data_url         = url       ,
                            polling_interval = 5000      ,
                            mode             = 'replace' ,
                            method           = 'GET'     )
    # plot the model data
    plot = figure( )
    plot.circle( 'x' , 'y' , source=source , size=2 )
    doc.add_root(column(plot))

def modify_doc2(doc):
    # get column name from query string
    args    = doc.session_context.request.arguments
    colName = str( args['colName'][0].decode('utf-8') )

    # get model data from Flask
    url = "http://localhost:8080/sendModelData/%s" % colName
    #pdb.set_trace()
    res = requests.get( url , timeout=None , verify=False )
    print( "CODE %s" % res.status_code )
    print( "ENCODING %s" % res.encoding )
    print( "TEXT %s" % res.text )
    data = res.json()

    # plot the model data
    plot = figure()
    plot.circle( 'x' , 'y' , source=data , size=2 )
    doc.add_root(column(plot))

bokeh_app1 = Application(FunctionHandler(modify_doc1))
bokeh_app2 = Application(FunctionHandler(modify_doc2))

io_loop = IOLoop.current()

server = Server({'/bkapp1': bokeh_app1 , '/bkapp2' : bokeh_app2 }, io_loop=io_loop, allow_websocket_origin=["localhost:8080"])
server.start()

@flask_app.route('/', methods=['GET'] )
def index():
    res =  "
"
    res += "
APP1 C1
"
    res += "
APP1 C2
"
    res += "
APP2 C1
"
    res += "
APP2 C2
"
    res += "
DATA C1
"
    res += "
DATA C2
"
    res += "
"
    return res

@flask_app.route( '/app1/<colName>' , methods=['GET'] )
def bkapp1_page( colName ) :
    script = server_document( url='http://localhost:5006/bkapp1' , arguments={'colName' : colName } )
    return render_template("embed.html", script=script)

@flask_app.route( '/app2/<colName>' , methods=['GET'] )
def bkapp2_page( colName ) :
    script = server_document( url='http://localhost:5006/bkapp2', arguments={'colName' : colName } )
    return render_template("embed.html", script=script)

@flask_app.route('/sendModelData/<colName>' , methods=['GET'] )
def sendModelData( colName ) :
    x = modelDf[ colName + "_x" ].tolist()
    y = modelDf[ colName + "_y" ].tolist()
    return jsonify( x=x , y=y )

if __name__ == '__main__':
    from tornado.httpserver import HTTPServer
    from tornado.wsgi import WSGIContainer
    from bokeh.util.browser import view

    print('Opening Flask app with embedded Bokeh application on http://localhost:8080/')

    # This uses Tornado to server the WSGI app that flask provides. Presumably the IOLoop
    # could also be started in a thread, and Flask could server its own app directly
    http_server = HTTPServer(WSGIContainer(flask_app))
    http_server.listen(8080)

    io_loop.add_callback(view, "http://localhost:8080/")
    io_loop.start()

Here's the pages rendered...

Here's some debug output...

C:\TestApp>python flask_embedJSONRoute.py
Opening Flask app with embedded Bokeh application on http://localhost:8080/
> C:\TestApp\flask_embedjsonroute.py(52)modify_doc2()
-> res = requests.get( url , timeout=None , verify=False )
(Pdb) n
> C:\TestApp\flask_embedjsonroute.py(53)modify_doc2()
-> print( "CODE %s" % res.status_code )
(Pdb) n
CODE 503
> C:\TestApp\flask_embedjsonroute.py(54)modify_doc2()
-> print( "ENCODING %s" % res.encoding )
(Pdb) n
ENCODING utf-8
> C:\TestApp\flask_embedjsonroute.py(55)modify_doc2()
-> print( "TEXT %s" % res.text )
(Pdb) n
TEXT
> C:\TestApp\flask_embedjsonroute.py(56)modify_doc2()
-> data = res.json()
(Pdb)

  File "C:\Anaconda3\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Body:
This appears to be not an issue with Bokeh per se but rather an issue with threading and blocking in the server that's running the Flask app.

It's reproducible apart from Bokeh entirely...

import requests
from flask import Flask, jsonify, request
import pandas
import pdb

flask_app = Flask(__name__)

# Populate some model maintained by the flask application
modelDf = pandas.DataFrame()
nData = 100
modelDf[ 'c1_x' ] = range(nData)
modelDf[ 'c1_y' ] = [ x*x for x in range(nData) ]
modelDf[ 'c2_x' ] = range(nData)
modelDf[ 'c2_y' ] = [ 2*x for x in range(nData) ]

@flask_app.route('/', methods=['GET'] )
def index():
    res =  "<table>"
    res += "<tr><td><a href=\"http://localhost:8080/sendModelData/c1\">SEND C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/sendModelData/c2\">SEND C2</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlaskNoProxy?colName=c1\">REQUEST OVER FLASK NO PROXY C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlaskNoProxy?colName=c2\">REQUEST OVER FLASK NO PROXY C2</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlask?colName=c1\">REQUEST OVER FLASK C1</a></td></tr>"
    res += "<tr><td><a href=\"http://localhost:8080/RequestsOverFlask?colName=c2\">REQUEST OVER FLASK C2</a></td></tr>"
    res += "</table>"
    return res

@flask_app.route('/RequestsOverFlaskNoProxy')
def requestsOverFlaskNoProxy() :
    print("RequestsOverFlaskNoProxy")
    # get column name from query string
    colName = request.args.get('colName')

    # get model data from Flask
    url = "http://localhost:8080/sendModelData/%s" % colName

    print("Get data from %s" % url )
    session = requests.Session()
    session.trust_env = False
    res = session.get( url , timeout=5000 , verify=False )
    print( "CODE %s" % res.status_code )
    print( "ENCODING %s" % res.encoding )
    print( "TEXT %s" % res.text )
    data = res.json()
    return data

@flask_app.route('/RequestsOverFlask')
def requestsOverFlask() :
    # get column name from query string
    colName = request.args.get('colName')

    # get model data from Flask
    url = "http://localhost:8080/sendModelData/%s" % colName
    res = requests.get( url , timeout=None , verify=False )
    print( "CODE %s" % res.status_code )
    print( "ENCODING %s" % res.encoding )
    print( "TEXT %s" % res.text )
    data = res.json()
    return data

@flask_app.route('/sendModelData/<colName>' , methods=['GET'] )
def sendModelData( colName ) :
    x = modelDf[ colName + "_x" ].tolist()
    y = modelDf[ colName + "_y" ].tolist()
    return jsonify( x=x , y=y )

if __name__ == '__main__':
    print('Opening Flask app on http://localhost:8080/')

    # THIS DOES NOT WORK
    #flask_app.run( host='0.0.0.0' , port=8080 , debug=True )

    # THIS WORKS
    flask_app.run( host='0.0.0.0' , port=8080 , debug=True , threaded=True )

One can see from the screen shot that serving data directly from sendModelData renders the JSon appropriately, but when fetched via the requests.get method yields an exception due to a 503 code as reported in the Python Console.

If I make the same attempt trying to eliminate the effect of the proxies which I have enabled via environment variables but this approach never completes and the request leaves the browser spinning indefinitely.

Come to think of it it may be completely unnecessary to even use requests as a middle man and I should be able to just get the json string and go about deserializing it myself. Well, that would work in this setup by in my actual code the Bokeh rendering is done in a completely different python Module than the Flask application so these functions are not even available unless I scramble the layering of the app.

EDIT
As it turns out the fundamental thing I was violating was with Flask's development environment...

You are running your WSGI app with the Flask test server, which by
  default uses a single thread to handle requests. So when your one
  request thread tries to call back into the same server, it is still
  busy trying to handle that one request.
  https://stackoverflow.com/a/22878916/1330381

So then the question becomes how to apply this threaded=True technique in the original Bokeh example? This may not be possible by the flask_embed.py example's reliance on the Tornado WSGI server which from this question suggests Tornado is single threaded by design.
Given the above  findings an even keener question is how does the AjaxDataSource all together avoid these threading issues faced by the requests module?

Update
Some more background on the Bokeh and Tornado coupling...

53:05 so they're actually are not very many, the question is about the
  dependencies for Bokeh and the Bokeh server. The new Bokeh server is
  built on tornado and that's pretty much the main dependency is it uses
  tornado. Beyond that there's not very many dependencies, runtime
  dependencies, for Bokeh. pandas is an optional dependency for
  Bokeh.charts. There's other dependencies, you know numpy is used. But
  there's only, the list of dependencies I think is six or seven. We've
  tried to pare it down greatly over the years and so, but the main
  dependency of the server is tornado. Intro to Data Visualization with
  Bokeh - Part 1 - Strata Hadoop San Jose
  2016


问:
Process multiple variables in bash loop
I have 4 lists of variables like this:

```<code>YEAR1="2008 2008 2009"
YEAR2="2008 2009 2009"
MONTH1="11 12 01"
MONTH2="12 01 02"
</code>```

I want to pipe them through to a Python script in a way that the first items from all 4 lists are input first, then the second items from each list and so on. I believe I need to use a WHILE loop for this, but mine doesn't work. I don't get an error message either.

```<code>while read $YEAR1 $YEAR2 $MONTH1 $MONTH2;do
    python python-code.py "$YEAR1" "$MONTH1" "$YEAR2" "$MONTH2"
done
</code>```

My Python script is tested and works, I'm just not getting my head around bash scripting.

Title: Process multiple variables in bash loop

Body:
I have 4 lists of variables like this:

YEAR1="2008 2008 2009"
YEAR2="2008 2009 2009"
MONTH1="11 12 01"
MONTH2="12 01 02"

I want to pipe them through to a Python script in a way that the first items from all 4 lists are input first, then the second items from each list and so on. I believe I need to use a WHILE loop for this, but mine doesn't work. I don't get an error message either.

while read $YEAR1 $YEAR2 $MONTH1 $MONTH2;do
    python python-code.py "$YEAR1" "$MONTH1" "$YEAR2" "$MONTH2"
done

My Python script is tested and works, I'm just not getting my head around bash scripting.

Body:
Use arrays instead:

#! /bin/bash
YEAR1=(2008 2008 2009)
YEAR2=(2008 2009 2009)
MONTH1=(11 12 01)
MONTH2=(12 01 02)

for (( i=0 ; i < ${#YEAR1[@]} ; ++i )) ; do
    python python-code.py ${YEAR1[i]} ${YEAR2[i]} ${MONTH1[i]} ${MONTH2[i]}
done


问:
Problems with converting some text in Tkinter Entry
I wrote a program which works well in console but then i tried to use this program with tkinter. The program is still working but the converted text is not the text that written in the Entry class of tkinter. The codes are below:

```<code>from tkinter import *

def dictionary():
    ascii_dictionary = {chr(i): bin(i)[2:] for i in range(128)}
    for i in ascii_dictionary:
        if len(ascii_dictionary[i]) < 8:
            count = 8 - len(ascii_dictionary[i])
            ascii_dictionary[i] = "".zfill(count) + ascii_dictionary[i]
    non_ascii_dictionary = {chr(i): bin(int(bytes(chr(i).encode(encoding="utf-8")).hex(), 16))[2:10] + " " +
                        bin(int(bytes(chr(i).encode(encoding="utf-8")).hex(), 16))[10:18] for i in range(128, 512)}
    dictionary = ascii_dictionary.copy()
    dictionary.update(non_ascii_dictionary)
    return dictionary

class Application():

    def __init__(self):
        self.window = Tk()
        self.frame_1 = Frame()
        self.frame_1.grid(row=0,column=0)
        self.widgets()
        self.mainloop = self.window.mainloop()

    def widgets(self):

        self.label_1 = Label(self.frame_1,text="Text To Binary:")
        self.label_1.grid(row=0,column=0)
        self.entry_1 = Entry(self.frame_1)
        self.entry_1.grid(row=0,column=1)
        self.button_1 = Button(self.frame_1,text="Convert",command=self.convert)
        self.button_1.grid(row=0,column=2)

    def convert(self):
        text_1=str(self.entry_1)
        return_value = dictionary()
        list_1 = [return_value[j] for i in text_1 for j in return_value if i == j]
        text_2 = " ".join(list_1)
        print(text_1,text_2)

instance=Application()
</code>```

For example when i type "hello" to the Entry then press the convert button, i see that the converted word is ".6138064.9675856". In your opinion, what is the problem?

答:
```<code>text_1=str(self.entry_1)
</code>```

str(self.entry_1) gets the string representation of the entry_1 widget. The string representation of a widget is its unique identifier, a collection of decimal points and digits. If you want the text inside the entry, use get.

```<code>text_1=str(self.entry_1.get())
</code>```

Body:
I wrote a program which works well in console but then i tried to use this program with tkinter. The program is still working but the converted text is not the text that written in the Entry class of tkinter. The codes are below:

from tkinter import *

def dictionary():
    ascii_dictionary = {chr(i): bin(i)[2:] for i in range(128)}
    for i in ascii_dictionary:
        if len(ascii_dictionary[i]) < 8:
            count = 8 - len(ascii_dictionary[i])
            ascii_dictionary[i] = "".zfill(count) + ascii_dictionary[i]
    non_ascii_dictionary = {chr(i): bin(int(bytes(chr(i).encode(encoding="utf-8")).hex(), 16))[2:10] + " " +
                        bin(int(bytes(chr(i).encode(encoding="utf-8")).hex(), 16))[10:18] for i in range(128, 512)}
    dictionary = ascii_dictionary.copy()
    dictionary.update(non_ascii_dictionary)
    return dictionary

class Application():

    def __init__(self):
        self.window = Tk()
        self.frame_1 = Frame()
        self.frame_1.grid(row=0,column=0)
        self.widgets()
        self.mainloop = self.window.mainloop()

    def widgets(self):

        self.label_1 = Label(self.frame_1,text="Text To Binary:")
        self.label_1.grid(row=0,column=0)
        self.entry_1 = Entry(self.frame_1)
        self.entry_1.grid(row=0,column=1)
        self.button_1 = Button(self.frame_1,text="Convert",command=self.convert)
        self.button_1.grid(row=0,column=2)

    def convert(self):
        text_1=str(self.entry_1)
        return_value = dictionary()
        list_1 = [return_value[j] for i in text_1 for j in return_value if i == j]
        text_2 = " ".join(list_1)
        print(text_1,text_2)

instance=Application()

For example when i type "hello" to the Entry then press the convert button, i see that the converted word is ".6138064.9675856". In your opinion, what is the problem?

Body:
text_1=str(self.entry_1)

str(self.entry_1) gets the string representation of the entry_1 widget. The string representation of a widget is its unique identifier, a collection of decimal points and digits. If you want the text inside the entry, use get.

text_1=str(self.entry_1.get())


问:
react-router Link typescript error
I just started to add TypeScript on my React project, and I can't figure out of this error :

```<code>import {Link} from 'react-router';
Module '"/Users/.../node_modules/@types/react-router/index"' has no exported member 'Link'.
</code>```

The Link component exists in react-router (the code is working), but TypeScript does not recognise it. I've added the @types/react-router, and it seems not to implements the Link. Any ideas ?

Extract from my package.json :

```<code>"@types/react": "^15.0.25",
"@types/react-dom": "^15.5.0",
"@types/react-router": "^4.0.11",
"@types/reactstrap": "^4.3.4",

...

"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "^3.0.2",
"reactstrap": "^4.2.0"

...

"typescript": "^2.3.3",
</code>```

答:
You have react-router version 3, but the @types package for version 4.  Version 4 of react-router moved a lot of the library into the react-router-dom package, which is why their types are not in the @types/react-router v4 packages.

You should remove the incorrect type package with:

```<code>npm un @types/react-router
</code>```

Then install the correct types with:

```<code>npm i --save-dev @types/react-router@3
</code>```

Title: react-router Link typescript error

Body:
I just started to add TypeScript on my React project, and I can't figure out of this error :

import {Link} from 'react-router';
Module '"/Users/.../node_modules/@types/react-router/index"' has no exported member 'Link'.

The Link component exists in react-router (the code is working), but TypeScript does not recognise it. I've added the @types/react-router, and it seems not to implements the Link. Any ideas ?

Extract from my package.json :

"@types/react": "^15.0.25",
"@types/react-dom": "^15.5.0",
"@types/react-router": "^4.0.11",
"@types/reactstrap": "^4.3.4",

...

"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "^3.0.2",
"reactstrap": "^4.2.0"

...

"typescript": "^2.3.3",

Body:
You have react-router version 3, but the @types package for version 4.  Version 4 of react-router moved a lot of the library into the react-router-dom package, which is why their types are not in the @types/react-router v4 packages.

You should remove the incorrect type package with:

npm un @types/react-router

Then install the correct types with:

npm i --save-dev @types/react-router@3


问:
Charset UTF-8 for external JavaScript file
I add an external JavaScript file like this:

```<code><head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script charset="utf-8" type="text/javascript" src="js/panel.js" ></script>
</head>
</code>```

But the text stored in panel.js file is displayed like this in the HTML file:

```<code>H69�*
</code>```

When I put JavaScript code in the HTML page, the text is displayed properly. But when I put JavaScript code in panel.js, it does not work.

答:
in the mac OS it is a capital -i...like this:</p>

```<code>file -I
</code>```

Body:
I add an external JavaScript file like this:

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

But the text stored in panel.js file is displayed like this in the HTML file:

H69�*

When I put JavaScript code in the HTML page, the text is displayed properly. But when I put JavaScript code in panel.js, it does not work.

Body:
in the mac OS it is a capital -i...like this:

file -I


问:
Hashing a template type
Here, I tried to make a map that its vertex can be user-defined class. But when I try to add template type element to the unordered_set it gives error. The code is:

```<code>#include <iostream>
#include <unordered_set>
#include <string>
#include <vector>
#include <functional>

template<class T> class Edge;

template<class T> class Vertex{          // Made it a class just for its constructor.
    public:
        template<class A> Vertex(A vert){
            A vertex = vert;
            std::unordered_set<Edge<A>> adjlist;
        }
};

template<class T> class Edge{       // Made it a class just for its constructor.
    public:
        template<class A> Edge(Vertex<A> vert1, Vertex<A> vert2, int w){
            Vertex<A> *origin = &vert1;
            Vertex<A> *target = &vert2;
        }
    };

template<class T>
class WUG{
    private:
        std::unordered_set<Vertex<T>> vertices;
        std::unordered_set<Edge<T>> edges;
        int num_of_edges;
        int num_of_vertices;
    public:
        WUG() {
            num_of_edges = 0;
            num_of_vertices = 0;
        }
        void addVertex(T newVert) {
            Vertex<T> temp = Vertex<T>(newVert);
            vertices.emplace(temp);                 //Problem is here
        }
int main(int argc, char** argv) {
    WUG<char> g1 = WUG<char>();
    g1.addVertex('A');
    g1.addVertex('B');
    g1.addVertex('C');

    return 0;
}
</code>```

Error: it opens hashtable_policy.h and gives error at

```<code>    template <typename _Key, typename _Hash>
         struct __is_noexcept_hash : std::integral_constant<bool,
         noexcept(declval<const _Hash&>()(declval<const _Key&>()))> //Here
    { };
    [Error] no match for call to '(const std::hash<Vertex<char> >) (const Vertex<char>&)'
</code>```

How do you emplace a template type object to unordered_set? How about pair of 2 template?

答:
I believe you need to provide special hashing and comparison functions to make the hash set (or in my example's case, hash map) work. Here is a minimal example. Tested with C++11.

```<code>#include <unordered_map>
#include <iostream>
#include <algorithm>

template<typename T>
struct foo {
  typedef T value_type;
  foo(T x) : x(x) {}
  T x;
};

template<typename T>
struct foo_hasher {
  int operator()(const T &val) const {
    return std::hash<typename T::value_type>()(val.x);
  }
};

template<typename T>
struct foo_equality {
  bool operator()(const T &left, const T& right) const {
    return left.x == right.x;
  }
};

int main() {
  typedef std::unordered_map<foo<int>, int, foo_hasher<foo<int>>, foo_equality<foo<int>>> Map;
  Map mp;
  foo<int> x(5);
  mp[x] = 10;
  mp[foo<int>(10)] = 22;

  std::for_each(mp.begin(), mp.end(), [](const Map::value_type &val) {
    std::cout << val.first.x << ", " << val.second << "\n";
  });
}
</code>```

Note that both my hashing and equality function are not at all restrictive - they are wrt T rather than foo, but the principal should be the same.

Title: Hashing a template type

Body:
Here, I tried to make a map that its vertex can be user-defined class. But when I try to add template type element to the unordered_set it gives error. The code is:

#include <iostream>
#include <unordered_set>
#include <string>
#include <vector>
#include <functional>

template<class T> class Edge;

template<class T> class Vertex{          // Made it a class just for its constructor.
    public:
        template<class A> Vertex(A vert){
            A vertex = vert;
            std::unordered_set<Edge> adjlist;
        }
};

template<class T> class Edge{       // Made it a class just for its constructor.
    public:
        template<class A> Edge(Vertex vert1, Vertex vert2, int w){
            Vertex *origin = &vert1;
            Vertex *target = &vert2;
        }
    };

template<class T>
class WUG{
    private:
        std::unordered_set<Vertex<T>> vertices;
        std::unordered_set<Edge<T>> edges;
        int num_of_edges;
        int num_of_vertices;
    public:
        WUG() {
            num_of_edges = 0;
            num_of_vertices = 0;
        }
        void addVertex(T newVert) {
            Vertex<T> temp = Vertex<T>(newVert);
            vertices.emplace(temp);                 //Problem is here
        }
int main(int argc, char** argv) {
    WUG<char> g1 = WUG<char>();
    g1.addVertex('A');
    g1.addVertex('B');
    g1.addVertex('C');

    return 0;
}

Error: it opens hashtable_policy.h and gives error at

    template <typename _Key, typename _Hash>
         struct __is_noexcept_hash : std::integral_constant<bool,
         noexcept(declval<const _Hash&>()(declval<const _Key&>()))> //Here
    { };
    [Error] no match for call to '(const std::hash<Vertex<char> >) (const Vertex<char>&)'

How do you emplace a template type object to unordered_set? How about pair of 2 template?

Body:
I believe you need to provide special hashing and comparison functions to make the hash set (or in my example's case, hash map) work. Here is a minimal example. Tested with C++11.

#include <unordered_map>
#include <iostream>
#include <algorithm>

template<typename T>
struct foo {
  typedef T value_type;
  foo(T x) : x(x) {}
  T x;
};

template<typename T>
struct foo_hasher {
  int operator()(const T &val) const {
    return std::hash<typename T::value_type>()(val.x);
  }
};

template<typename T>
struct foo_equality {
  bool operator()(const T &left, const T& right) const {
    return left.x == right.x;
  }
};

int main() {
  typedef std::unordered_map<foo<int>, int, foo_hasher<foo<int>>, foo_equality<foo<int>>> Map;
  Map mp;
  foo<int> x(5);
  mp[x] = 10;
  mp[foo<int>(10)] = 22;

  std::for_each(mp.begin(), mp.end(), [](const Map::value_type &val) {
    std::cout << val.first.x << ", " << val.second << "\n";
  });
}

Note that both my hashing and equality function are not at all restrictive - they are wrt T rather than foo, but the principal should be the same.


问:
Object Oriented questions in Javascript
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

```<code>function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

```<code>function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

```<code>var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());
</code>```

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

```<code>var user = new User("Bob", 44);
</code>```

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

答:
2:

You can access name and age, without using such functions. In javascript you have to use different hacks to keep something private or protected.

This

```<code>User.name = "BoB";
User.age = 44;
</code>```

will produce same output as your example.

There are no constructors as they appear in other languages. Easiest way would be to just define init() function and call it right after you instance the object.

But my biggest tip for you is to look into http://www.prototypejs.org/. It's a javascript library with a lot of cool features which tries to make javascript "more OO*".

Using prototype library you can make classes to behave more like real OOP classes. It also features constructors.

Edit:
As for what you asked in your comment:

```<code>person = new User();
person.name = "Bob";
person.age = 44;
</code>```

OwnerDisplayName: BrianH

Title: Object Oriented questions in Javascript

Body:
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

var user = new User("Bob", 44);

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

LastEditorDisplayName: BrianH

Body:
2:

You can access name and age, without using such functions. In javascript you have to use different hacks to keep something private or protected.

This

User.name = "BoB";
User.age = 44;

will produce same output as your example.

There are no constructors as they appear in other languages. Easiest way would be to just define init() function and call it right after you instance the object.

But my biggest tip for you is to look into http://www.prototypejs.org/. It's a javascript library with a lot of cool features which tries to make javascript "more OO*".

Using prototype library you can make classes to behave more like real OOP classes. It also features constructors.

Edit:
As for what you asked in your comment:

person = new User();
person.name = "Bob";
person.age = 44;

OwnerDisplayName: Maiku Mori

LastEditorDisplayName: Maiku Mori


问:
Hidden focus on blur of an input element in dom
A little Explanation : I am using List view control of kendo UI(Telerik). I am triggering an update event of that control after editing the fields in list view. The list view control is having some text-boxes, a dropdown,checkbox and a submit button. When a user change something,  ideally it should trigger update but its not doing update because control is not able to judge if there  is a change  in model.

It is only working if I input something in textbox and just click on outside of textbox i.e just do a onblur before hitting submit. I don't know why it is happening but what I need is to just trigger a focus event but in a hidden mode so that user is unaware of it but it just happens after a user input something in textbox so that the list view control works successfully.

I am trying to do it like below but it will get noticed to user. How can i trigger focus in hidden mode after a user just enter something in textbox before hitting a submit?

```<code> function BlurFunc() {
                    debugger;
                    $(this).closest('li').find('.inputField').focus();
                }
</code>```

答:
Without your code it is not clear whether you are using MVVM data binding to your model, but this may help; from http://docs.telerik.com/kendo-ui/framework/mvvm/bindings/value:

By default the value binding relies on the change DOM event, which is
  raised after blurring the element whose value has changed. This means
  that the value from the View-Model is updated when the element loses
  focus. The data-value-update attribute can be used to specify a
  different DOM event, such as keyup or keypress. The keydown event is
  not supported, because the DOM element value is not yet updated when
  that event triggers.

For example, try adding data-value-update="keyup" as an attribute to your text box input element:

```<code><input data-value-update="keyup" data-bind="value: inputValue" />
</code>```

This should then update the model value upon each key press and not wait until focus has been removed.

Body:
A little Explanation : I am using List view control of kendo UI(Telerik). I am triggering an update event of that control after editing the fields in list view. The list view control is having some text-boxes, a dropdown,checkbox and a submit button. When a user change something,  ideally it should trigger update but its not doing update because control is not able to judge if there  is a change  in model.

It is only working if I input something in textbox and just click on outside of textbox i.e just do a onblur before hitting submit. I don't know why it is happening but what I need is to just trigger a focus event but in a hidden mode so that user is unaware of it but it just happens after a user input something in textbox so that the list view control works successfully.

I am trying to do it like below but it will get noticed to user. How can i trigger focus in hidden mode after a user just enter something in textbox before hitting a submit?

 function BlurFunc() {
                    debugger;
                    $(this).closest('li').find('.inputField').focus();
                }

Body:
Without your code it is not clear whether you are using MVVM data binding to your model, but this may help; from http://docs.telerik.com/kendo-ui/framework/mvvm/bindings/value:

By default the value binding relies on the change DOM event, which is
  raised after blurring the element whose value has changed. This means
  that the value from the View-Model is updated when the element loses
  focus. The data-value-update attribute can be used to specify a
  different DOM event, such as keyup or keypress. The keydown event is
  not supported, because the DOM element value is not yet updated when
  that event triggers.

For example, try adding data-value-update="keyup" as an attribute to your text box input element:

<input data-value-update="keyup" data-bind="value: inputValue" />

This should then update the model value upon each key press and not wait until focus has been removed.


问:
Excel VBA how to populate values from different sheets
I have a sheet that I want to be able to transport cell values being double-clicked by users to another sheet/form called JE.

Example: user clicks on cell F10 in sheet JE, that takes the user to a different sheet (containing a macro), once the user is at that sheet, I want the user to be able to double-click any cell in the A column and the cell value being clicked, fills cell F10 back in sheet JE. So, after being navigated to a macro/different sheet, If the user double clicks on cell A7 and the value "123ABC" is in A7, I would like "123ABC" to populate cell F10 in sheet JE. Similarly, if the user clicks cell F25 on sheet JE, and still chooses to double-click A7 in a different sheet, I would like the value "123ABC" to fill F25 in sheet JE. I would also like the cell in column F to turn to a no-fill background once a value is present in the cell.

The issue I am having now is that my code is set up in such a way that no matter which row the user is using on sheet JE, the values in column A of the macros are only filling the first cell in column F(F7) Whereas, I want the value being double-clicked on in the macro to fill in the F column cell that is active, not the first cell in the F column. Also, when double-clicked, the values in column A of the macros, are not changing the background color of the red cell in column F to a no fill, white background.

This code is the code associated with sheet JE (The main form users are filling out)

```<code>Option Explicit
Public sourceRange As Range

Private Sub Worksheet_Change(ByVal Target As Range)
'  If Not Intersect(Target, Range("C7:D446")) Is Nothing Then
      Dim c As Range: Set c = Range("D7:D446")
'     For Each c In Target
 For Each c In c.Cells
          Select Case c.Value
              Case "1000GP", "1000MM", "19FEST", "20IEDU", "20ONLC", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
                  Cells(c.Row, "F").Interior.ColorIndex = 3
              Case Else
                 Cells(c.Row, "F").Interior.ColorIndex = 0
          End Select
      Next c
' End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing ' Set it to nothing to avoid too long remembering
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target ' Remember source cell
      'Cancel = True
      Select Case Target.Offset(0, -2).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
End If

End Sub
</code>```

This is the code that lies in all of the macro sheets which the user is brought to when clicking on the cells in the F column in Sheet JE.

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Set JE.sourceRange = Target.Value
If Target.Column = 1 Then
   If Not JE.sourceRange Is Nothing Then
        JE.sourceRange.Value = ActiveCell.Value
        Cells(c.Row, "F").Interior.ColorIndex = 0

End If
End If
End Sub
</code>```

I am also having trouble getting values for the C column to populate multiple rows. For example, if I already have a value in C7 and want to add a value being clicked on in a sheet to the C column as well, If i click on a value, it will overwrite the value in C7 rather than populating cell C8. Here is the code I have for that sheet:

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Target.Column = 1 Then
'Sheet2.Range("F" & Target.Row & ":F" & Target.Row).Value = ActiveCell.Value
Sheet2.sourceRange.Value = ActiveCell.Value
Worksheets("JE").Activate
'Sheet2.Activate

'Cells(c.Row, "F").Interior.ColorIndex = 3
Cancel = True
End If
End Sub
</code>```

答:
Have you tried using the Target argument? It will tell you the row and column that is being double clicked, and you can use that to construct the range more specifically.</p>

```<code>Worksheets("JE").Range("F" & Target.Row & ":F" & Target.Row).Value = ActiveCell.Value
</code>```

Body:
I have a sheet that I want to be able to transport cell values being double-clicked by users to another sheet/form called JE.

Example: user clicks on cell F10 in sheet JE, that takes the user to a different sheet (containing a macro), once the user is at that sheet, I want the user to be able to double-click any cell in the A column and the cell value being clicked, fills cell F10 back in sheet JE. So, after being navigated to a macro/different sheet, If the user double clicks on cell A7 and the value "123ABC" is in A7, I would like "123ABC" to populate cell F10 in sheet JE. Similarly, if the user clicks cell F25 on sheet JE, and still chooses to double-click A7 in a different sheet, I would like the value "123ABC" to fill F25 in sheet JE. I would also like the cell in column F to turn to a no-fill background once a value is present in the cell.

The issue I am having now is that my code is set up in such a way that no matter which row the user is using on sheet JE, the values in column A of the macros are only filling the first cell in column F(F7) Whereas, I want the value being double-clicked on in the macro to fill in the F column cell that is active, not the first cell in the F column. Also, when double-clicked, the values in column A of the macros, are not changing the background color of the red cell in column F to a no fill, white background.

This code is the code associated with sheet JE (The main form users are filling out)

Option Explicit
Public sourceRange As Range

Private Sub Worksheet_Change(ByVal Target As Range)
'  If Not Intersect(Target, Range("C7:D446")) Is Nothing Then
      Dim c As Range: Set c = Range("D7:D446")
'     For Each c In Target
 For Each c In c.Cells
          Select Case c.Value
              Case "1000GP", "1000MM", "19FEST", "20IEDU", "20ONLC", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
                  Cells(c.Row, "F").Interior.ColorIndex = 3
              Case Else
                 Cells(c.Row, "F").Interior.ColorIndex = 0
          End Select
      Next c
' End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing ' Set it to nothing to avoid too long remembering
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target ' Remember source cell
      'Cancel = True
      Select Case Target.Offset(0, -2).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
End If

End Sub

This is the code that lies in all of the macro sheets which the user is brought to when clicking on the cells in the F column in Sheet JE.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Set JE.sourceRange = Target.Value
If Target.Column = 1 Then
   If Not JE.sourceRange Is Nothing Then
        JE.sourceRange.Value = ActiveCell.Value
        Cells(c.Row, "F").Interior.ColorIndex = 0

End If
End If
End Sub

I am also having trouble getting values for the C column to populate multiple rows. For example, if I already have a value in C7 and want to add a value being clicked on in a sheet to the C column as well, If i click on a value, it will overwrite the value in C7 rather than populating cell C8. Here is the code I have for that sheet:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Target.Column = 1 Then
'Sheet2.Range("F" & Target.Row & ":F" & Target.Row).Value = ActiveCell.Value
Sheet2.sourceRange.Value = ActiveCell.Value
Worksheets("JE").Activate
'Sheet2.Activate

'Cells(c.Row, "F").Interior.ColorIndex = 3
Cancel = True
End If
End Sub

Body:
Have you tried using the Target argument? It will tell you the row and column that is being double clicked, and you can use that to construct the range more specifically.

Worksheets("JE").Range("F" & Target.Row & ":F" & Target.Row).Value = ActiveCell.Value