Categories
discuss

When to create variables (memory management)

You create a variable to store a value that you can refer to that variable in the future. I’ve heard that you must set a variable to ‘null’ once you’re done using it so the garbage collector can get to it (if it’s a field var).

If I were to have a variable that I won’t be referring to agaon, would removing the reference/value vars I’m using (and just using the numbers when needed) save memory? For example:

int number = 5;
public void method() {
    System.out.println(number);
}

Would that take more space than just plugging ‘5’ into the println method?

I have a few integers that I don’t refer to in my code ever again (game loop), but I’ve seen others use reference vars on things that really didn’t need them. Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Answer

I’ve heard that you must set a variable to ‘null’ once you’re done using it so the garbage collector can get to it (if it’s a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don’t need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don’t live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won’t be referring to agaon, would removing the reference vars I’m using (and just using the numbers when needed) save memory?

You don’t free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging ‘5’ into the println method?

The JIT is smart enough to turn fields which don’t change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn’t both with 4 million bytes.

Categories
discuss

Why is an _id with ObjectID added to when using MongoDB’s $push to add new object to an array?

I am using Node.js and Mongoose. player and tournament variables are Mongoose objects, fetched just before.

I want to add a new tournamentSession object (NOT a Mongoose object) into the tournamentSessions field of the player object. I am using the findOneAndUpdate to be able to make sure that I dont add the same tournement twice (using the “$ne”)

Player.findOneAndUpdate({
            '_id': player._id,
            'tournamentSessions.tournament': {
                '$ne': tournament._id
            }
        }, {
            '$push': {
                'tournamentSessions': {
                    'tournament': tournament._id,
                    'level': 1,
                    'status': 'LIMBO',
                    'score': 0,
                }
            }
        }, function(err, updatedPlayer) {
            // ...
        });

Everything works fine, except that the “_id” field containing an ObjectID is added to the newly added session inside the tournamentSessions array, and I cant understand why this is happening.

If I manually add the “_id” field and with the value “BLABLABLA”, the “_id” field is never stored (as it shouldnt, coz its not declared in the schema)

Ye, And here is the schemas:

var Player = mongoose.model('Player', Schema({
    createdAt: { type: Date, default: Date.now },
    lastActiveAt: Date,
    clientVersion: String,
    tournamentSessions: [{
        tournament: { type: Schema.Types.ObjectId, ref: 'Tournament' },
        level: Number,
        status: String,
        score: Number
    }],
    friends: Array
}));

var Tournament = mongoose.model('Tournament', Schema({
    createdAt: { type: Date, default: Date.now },
    open: Boolean,
    number: Number,
    level: Number,
    reactionLimit: Number,
    deadlineAt: Date,
    stats: {
        total: Number,
        limbo: Number,
        blessed: Number,
        damned: Number
    }
}));

Answer

You can disable the _id field by explicitly defining the tournamentSessions array with its own schema so that you can set its _id option to false:

var Player = mongoose.model('Player', Schema({
    createdAt: { type: Date, default: Date.now },
    lastActiveAt: Date,
    clientVersion: String,
    tournamentSessions: [new Schema({
        tournament: { type: Schema.Types.ObjectId, ref: 'Tournament' },
        level: Number,
        status: String,
        score: Number
    }, { _id: false })],
    friends: Array
}));
Categories
discuss

Are Up, Down, Left, Right Arrow KeyCodes always the same?

As the title suggests, in my code I use the following codes:

  • Left: 37
  • Up: 38
  • Right: 39
  • Down: 40

And check for those key codes to determine my action. My question is, do those always remain the same? If I were to use a DVORAK keyboard, or a non-English keyboard, would those key codes remain the same?

Along the same line, is there a preferred method for detecting those keystrokes?

Currently, I do it as follows:

    var Key = {
        _pressed: {},
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40,

        isDown: function (keyCode) {
            return this._pressed[keyCode];
        },

        onKeydown: function (event) {
            this._pressed[event.keyCode] = true;

            if (Key.isDown(Key.UP))
                //do up action
            else if (Key.isDown(Key.DOWN)) {
                //do down action
            }
            delete this._pressed[event.keyCode];
        }
    };

Answer

Yes, arrow key keycodes are always the same, regardless of the keyboard layout.

I regularly use different keyboard layouts (Dvorak, Russian, Ukrainian, Hebrew, Spanish) and I have tried all of them in JavaScript and they give consistent results for the arrow keys.

Categories
discuss

App requesting undeclared permission – “Test access to protected storage”

I’ve added to my manifest permission declaration for WRITE_EXTERNAL_STORAGE, and after some time I’ve noticed it asks also for Test access to protected storage when installing.
I declare in my manifest the minSdk as 14 and my targetSdk as 19.

How can I get rid of that ?

Answer

That prompt would appear to be tied to READ_EXTERNAL_STORAGE, which you are presumably being given automatically since you requested WRITE_EXTERNAL_STORAGE.

How can I get rid of that ?

Remove your WRITE_EXTERNAL_STORAGE permission. This, of course, has side effects. 🙂

Categories
discuss

inter-Iframe communication using postMessage

I have a parent page of domain A (http://example.com)

On the parent page exists two iframes that are the same domain but not domain A. (http://test.com)

Is there any way to pass a value from one test.com iframe to the other when the parent is example.com or is the behavior I am describing against the “rules” of iframes

Thanks

Answer

Checkout this JSFiddle, I simulated the cross-domain iFrames in order to make it more readable. Basically the top parent of both frames acts as a mediator to re-dispatch the message to the target frame, but the frames trigger all actions and responses.

HTML

<!-- Adding the sandboxing attribute to illustrade cross-domain -->
<iframe id="one" sandbox="allow-scripts"></iframe>
<iframe id="two" sandbox="allow-scripts"></iframe>

JavaScript

var frame_one = document.getElementById('one');
var frame_two = document.getElementById('two');

// The parent has to mediate because cross-domain sandboxing
// is enabled when on different domains, plus backwards compatible.
window.addEventListener('message', function (m) {
    // Using an object with a 'frame' property that maps to the ID
    // which could be done as you would like.
    var targetFrame = document.getElementById(m.data.frame);
    targetFrame.contentWindow.postMessage(m.data.message, '*');
}, false);


/**
 * This is just to illustrate what a normal document would look
 * like you should just set the normal 'src' attribute and the
 * string would be the normal HTML of the documents.
 */
frame_two.srcdoc = '<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener("message", function (m) {
alert("Frame Two Says: " + m.data);
}, false);
window.addEventListener("load", function () {
window.parent.postMessage({frame: "one", message: "Received message from frame two!"}, "*");
}, false);
</script>
</head>
<body>
two
</body>';

frame_one.srcdoc = '<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener("message", function (m) {
alert("Frame One Says: " + m.data);
}, false);
window.addEventListener("load", function () {
setTimeout(function () {
window.parent.postMessage({frame: "two", message: "Received message from frame one!"}, "*");
}, 1500);
}, false);
</script>
</head>
<body>
one
</body>';
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..