How to check if JavaScript object is JSON

Question: I have a nested JSON object that I need to loop through, and the value of each key could be a String, JSON array or another JSON object. Depending on the type of object, I need to carry out different operations. Is there any way I can check the type of the object to see if it is a String, JSON object or JSON array?
I tried using typeof and instanceof but both didn't seem to work, as typeof will return an object for both JSON object and array, and instanceof gives an error when I do obj instanceof JSON.
To be more specific, after parsing the JSON into a JS object, is there any way I can check if it is a normal string, or an object with keys and values (from a JSON object), or an array (from a JSON array)?
For example:
JSON
var data = "{'hi':
             {'hello':
               ['hi1','hi2']
             },
            'hey':'words'
           }";

Sample JavaScript
var jsonObj = JSON.parse(data);
var path = ["hi","hello"];

function check(jsonObj, path) {
    var parent = jsonObj;
    for (var i = 0; i < path.length-1; i++) {
        var key = path[i];
        if (parent != undefined) {
            parent = parent[key];
        }
    }
    if (parent != undefined) {
        var endLength = path.length - 1;
        var child = parent[path[endLength]];
        //if child is a string, add some text
        //if child is an object, edit the key/value
        //if child is an array, add a new element
        //if child does not exist, add a new key/value
    }
}

How do I carry out the object checking as shown above?
Comment: [JSON](http://en.wikipedia.org/wiki/JSON) is just a notation stored as a *string*. Are you sure you're not confusing terms?
Comment: change hasn't made it more clear (at leas for me). What if you give example of JSON you're dealing with
Comment: Nope, I updated the question to make it clearer. I guess my main question is what happens after we do a `.parse()` on a JSON string, and how to identify it?
Comment: Updated question with an example. (:
Comment: The real question is: why do you care?
Comment: You cannot know if "level1 was formerly a JSON object". You can only know it is an object *now*.
Comment: @Len: Because based on what it originally was, I need to carry out different operations.
Comment: Your talk of what the object was formerly confuses me. Before you parsed the data, jsonObj.level1 didn't exist. After you parsed it's an object.
Comment: @PeterWilkinson: Ok, it seems that my question is still confusing. I've edited the question again. Hope it helps.
Comment: @WeiHao The whatIsIt method I suggested below should work nicely for you.
Answer: I'd check the constructor attribute.
e.g.
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    if (object === undefined) {
        return "undefined";
    }
    if (object.constructor === stringConstructor) {
        return "String";
    }
    if (object.constructor === arrayConstructor) {
        return "Array";
    }
    if (object.constructor === objectConstructor) {
        return "Object";
    }
    {
        return "don't know";
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];

for (var i=0, len = testSubjects.length; i < len; i++) {
    alert(whatIsIt(testSubjects[i]));
}

Edit: Added a null check and an undefined check.
Comment: `else if` is unnecessary
Comment: So many `if` statements... Use a [`switch`](https://www.w3schools.com/js/js_switch.asp)!
Comment: Is not this the same as using instanceof?
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/instanceof
Comment: @Pereira: JavaScript has some confusing wrinkles.  Try "surely_this_is_a_string" instanceof String.
Comment: `{}.constructor` is causing me to get `ERROR TypeError: Cannot read property 'constructor' of undefined` in my angular application.
Comment: @Minyc510 : Looks like browser behaviour has changed.  Wrapping in brackets seems to fix it.  I've edited the answer to reflect this.
Comment: Nice answer - but absolutely ridiculous that there is no function to do this in JS
Comment: I don't feel that this answers the question. a string is a string, but a JSON object is ... also a string. So in my case, I need to check if any value is JSON before I call JSON.parse, so it doesn't blow up.

My answer would be to use try-catch and just return false in the catch and true otherwise.
Comment: The question has been edited a few times, but the last paragraph still specifically requests determining object type after it has been parsed.
Answer: You can use Array.isArray to check for arrays.  Then typeof obj == 'string', and typeof obj == 'object'.
var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
    if (Array.isArray(p)) return 'array';
    else if (typeof p == 'string') return 'string';
    else if (p != null && typeof p == 'object') return 'object';
    else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));

's' is string'a' is array 'o' is object'i' is other
Comment: Don't forget to take into account that `typeof null === 'object'`
Comment: `[{
  "name":[
    {"key": "any key" }
    ]
}]`

this  is also valid json but its return array by your code.
check this - [fiddle](http://jsfiddle.net/6dhjbtuw/14/)
Comment: If you ̵d̵a̵r̵e̵ ̵t̵o̵ use that function for a `class Test {}`, `typeof` will return `object`, sooo...
Answer: An JSON object is an object. To check whether a type is an object type, evaluate the constructor property.
function isObject(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Object;
}

The same applies to all other types:
function isArray(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Array;
}

function isBoolean(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Boolean;
}

function isFunction(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Function;
}

function isNumber(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Number;
}

function isString(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == String;
}

function isInstanced(obj)
{
    if(obj === undefined || obj === null) { return false; }

    if(isArray(obj)) { return false; }
    if(isBoolean(obj)) { return false; }
    if(isFunction(obj)) { return false; }
    if(isNumber(obj)) { return false; }
    if(isObject(obj)) { return false; }
    if(isString(obj)) { return false; }

    return true;
}

Comment: JSON encoded resource is not an object.  It is a string.  Only after you decode it or in Javascript `JSON.parse()` it does the JSON resource become an object.  Therefore if you test a resource coming from a server to see if it is JSON, it is best to check first for String, then if is a not a `` and then after parsing if it is an object.
Comment: This is easiest way! Worked
Answer: you can also try to parse the data and then check if you got object:
try {
    var testIfJson = JSON.parse(data);
    if (typeof testIfJson == "object"){
        //Json
    } else {
        //Not Json
    }
}
catch {
    return false;
}

Comment: This can cause an "Uncaught SyntaxError" if the data isn't JSON parsable
Answer: If you are trying to check the type of an object after you parse a JSON string, I suggest checking the constructor attribute:
obj.constructor == Array || obj.constructor == String || obj.constructor == Object

This will be a much faster check than typeof or instanceof.
If a JSON library does not return objects constructed with these functions, I would be very suspiciouse of it.
Comment: A much more direct approach. Thanks! =D
Comment: Preferred answer. Where do you get the performance benefit info from?
Comment: @DanielF it was common wisdom back in '12, things are all different now so I don't know if that holds
Answer: The answer by @PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof
function isJson(obj) {
    var t = typeof obj;
    return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}

Answer: You could make your own constructor for JSON parsing:
var JSONObj = function(obj) { $.extend(this, JSON.parse(obj)); }
var test = new JSONObj('{"a": "apple"}');
//{a: "apple"}

Then check instanceof to see if it needed parsing originally
test instanceof JSONObj

Answer: I wrote an npm module to solve this problem. It's available here:
object-types: a module for finding what literal types underly objects
Install
  npm install --save object-types

Usage
const objectTypes = require('object-types');

objectTypes({});
//=> 'object'

objectTypes([]);
//=> 'array'

objectTypes(new Object(true));
//=> 'boolean'

Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types
Answer: Try, Catch block will help you to solve this
Make a function
function IsJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

Example:
console.log(IsJson('abc')) // false
console.log(IsJson('[{"type":"email","detail":"email@example.com"}]')) // true

Answer: Why not check Number - a bit shorter and works in IE/Chrome/FF/node.js

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    else if (object === undefined) {
        return "undefined";
    }
    if (object.constructor.name) {
            return object.constructor.name;
    }
    else { // last chance 4 IE: "\nfunction Number() {\n    [native code]\n}\n" / node.js: "function String() { [native code] }"
        var name = object.constructor.toString().split(' ');
        if (name && name.length > 1) {
            name = name[1];
            return name.substr(0, name.indexOf('('));
        }
        else { // unreachable now(?)
            return "don't know";
        }
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
// Test all options
console.log(whatIsIt(null));
console.log(whatIsIt());
for (var i=0, len = testSubjects.length; i < len; i++) {
    console.log(whatIsIt(testSubjects[i]));
}
Answer: I combine the typeof operator with a check of the constructor attribute (by Peter):
var typeOf = function(object) {
    var firstShot = typeof object;
    if (firstShot !== 'object') {
        return firstShot;
    }
    else if (object.constructor === [].constructor) {
        return 'array';
    }
    else if (object.constructor === {}.constructor) {
        return 'object';
    }
    else if (object === null) {
        return 'null';
    }
    else {
        return 'don\'t know';
    }
}

// Test
var testSubjects = [true, false, 1, 2.3, 'string', [4,5,6], {foo: 'bar'}, null, undefined];

console.log(['typeOf()', 'input parameter'].join('\t'))
console.log(new Array(28).join('-'));
testSubjects.map(function(testSubject){
    console.log([typeOf(testSubject), JSON.stringify(testSubject)].join('\t\t'));
});

Result:
typeOf()    input parameter
---------------------------
boolean     true
boolean     false
number      1
number      2.3
string      "string"
array       [4,5,6]
object      {"foo":"bar"}
null        null
undefined

Answer: I know this is a very old question with good answers. However, it seems that it's still possible to add my 2¢ to it.
Assuming that you're trying to test not a JSON object itself but a String that is formatted as a JSON (which seems to be the case in your var data), you could use the following function that returns a boolean (is or is not a 'JSON'):
function isJsonString( jsonString ) {

  // This function below ('printError') can be used to print details about the error, if any.
  // Please, refer to the original article (see the end of this post)
  // for more details. I suppressed details to keep the code clean.
  //
  let printError = function(error, explicit) {
  console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
  }

  try {
      JSON.parse( jsonString );
      return true; // It's a valid JSON format
  } catch (e) {
      return false; // It's not a valid JSON format
  }

}

Here are some examples of using the function above:
console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );

console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );

console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );

console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );

console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );

console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );

console.log('\n7 -----------------');
j = '[{"a":1, "b":   2}, {"c":3}]';
console.log( j, isJsonString(j) );

When you run the code above, you will get the following results:
1 -----------------
abc false

2 -----------------
{"abc": "def"} true

3 -----------------
{"abc": "def} false

4 -----------------
{} true

5 -----------------
[{}] true

6 -----------------
[{},] false

7 -----------------
[{"a":1, "b":   2}, {"c":3}] true

Please, try the snippet below and let us know if this works for you. :)
IMPORTANT: the function presented in this post was adapted from https://airbrake.io/blog/javascript-error-handling/syntaxerror-json-parse-bad-parsing where you can find more and interesting details about the JSON.parse() function.

function isJsonString( jsonString ) {

  let printError = function(error, explicit) {
  console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
  }

  try {
      JSON.parse( jsonString );
      return true; // It's a valid JSON format
  } catch (e) {
      return false; // It's not a valid JSON format
  }

}

console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );

console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );

console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );

console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );

console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );

console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );

console.log('\n7 -----------------');
j = '[{"a":1, "b":   2}, {"c":3}]';
console.log( j, isJsonString(j) );
Answer: Try this
if ( typeof is_json != "function" )
function is_json( _obj )
{
    var _has_keys = 0 ;
    for( var _pr in _obj )
    {
        if ( _obj.hasOwnProperty( _pr ) && !( /^\d+$/.test( _pr ) ) )
        {
           _has_keys = 1 ;
           break ;
        }
    }

    return ( _has_keys && _obj.constructor == Object && _obj.constructor != Array ) ? 1 : 0 ;
}

It works for the example below
var _a = { "name" : "me",
       "surname" : "I",
       "nickname" : {
                      "first" : "wow",
                      "second" : "super",
                      "morelevel" : {
                                      "3level1" : 1,
                                      "3level2" : 2,
                                      "3level3" : 3
                                    }
                    }
     } ;

var _b = [ "name", "surname", "nickname" ] ;
var _c = "abcdefg" ;

console.log( is_json( _a ) );
console.log( is_json( _b ) );
console.log( is_json( _c ) );

Answer: Based on @Martin Wantke answer, but with some recommended improvements/adjusts...
// NOTE: Check JavaScript type. By Questor
function getJSType(valToChk) {

    function isUndefined(valToChk) { return valToChk === undefined; }
    function isNull(valToChk) { return valToChk === null; }
    function isArray(valToChk) { return valToChk.constructor == Array; }
    function isBoolean(valToChk) { return valToChk.constructor == Boolean; }
    function isFunction(valToChk) { return valToChk.constructor == Function; }
    function isNumber(valToChk) { return valToChk.constructor == Number; }
    function isString(valToChk) { return valToChk.constructor == String; }
    function isObject(valToChk) { return valToChk.constructor == Object; }

    if(isUndefined(valToChk)) { return "undefined"; }
    if(isNull(valToChk)) { return "null"; }
    if(isArray(valToChk)) { return "array"; }
    if(isBoolean(valToChk)) { return "boolean"; }
    if(isFunction(valToChk)) { return "function"; }
    if(isNumber(valToChk)) { return "number"; }
    if(isString(valToChk)) { return "string"; }
    if(isObject(valToChk)) { return "object"; }

}

NOTE: I found this approach very didactic, so I submitted this answer.
Answer: Peter's answer with an additional check! Of course, not 100% guaranteed!
var isJson = false;
outPutValue = ""
var objectConstructor = {}.constructor;
if(jsonToCheck.constructor === objectConstructor){
    outPutValue = JSON.stringify(jsonToCheck);
    try{
            JSON.parse(outPutValue);
            isJson = true;
    }catch(err){
            isJson = false;
    }
}

if(isJson){
    alert("Is json |" + JSON.stringify(jsonToCheck) + "|");
}else{
    alert("Is other!");
}

Answer: I have a pretty lazy answer to this, which will not throw an error if you try to parse a string/other values.
const checkForJson = (value) => {
    if (typeof value !== "string") return false;

    return value[0] === "{" && value[value.length - 1] === "}";
}

You can use this to check the value of your keys while you make some recursive func; sorry if this doesn't answer the question completely
Ofc this isn't the most elegant solution and will fail when a string actually starts with "{" and ends with "}" although those use cases would be rare, and if you really wanted, you can check for a presence of quotes or other nonsense... anyway, use at your own discretion.
TLDR: it's not bulletproof, but it's simple and works for the vast majority of use cases.
Comment: It will also not work if there is an array inside. Try with `JSON.parse(JSON.stringify(['a','b','c',1,2,3])))`
Answer: lodash is also the best bet to check these things.
function Foo() {
  this.a = 1;
}

_.isPlainObject(new Foo);
// => false

_.isPlainObject([1, 2, 3]);
// => false

_.isPlainObject({ 'x': 0, 'y': 0 });
// => true

_.isPlainObject(Object.create(null));
// => true

https://www.npmjs.com/package/lodash
https://lodash.com/docs/#isPlainObject
Answer: Quickly check for a JSON structure using lodash-contrib:
const _ = require('lodash-contrib');

_.isJSON('{"car": "ferarri"}'); //true for stringified
_.isJSON({car: "ferarri"}); //true

Usage guide: this blog entry
Answer: try this dirty way
 ('' + obj).includes('{')


kubuntu unkillable font management settings tool

Question: Running kubuntu 16.04.1 fully up-to-date.
I brought up the font management tool (System Settings > Fonts > Font Management) and tried uninstalling a few fonts. The "Updating font configuration. Please wait..." progress bar was stuck at 100% for several minutes.
sudo strace -f -p $(ps ax | grep fontinst | grep -v grep | cut -c 1-5)  shows that it's stuck in a loop, lstat-ing a couple of hundred font files. It pauses for a few seconds, then stats the font directories and lstats a bunch of font files (see https://gist.github.com/jayeye/bb5ef45801c6b7ae1fbdea8917d7ad1f), and the process repeats.
If I kill the process, another one starts up doing the same. Neither the cancel button nor hitting x on the window frame kills it.
Help?
Comment: Sounds like a bug, no. Did it uninstall the fonts; perhaps it doesn't have permissions to delete them, attempts delete, fails, loops? Does `sudo kcmshell5 fontinst` work or get better output?
Answer: I'm running into this as well.  I don't know what causes it, but I usually just kill it with:
sudo kill -9 `pgrep systemsettings`


Recursive function to add all the digits

Question:
I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)
I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?
def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10

Answer: The problem is the line
return digit_sum(n//10) + n%10

because if the sum of the digits of n//10 and the last digit becomes a number of two digits no one is reducing it. A possible solution is:
return digit_sum(digit_sum(n//10) + n%10)

Answer: You can use your approach with minor modifications:
def digit_sum(n):
    if n<10:
         return n
    return (digit_sum(n//10) + n%10 - 1) % 9 + 1

Or ignoring the recursion requirement:
def digit_sum(n):
    return n if n<10 else (n-1) % 9 + 1

Or even shorter (thanks @thanasisp):
def digit_sum(n):
    return n and n%9 or 9

Comment: Simpler than mine, & passes the tests :)
Comment: @ReblochonMasque The recursion bit feels artificial though ;-)
Comment: You could make the second one shorter: `return n%9 or 9` (n>0)
Comment: @thanasisp Or with zero check: `return n and n%9 or 9`
Answer: Try this:
def digit_sum(n):
    """ Recursively add the digits of a positive integer until the sum
    becomes a single digit. Return the sum. """

    sum_of_digits = sum(int(digit) for digit in str(n))
    if sum_of_digits < 10:
        return sum_of_digits
    else:
        return digit_sum(sum_of_digits)

>>> digit_sum(38)
2

Answer: You can do the following:
def digit_sum(n):
    if n < 10:
        return n
    return digit_sum(sum(map(int, str(n))))

Answer: Here is a recursive solution that does not cast to str:
def digit_sum(n):
    def _digit_sum(n):
        if n == 0:
            return n
        return n % 10 + digit_sum(n//10)
    s = _digit_sum(n)
    if s > 9:
        return digit_sum(s)
    return s

some tests:
def test_digit_sum():
    n = 2
    print(n, digit_sum(n))
    assert digit_sum(n) == 2
    n=10
    print(n, digit_sum(n))
    assert digit_sum(n) == 1
    n=143
    print(n, digit_sum(n))
    assert digit_sum(n) == 8
    n=1434
    print(n, digit_sum(n))
    assert digit_sum(n) == 3
    n=143488837772
    print(n, digit_sum(n))
    assert digit_sum(n) == 8
    print("***all tests pass***")

test_digit_sum()

output:
2 2
10 1
143 8
1434 3
143488837772 8
***all tests pass***


Failed to upgrade to Ubuntu 11.10

Question: This error prevents the system from upgrading to a newer version of Ubuntu, what is causing it?
<code> W: Failed to fetch http://extras.ubuntu.com/ubuntu/dists/natty/main/source/Sources      404  Not Found

 W: Failed to fetch http://extras.ubuntu.com/ubuntu/dists/natty/main/binary-amd64/Packages  404  Not Found

 E: Some index files failed to download. They have been ignored, or old ones used instead.
</code>
Since I got the warning message that this release is not supported anymore, should I download and install Ubuntu 12.10 directly from Ubuntu's site instead?
Comment: The actual error is missing. Please run the following command in a terminal and provide the full output it produces: `sudo apt-get update`
Comment: @DennisKaarsemaker: Done. Thank you for your help.
Answer: Fortunately it's only the extras repo that's not working. You can disable that in the software sources application or by editing the relevant file in <code>/etc/apt</code>. After that, the upgrade to 11.10 should work. It's also advisable to upgrade to 12.04 LTS after upgrading to 11.10 as 11.10 is only supported for a few more months and 12.04 LTS for at least 2 4 (see below) more years (and a few months).
Comment: 12.04 LTS will be supported until April 2017. https://wiki.ubuntu.com/Releases
Comment: Thank you for your answer, could you elaborate on how to disable it?
Comment: Each repository is listed in either /etc/apt/sources.list or in a file in /etc/apt/sources.list.d - to disable the usage of a repository, open the file in a text editor as root (`gksudo gedit filename_goes_here`) and place a `#` in front of the line you want to disable. Any line that mentions extras.ubuntu.com should be disabled.
Comment: @fabricator4 - ah, must have missed that change in release policy, thanks for the addition.

Failed to upgrade to Ubuntu 11.10


Existence of right hand limit

Question: I know that $\frac{\sin x} {x}$ tends to $1$ as $x \to 0$. Then why it's said that $\frac{\sin [x]} {[x]}$ is not defined, as $x \to 0^+$. But it exists and is equal to 1. x belongs to (-1,1).
([x] is greatest integer less than or equal to x.)
I don't understand why they say, it's not defined.
Does this limit exist and equal to 1?
Comment: Assuming that $[x]$ denotes the greatest integer function (i.e., floor function), for $0 \leq x < 1$, we have $[x] = 0$. So it involves division by zero, which renders the expression $\sin[x]/[x]$ undefined near $x = 0$ from the right.
Comment: How is $[x]$ defined?
Comment: So , if [x]=0 , then sin[x]/[x] is 0/0 form. And we can use L'HOSPITAL'S rule that results 1.
Comment: So, can I say that the right hand limit exists.
Comment: @user634631 You use l'Hopital rule to compute a limit, not to define a function.
Comment: I've got that point. Ok
Answer: By left,
$$\forall x\in(-1,0)\;\;\; \sin(\lfloor x\rfloor)=\sin(-1)$$
so, $$\lim_{x\to 0^-} \frac{\sin(\lfloor x\rfloor)}{\lfloor x\rfloor} =\sin(1)$$
By right,
$$\forall x\in(0,1) \;\;\; \lfloor x\rfloor =0=\sin(\lfloor x\rfloor)$$
so, the function $x\mapsto \frac{\sin(\lfloor x\rfloor)}{\lfloor x\rfloor}=\frac 00 $ is not well defined on the right of $ 0 $ and we cannot speak about right limit

Existence of right hand limit


Pollable StreamListener or MessageSource for RabbitMQ Queue

Question: I have Spring Cloud Stream Rabbit project that sends messages to an rabbit exchange errorEx in case of errors in the flow.
I want to periodically(once in 5 mins) listen from the queue and process it.
Is there any way I can have a Pollable @StreamListener?
OR Can I configure a rabbitMQ org.springframework.integration.core.MessageSource so I can build a IntegrationFlow with a Poller?
Answer: Spring Integration AMQP doesn't provide a pollable adapter. @StreamListener only supports Subscribable channels.
You could use a custom MessageSource that uses a RabbitTemplate receive() operation to fetch messages.
Or, you could use the message-driven adapter and stop()/start() it as needed.
Comment: Used a `CustomMessageSource` where I was able to do `rabbitTemplate.receive()`. Then used it with poller in a IntegrationFlow. `IntegrationFlows.from(customMessageSource, c -> c.poller(Pollers.fixedDelay(10000, 10000).maxMessagesPerPoll(1))) .channel(retryChannel()).get()`


Getting out of a function, with reference, an object of a type with no default constructor

Question: For example
bool read(Input &input);

Input input; //error
bool success = read(input);

will be an error because Input has no default constructor.
Is there any trickery I can use to get the Input object out of the function in this case? I imagine there must be some unique_ptr trickery available to me, but I'm not sure exactly how. Feel free to suggest other methods.
Please suggest with example how the read function could look.
I would rather not create a (meaningless) default constructor for Input just for this purpose, and note that this is just a silly example, so don't attach any special meaning to the words "Input", "read", etc. :)
Comment: Have `read()` return an `Input` and `throw` an exception on failure?
Comment: why not do `Input read();` ?
Comment: Because in my case, the return type will be important, and even "false" is not invalid enough to be an exception.
Comment: pass a pointer to Input
Comment: Use a constructor that `Input` **does** have.
Answer: bool read(unique_ptr<Input> &input)  // read asume input is disposable/empty
{    ....
  input.reset(new Input( a,d,c ) );
     ....
 }

....
unique_ptr<Input> input;      //error ?
bool success = read(input);
if (input)
  if (succes)
     input->X();
  else
     input->Y();

Comment: Yes I imagine something like this, but the problem is that you can't reassign to the input pointer within the read function. I guess I could do "input.reset(new whatever)", but does that sound right?
Comment: A `unique_ptr` is enough in itself to signal "no object", so i do not see the purpose in passing it by reference with a `bool` function result. Also, dynamic allocation is, relative to ordinary C++ stack allocation, extremely inefficient. So what compelling argument is there for taking on that verbosity, obscurity and inefficiency?
Comment: @ Cheers and hth. - Alf : this is just a silly example, so don't attach any special meaning to the words "Input", "read", etc. ... Because in my case, the return type will be important, and even "false" is not invalid
Answer: If you are in pre-C+11 world, there is a workaround by use of malloc:
bool read(Input &input); // keep the function read intact

Input* input = static_cast<Input*>(malloc(sizeof(Input))); // bypass constructor
bool success = read(*input);
...
free(input); // don't forget to free input later

Answer: From the comments, it appears that your problem is to design a function that

can fail (and if so should signal that to caller),
but if not, produces a value of a type without a default cconstructor

The first point is easy: use exceptions.
The second point is also easy: use the function return value feature.
I.e.,
Object foo()
{
    if( "didna wrok" )
    {
        throw std::runtime_error( "foo: I failed, miserably" );
    }

    return Object( arg1, arg2, arg3 );
}

Now there also many other ways to do this, but the above is the most natural, directly using the language features that are intended to support and fully solve these aspects.
Answer: unique_ptr<Input> input_ptr = read();

where read() is defined as:
unique_ptr<Input> read()
{
    .
    .
    .
    return unique_ptr<Input>(new Input(x,y,z));
}

Comment: A more efficient and safe variant is to use an implementation of Barton and Nackman's `Fallible` class, such as `boost::optional`. It's also trivial to implement (in a few minutes) for POD inner type. I didn't suggest that in my answer  --  I merely stated that there are many more possibilities  --  because evidently the OP is learning the basics of C++.


[SeleniumRC]Cannot call method 'indexOf' of undefined in Chrome

Question: Please help me to fix this issue (Cannot call method 'indexOf' of undefined in Chrome). I'm running selenium using .NET framework and I don't see any overload method in selenium.start to pass "--disable-web-security".
My selenium server is selenium-server-standalone-2.0b3.jar.
Any help will be greatly appreciated.
Thanks,
Pritam
Answer: -disable-web-security is a browser configuration and not a selenium server option. In Java, you can declare it as follows -
BrowserConfigurationOptions bco = new BrowserConfigurationOptions();
bco.setCommandLineFlags("-disable-web-security");

Do this prior to initializing the Selenium server.


Updating ng-template from child component

Question: I am using ng-template for passing content to Child Component, but I am looking to get specific value of selected item from the child component
I have a grand child component too, the value is emitted from the Grand Child component to Child component and then to Parent component.
Although I can get the selected value, but it renders same value for complete ng-template
For Example : If I click on last div, all of the Selected values becomes "3"

You can have much better idea checking below stackblitz
https://stackblitz.com/edit/angular-rfvkoj
EDIT : how can I have it render specific selected values ?
Answer: It is working as intended.  It renders the same value because you are rendering {{selected}} in every iteration of the template, and selected is set to whatever most recent value is emitted from ChildComponent.  What did you expect it to render?
As an aside, it is a poor pattern to use @Input to send data through multiple levels, from parent to child to grand-child.  This quickly becomes difficult to manage.  Even your very small code sample is already difficult to follow.
I suggest instead that you use a shared service, provided at the parent level
@Component({
  ...
  providers: [MyService]
})
export class ParentComponent {
  ...
}

You can then inject that service in parent and grand-child, and use the service to keep track of state.


Change format to hh:mm:sss

Question: Can I adapt this formula to make the result into hh:mm:ss format instead of just a raw number?
Get hours from schedule
    =ARRAYFORMULA(
      SUM(
       IFERROR(
        IF(
         --REGEXEXTRACT(A2:G2,"- (\d+:\d+)")<(--REGEXEXTRACT(A2:G2,"^(\d+:\d+)")),
          1+REGEXEXTRACT(A2:G2,"- (\d+:\d+)")-
          REGEXEXTRACT(A2:G2,"^(\d+:\d+)"),
          REGEXEXTRACT(A2:G2,"- (\d+:\d+)")-
          REGEXEXTRACT(A2:G2,"^(\d+:\d+)")))*
       24))

Answer: try:
=ARRAYFORMULA(TEXT(SUM(IFERROR(IF(
 --REGEXEXTRACT(A2:G2,"- (\d+:\d+)")<(
 --REGEXEXTRACT(A2:G2,"^(\d+:\d+)")),
 1+REGEXEXTRACT(A2:G2,"- (\d+:\d+)")-
   REGEXEXTRACT(A2:G2,"^(\d+:\d+)"),
   REGEXEXTRACT(A2:G2,"- (\d+:\d+)")-
   REGEXEXTRACT(A2:G2,"^(\d+:\d+)")))*24), "[hh]:mm:ss"))

Comment: I get 00:00:00 instead of the actual number
Comment: @mau can you share a copy of your sheet?
Comment: I cant since I have sensitive information but I posted a ss of the example
Comment: @mau hard to tell for sure... try `hh:mm:ss` instead of `[hh]:mm:ss`
Comment: I've got the same result
Answer: Suggestion
Based on your question & on your previous post, you want to sum up the time from range A2:G2 OR AR2:AX2 (as seen on your sample screenshot) in hh:mm:ss format. Perhaps you can try this tweaked function below:
=ARRAYFORMULA(TEXT(SUM(IFERROR(TIMEVALUE(TRANSPOSE(
{
ARRAYFORMULA(IFNA(REGEXEXTRACT(AR2:AX2,"- (\d+:\d+)"),0)),
ARRAYFORMULA(IFNA(REGEXEXTRACT(AR2:AX2,"^(\d+:\d+)"),0))
}
)))), "[hh]:mm:ss"))

This function was derived from an answer on this quite similar post:

Demonstration

Change format to hh:mm:sss


solving project euler #4 with c++

Question: Q.A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
this is my code .it worked for 2 digit problem and gave 9009 as answer but it is not working for 3 digit number part.
<code>#include <iostream>
using namespace std ;
bool ispallin(int n)
{
int  reverse = 0, temp;
temp = n;

 while (temp != 0)
 {
  reverse = reverse * 10;
  reverse = reverse + temp%10;
  temp    = temp/10;
  }

  if (n == reverse)
  return true;
  else
  return false;

}
 int main() {
int a[999*999]={0},i,j,no;//0 implies no. at i th position is pallindrome
for(i=100;i<1000;i++)
{
for(j=100;j<1000;j++)
{
    if(a[i*j]==0)//no. is pallin
    {
         if(ispallin(i*j))
         no=i*j;

        else a[i*j]=1;//no. at this pos is not pallindrome
}
 }

}
cout<<no;
return 0;
}
</code>
Comment: what do you mean with "it is not working"?
Comment: Not providing me with the correct Answer
Answer: your code is very nice, i would add a little bit more comments or maybe meaningful names to the functions but it is good code, the answer isn't what you were looking for because you never made sure that the result is the highest there is.
maybe 700*700 would be a palindrome but then 701*600 would also be a palindrome, i your case once 'i' is bigger it will overwrite the result, even if the polindrom is a bigger one.

solving project euler #4 with c++


CSS- How to align background image over bottom border line? Jsfiddle included

Question: I have an image I am trying to display over the top of a bottom border, but it is being arranged behind the bottom border element (in this example, named "divider"), and I can't get it to align correctly.
I would like the image to be displayed in the middle of the the border element and over the top of it. Vertically, I am trying to get the 1px line on the left and right side of the image to align with the 1px border to appear as if it is one element.
Here is the code:
.divider {
border-bottom: 1px solid #c3c3c3;
clear: both;
display: block;
margin-bottom: 20px;
padding-top: 20px;
width: 100%;
}

.sidearrow {
background: url(http://s16.postimage.org/sbf7v9n75/sidearrow.png) 50% 14px no-repeat;
width: 100%;
height: 25px;
}

Here is some content above

Here is some content below

And the jsfiddle: http://jsfiddle.net/F5xjx/2/
Any ideas how to get this to work? Thanks in advance.
Comment: can you post the screenshot of your expected result exactly what you want..............
Answer: Not entirely sure what you want, but is this the effect you're going for?
.divider {
    border-bottom: 1px solid #c3c3c3;
    clear: both;
    display: block;
    margin-bottom: 20px;
    padding-top: 20px;
    width: 100%;
}

.sidearrow {
    background: url("http://s16.postimage.org/sbf7v9n75/sidearrow.png") no-repeat scroll center top transparent;
    width: 100%;
    height: 25px;
}

http://jsfiddle.net/nottrobin/gbrcB/1/
Comment: The arrow image is still aligning itself behind the bottom border of .divider.
Answer: Not sure if this is what you are after, but the padding is simply not needed:
http://jsbin.com/ibaveg/1/


What is the best way to let the user change the language in a windows forms application

Question: Situaltion:

I have a windows forms application which is currently only available in german for the end user
There is an existing userbase which gets auto updates
The application is already translated to english in our dev branch
The apps main window is a ribbon form

Now I want to allow the user to switch between german and english (more languages will follow) and I am thinking on how to implement the option to change the language.
I thought about a ribbon group with little flags for every language available.
The flags are greyed out except from the current selected.
The ribbon section shows up to six icons and more are shown only if you extend the section (ribbon standard)
Of course the current selected languge, the current users local are always shown
This seems to be a simple approach to me but than again I have never seen something similar in a windows forms application so I am wondering if this is a good idea or if I should use a different concept.
Comment: Which version of windows are you running?
Comment: Windows XP to Windows 8.1 are all supported.
Answer: Using a dropdown of languages positioned appropriately on the form of course would be ideal. One - you can just add more languages to the dropdown in the future. Two, you can display the language in the dropdown in native script. Three, assuming you add 20 languages in the future, scroll on the dropdown won't be an issue, whereas content would scroll inside the ribbon.
Answer: It can also be done this way
A language icon could be placed somewhere on the top bar, On mouse hover (or on click) a language drop-down or a small div to place the other language flags. When the user selects a particular language flag, it replaces the previous one.This would save space on the page and is also user friendly.


Modify back button href in jquery mobile

Question: I need to change the back button link in jQuery mobile depending on some circumstances. But the following approach is not working.
$.mobile.activePage.find('a[data-rel="back"]').attr('href',"#newPage");

In the console, its showing the new url but its not working. Also, can anyone tell the correct way to modify back button history in jQuery mobile?
Comment: in what event do u use this? `pageinit`?
Comment: http://stackoverflow.com/a/17045415/1771795 hope this helps.
Answer:  Method 1
You'll have to remove data-rel from the a tag if you want to redirect when you click on it because data-rel takes more priority that href. Here's how i got it to work.

I have three pages, #mypage1, animals, page3
On the pagebeforeshow of the second page, which has a back button, I put this code in, in which im changing the href to re-direct to #page3 :
$(document).on("pagebeforeshow", "#animals", function (e) {
   var $a = $.mobile.activePage.find('a[data-rel=back]');
   $a.attr("href", "#page3");
   $a.removeAttr("data-rel");
});

Beware that pageinit wont work in this case, because the activePage object will still point to older page.
Demo : http://jsfiddle.net/hungerpain/rDtKL/2/

 Method 2 (a more better way)
Bind this event on the a with data-rel set to it. You can bind this in pageinit :
$(document).on("pageinit", "#animals", function (e) {
    $(this).on("click", "[data-rel=back]", function (e) {
        e.stopImmediatePropagation();
        e.preventDefault();
        $.mobile.changePage("#page3");
    });
});

Note that you must use both stopImmediatePropagation and preventDefault to make this work onclick.
Demo : http://jsfiddle.net/hungerpain/rDtKL/3/
 Method 3 (the most clean way there is)
Add that button to your header programmatically, so that you can decide whether you need that data-rel attribute.
Answer: You can add an id="backchange" to your button and change the text in jQuery :
$("#backchange .ui-btn-text").text("nextext");


How can I anchor deck tension ties to solid brick?

Question: I am currently repairing a deck that is several years old and noticed that it does not have deck tension ties installed.
The ledger is hung on a solid brick wall (8" thick, two courses). The brick wall is the primary structure of the home (~100 years old).
The local permitting office indicated that 4 ties are required for the deck, each installed to achieve 750lbs of tension, with a tie no more than 2 feet from each end.
The wood connection is easy to find (e.g., Simpson), but I'm having trouble finding a masonry fastener that is approved for wet exterior applications and can develop the full 750lbs pull-out strength in brick.
Is there a standard or approved way to attach tension connections to solid brick?
Comment: I'd be surprised if that would pass inspection anyway--brick isn't usually considered structural. It's essentially siding in modern homes. You'd have to anchor through to the actual wall. Maybe revise to tell us more about your home's construction and age.
Comment: @r13 I think you misunderstood.  I read it as the deck _is currently_ tied (hung) on the wall, therefore, it needs lateral stabilization.  Regardless though, even free-standing would likely require the ties unless it was very well cross-braced.
Comment: I am not clear on why the local requires the deck be tied to the main building. Usually, the deck can be stand-alone as far as it is structurally stable. If insisted by the inspector, you should consult with a structural engineer to provide a solution. I'll look into Hilti Anchors or using thru-bolts.
Comment: @DonBoitnott I knew it is attached.  But, you are correct, the code now requires "positive attachment" to tie the deck to the building.
Comment: @isherwood the brick is the structure of the home - I've revised - thank you!
Answer: Based on 2015 International Building Code:

See P.17 & 18 Prescriptive Residential Wood Deck Construction Guide
Comment: Yes, I am familiar with those code requirements - I am looking to satisfy the condition of attaching directly to masonry. The document you linked directs "use expansion anchors or epoxy anchors when fastening to concrete or masonry" - I am looking for an appropriate anchor.
Comment: As suggested, check out proper anchors and adhesives from Hilti.com. They provide expansion anchor as well, but I doubt it would work.
Comment: Simpson (Strong-Tie) has anchors for masonry works too.
Comment: You can do the research to get an idea of the availability of materials. However, I still think it is the engineer's job to provide the connection details and specify the type of anchorage for your application.
Comment: This is my original comment to your question that you may have missed: "I am not clear on why the local requires the deck be tied to the main building. Usually, the deck can be stand-alone as far as it is structurally stable. If insisted by the inspector, you should consult with a structural engineer to provide a solution. I'll look into Hilti Anchors or using thru-bolts. – r13 6 hours ago" (see the Comment block below the question box)
Comment: Here is the reason why it is an engineer's job. At first glance, it seems Hilti Hit-HY270 anchor system fits the work over the 8" brick wall. But further reading on its technical report, it says "the existing masonry wall must have a minimum nominal thickness of 13 thickness (3 wythes) with the shear strength of in-place mortar no less than 50 psi." We can make a dangerous mistake by look at the strength charts only.
Answer: I think you are looking for something like Simpson RP6:
https://www.google.com/search?q=rp6+simpson+brick+wall&rlz=1CDGOYI_enUS900US900&hl=en-US&sxsrf=ALeKk03NVqTp7MITyNhOK7p85QYuac7ldg%3A1623188036405&ei=ROK_YOelGLyLwbkPo5u8kAQ&oq=rp6+simpson+brick+wall&gs_lcp=ChNtb2JpbGUtZ3dzLXdpei1zZXJwEAMyBQghEKABMgUIIRCrAjoECAAQRzoGCAAQFhAeOgcIIRAKEKABUO0zWJKcAWCZoQFoAHABeACAAaoCiAGhDpIBBjAuMTAuMZgBAKABAcgBCMABAQ&sclient=mobile-gws-wiz-serp#imgrc=-nlob-a5gBv1tM
Comment: Why is R13 is citing the code requirement and NOT posting an answer.


Does this light switch wiring seem wrong?

Question: I'm trying to replace this regular light switch with a dimmer. After I open the cover, there are 2 groups of wires from the wall. I don't know why the white wires are not used, but this is the original wiring.
Left Group

2 white (not used)
1 copper for ground (connected to right group ground)
2 black

letter B in the pic, plugged in to the bottom of switch
letter C in the pic, screwed to the bottom of the switch
Right Group

1 white (not used)
1 copper for ground (connected to left group ground)
1 black, letter A in the pic, plugged in to the top of switch

Now my question is how do I connect to the dimmer below?
I know the green wire goes to the ground copper, and the red with a sticker should not be used since I'm not doing a 3-way.
Which one should I connect the black and red with?
My educated guess is:

connect A with dimmer red wire
connect B and C with dimmer black wire
connect ground copper with dimmer green wire

Does that sound right?
Comment: The whites are absolutely being used. They just don't connect to the switch.
Answer: Your original switch was a 50 cent cheapie. It had both screw terminals and backstabs. In your photo, the "B" backstab is internally connected to the yellow screw. So the installer is using the dual connections to splice together "B" and "C", as well as connect them to that leg of the switch.
It's very common to bring power (always-hot+ground) to a switch, and then daisy-chain off of it to power another switch or outlet.  Most likely, that accounts for hots B and C.
So "A" must be the switched-hot to the light.  I prefer to mark wires with colored electrical tape to identify them by function, and the preferred color for switched-hot is red. I would mark "A" red.
The preferred color for always-hot is black. So B and C stay black.
Your smart switch also uses those same preferred colors. Join em. Done.
"That was easy"
Comment: My new switch is a LED dimmer but it's not a smart switch. So I connected A to dimmer's Red, B and C to dimmer's Black, and copper ground to dimmer's Green. But, sometimes the light doesn't turn on or have a 2 to 3 second delay if the dimmer was on a low position. No delay if position is on high. I heard dimmer can introduce a delay, but isn't that too long?
Comment: The dimming on the switch is adjustable, so I adjusted it, but now the dimming range is less, but it seems to get rid of the random delay.
Comment: That's all too utterly normal for LED dimmers and LED lights.
Comment: @RayCheng Yeah, look into the tech of how *triac dimmers* work.  It will become obvious that the design was optimized for "cheap" and optimized exclusively for how *incandescent* bulbs behave. It was very imprecise to begin with. It doesn't work on LEDs.  "Dimmable" LEDs are specifically designed to endure it, analyze the waveform, and give the brightness level the triac dimmer seems to be asking for.  It's a black art. There are other technologies designed specifically for LED dimming, but they require different wiring schemes.


setting an array element with a sequence error in scikit learn GradientBoostingClassifier

Question: Here is my code, anyone have any ideas what is wrong? The error happens when I call fit,
import pandas as pd
import numpy as np
from sklearn.ensemble import (RandomTreesEmbedding, RandomForestClassifier,
                              GradientBoostingClassifier)
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer

n_estimators = 10
d = {'f1': [1, 2], 'f2': ['foo goo', 'goo zoo'], 'target':[0, 1]}
df = pd.DataFrame(data=d)
X_train, X_test, y_train, y_test = train_test_split(df, df['target'], test_size=0.1)

X_train['f2'] = CountVectorizer().fit_transform(X_train['f2'])
X_test['f2'] = CountVectorizer().fit_transform(X_test['f2'])

grd = GradientBoostingClassifier(n_estimators=n_estimator, max_depth=10)
grd.fit(X_train.values, y_train.values)

Comment: I think the problems is in `CountVectorizer`. That return a Sparse matrix (then you are mixing the 2 types of matrix) Try with convert it `.to dense()`.
Comment: @Lucas, it works! cool!
Answer: The problem is with CountVectorizer:
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

d = {'f1': [1, 2], 'f2': ['foo goo', 'goo zoo'], 'target':[0, 1]}
df = pd.DataFrame(data=d)
df['f2'] = CountVectorizer().fit_transform(df['f2'])

df.values is:
array([[1,
        <2x3 sparse matrix of type '<class 'numpy.int64'>'
    with 4 stored elements in Compressed Sparse Row format>,
        0],
       [2,
        <2x3 sparse matrix of type '<class 'numpy.int64'>'
    with 4 stored elements in Compressed Sparse Row format>,
        1]], dtype=object)

We can see that we are mixing sparse matrix with dense matrix. You can transform it to dense with: todense():
dense_count = CountVectorizer().fit_transform(df['f2']).todense()

where dense_count is something like:
matrix([[1, 1, 0],
        [0, 1, 1]], dtype=int64)


How to run ShellCommandActivity on my own EC2 instance?

Question: I am trying to run a simple command to test a ShellCommandActivity with Data Pipeline from AWS.
>>> /usr/bin/python /home/ubuntu/script.py

That script should create a file on a S3, I know I could create a S3 file using the same Data Pipeline, but I want to test how to execute the script.
When I execute the pipeline I get this error:

/usr/bin/python: can't open file '/home/ubuntu/script.py': [Errno 2] No such file or directory

This is because AWS DP create a complete new EC2 instance when it runs, and my script.py is not there.
I created a Resource EC2

But there is not a field to define my own EC2 instance. How can I do this? Or maybe there some other way to approach this.
Thanks.
Answer: One workaround is directly execute script.py
like
"command": "script.py"
Be sure your script.py with header
#!/usr/bin/env python

Comment: `script.py` does not exists in the created EC2.
Answer: The script has to be placed on S3 and provide the path (//S3:....) in the script uri of the ShellCommandActivity


How represent in printf a variable type unsigned long

Question: To print a var of int in printf you have to %i or %d but what should i add for an unsigned long
Comment: http://en.cppreference.com/w/cpp/io/c/fprintf
Answer: %lu is the correct format specifier for an unsigned long
Answer: %lu is the correct format for unsigned long.


How do I reorder the Nautilus right-click menu?

Question: Is it possible to reorder the default items in the Nautilus context menu?
e.g. when I right-click on an archive, the top item is "Open with Archive Manager" but way down the bottom is "Extract Here".
I would like to move the "Extract Here" item next to the "Open with Archive Manager" item as they are both actions that deal with the archive itself.
Comment: There is [question](http://stackoverflow.com/q/3326507) related it. But now `/usr/share/nautilus/ui/nautilus-directory-view-ui.xml` it is [**not available**](http://askubuntu.com/a/218446).
Comment: Based on [this](http://askubuntu.com/questions/5055/is-it-possible-to-hide-the-copy-to-and-move-to-context-menus) answer -the file/usr/share/nautilus/ui/nautilus-directory-view-ui.xml is now compiled in for speeed. So you will to make the changes to the source code of nautilus and recompile.
Comment: Maybe a screenshot would make this even clearer. I like this type of usability question.
Comment: Neither of these are duplicate questions! The first one is about adding new items to the menu, the second one is about adding python scripts. I asked about re-ordering the existing menu!
Comment: possible duplicate of [How to customize the context menu in Nautilus?](http://askubuntu.com/questions/21953/how-to-customize-the-context-menu-in-nautilus) and [How to get the Nautilus scripts working in 13.04](http://askubuntu.com/questions/281062/how-to-get-nautilus-scripts-working-on-ubuntu-13-04)
Answer: It is unfortunately not possible to do this, because of the changes to Nautilus and the removal of /usr/share/nautilus/ui/nautilus-directory-view-ui.xml. It has been asked  (June 2012) in the gnome nautilus mailing lists, and it is clear from the developers' responses that one would now have to download the source code, patch it, and then recompile it to re-order menus.
Source: Is it possible to hide the "Copy To" and "Move To" context menus?


Confusion about glVertexAttribPointer and non-active attributes

Question: When binding an attribute index using glVertexAttribPointer, what happens when a later bound program does not contain an attribute at said index?
Is the behaviour undefined, or is the attribute ignored altogether?
I have searched the docs quite extensively, and have not been able to find much info about the link between programs and dynamic attribute bindings.
Comment: Hi Christian, thanks for updating my answer. I understand now that the phrase "thanks all" is only appropriate for letters to close family and the bereaved, and will try to do better in future.
Answer:
...have not been able to find much info about the link between programs and dynamic attribute bindings.

That is because there really is no link between them. Your vertex array data, i.e. the enabled attribute arrays and the buffers which they source their data from, don't really care at all which future shader programs they'll be used with.
If they enable attribute arrays that are not needed by the program, that data is just ignored. It's not like the attributes are read from the buffers and will spill out of your GPU when the program doesn't consume them ;-), they're just not read at all.
If on the other hand the program uses attributes for which you don't have an array/buffer enabled, that isn't an error either. Instead, the attribute data will be sourced from a single value that is constant over the entire draw call and can be set with the often somewhat forgotten glVertexAttrib functions.
Comment: "*they're just not read at all*" They *are* read. They simply aren't read *into* anywhere.
Comment: @NicolBolas just for the record, what is it called when something is read but not into anywhere? Doesn't the activity of reading involve that a subject takes the information _into_ account somehow? Otherwise it might be described as a passive verb, like _scanning_.
Comment: In any case, thank you both for the clarifications. I think I realise my mistake now. For any others that (either actively or passively) read this, I thoroughly recommend learning OpenGL through the spec. It taught me how to fly, and not __into__ hasty conclusions.
Comment: @invertedPanda: "*just for the record, what is it called when something is read but not into anywhere?*" There isn't a word for that. Technically, the read goes into cache memory, but that doesn't really matter. It won't affect the shader itself, merely the performance of having to read useless data.
Comment: @NicolBolas Ah, I see now. Is it possible for the OpenGL driver to optimise away any performance cost, and does that tend to happen in reality? Or is it negligible, in the grand scheme of things?
Comment: @NicolBolas That is interesting to know. Is that guaranteed to happen? I honestly thought the driver should be smart enough to know which attributes the shader needs and not read irrelevant data.
Comment: @ChristianRau: Memory isn't read bytewise; it's read by cache lines. So if the GPU needs to read the neighboring bytes, it *must* read the unused ones too.
Comment: @NicolBolas Well, of course if the attributes are tightly packed in the same buffer, some additional data will inevitably be read, but that would be the case regardless if the attribute array is enabled or not. But in case the irrelevant attributes are sourced from different buffers, there doesn't seem to be a need to touch those.


If $T$ is bounded on $S[0,1]$ $\Longrightarrow$ $T$ is bounded on $B[0,1]$?

Question: Let $T:X\longrightarrow Y$ be a  linear operator , $X \;,\;Y$ normed spaces
If $T$ is bounded on $B[0,1]$ , we define $\|T\|:=\sup_{\|x\|\le1} \|T(x)\|=\sup_{\|x\|=1} \|T(x)\|$
If $T$ is bounded on $S[0,1]$ $\Longrightarrow$ $T$ is bounded on $B[0,1]$ ?
$S[0,1]=\{x \in X :||x||=1\}$
$B[0,1]=\{x \in X :||x||\le1\}$
Any hints would be appreciated.
Comment: For $\Vert x\Vert\ne0$, $\Vert Tx\Vert ={\Vert x\Vert}\cdot\Vert T(x/\Vert x\Vert)\Vert$.
Answer: $T(\lambda x) = ?$ ... $\lambda =\lambda(\lVert x\rVert)$


LXD public ip to container using routed

Question: I'm trying to set a public ip to a container using the routed nictype in LXD,
Essentially i inited a fresh container, ran lxc config device add c1 eth0 nic nictype=routed parent=eth0 ipv4.address=my.public.ip
then started the container, it shows the correct ip in the IPV4 section for a split second, and running an lxc list again shows it dissapearing into a blank. So it IS* being set properly, at least to lxc, but a few seconds after startup it goes away.
My guess is there's maybe some DHCP style nonsense going on inside the container trying to get an ip from the host lxd machine? Any ideas are useful I don't have much knowledge with networking
Answer: For routed to work, you need to make some configuration in LXD and some configuration in the container. It is easier to create a LXD profile that contains both parts of the configuration.
Here is an example LXD profile. The upper part is about the container configuration, and the below part is what LXD needs to know to configure routed for the container.
config:
  user.network-config: |
    version: 2
    ethernets:
        eth0:
            addresses:
            - 192.168.1.200/32
            nameservers:
                addresses:
                - 220.127.116.11
                search: []
            routes:
            -   to: 0.0.0.0/0
                via: 169.254.0.1
                on-link: true
description: Default LXD profile
devices:
  eth0:
    ipv4.address: 192.168.1.200
    nictype: routed
    parent: enp6s0
    type: nic
name: routed_192.168.1.200
used_by:

To create a container with this profile, you would then run
lxc launch ubuntu: mycontainer --profile default --profile routed_192.168.1.200

References: https://blog.simos.info/how-to-get-lxd-containers-get-ip-from-the-lan-with-routed-network/

LXD public ip to container using routed


C reallocing a typedef?

Question: I need a struct declaration that contains a single string which I can then make an array of(so basically an array of pointers to strings). I know how to make an array of structs which each contain a string:
typedef char line_t[MAX_INPUT + 1];

typedef struct {
line_t text;
} lines;

lines *arrayoflines;
arrayoflines = (char *)calloc(MAX_INPUT + 1, sizeof(char));

No issue here. However, what if the number of characters in the string that needs to be stored goes past the bounds of MAX_INPUT? I feel I'd need to realloc char line_t[MAX_INPUT + 1] and that is what I have absolutely no idea how to do.
Edit: Seems like some thought that the number of strings in the array of strings was the issue. I meant reallocating for the length of the string that can be stored in each element in the array of strings.
Comment: why not just prevent the input from exceeding MAX_INPUT
Comment: @Les university assignment question - I don't know the size of the input. It could be anything. My lecturer is a harsh human.
Comment: still, you will know the size of your input when your program reads it.  as for your initial allocation, typically it would be...  arrayoflines = calloc(1,sizeof(lines));
Comment: If you want more lines later, it would be... arrayoflines = realloc(arrayoflines, N * sizeof(lines));  where N is the new number of lines.  Note: the new space will not be initialized, so you may want to use memset() on the new portion of your array.
Comment: @Les the number of lines I know how to reallocate just fine. The size of each line is the issue.
Answer: It is better to allocate memory for each line. I.e. instead of array of static arrays line_t[MAX_INPUT + 1] define array of char pointers: char ** arrayoflines.
Comment: You have to allocate memory for each element: `arrayoflines[0] = (char *)malloc( line_len + 1)`. Then you can copy line: `strcpy( arrayoflines[0], _your_string_buf_ )`. PS: Don't forget to `free` elements at the end.
Comment: By this you mean allocate memory to each element of an array of structs individually?
Comment: @Laefica Not array of structs but array of `char`-s. It is harder to do separate `malloc` but the usage of memory will be optimal. With static arrays you will waste memory for unused chars.
Answer: You have a limit for the maximum line defined in your array.  So, I assume any given line will never exceed that (you should check your input if this assumption is wrong).  You can read a shorter line into the line_t (by terminating your string with a NULL), but you will not recover the space in memory.  If you don't have many lines expected, your fixed buffer approach will work, i.e., you don't need to realloc.
However, if you need to be efficient with space, maybe because you will read millions of lines, you should allocate memory for each line.  In other words, you might consider changing line_t to a char* instead of char[MAX_INPUT+1].  They are semantically equal for your programming purposes.  But behind the scene, you are not setting a fixed size.
typedef char* line_t;

line_t *arrayoflines;
arrayoflines = calloc(1, sizeof(line_t));
arrayoflines[0] = calloc(MAX_INPUT + 1, sizeof(char));

//if you learn the size after reading into the buffer, and it's smaller,
// realloc the buffer - be sure to include space for NULL and be sure it
// is set to NULL
arrayoflines[0] = realloc(arrayoflines[0], (new_smaller_count+1) * sizeof(char))
arrayoflines[0][new_smaller_count] = NULL;

Comment: Why does `new_smaller_count` need to be set to `NULL`?
Comment: @Laefica - you are right, if the initial allocation is calloc'ed it is already null.  I have a habit of explicitly storing the NULL.
Comment: Oh, yep. Sorry I read that wrong. Haven't seen that get used. My tutor/lecturer have always done in this situation `arrayoflines[0][new_smaller_count] = '\0'`
Answer: if you can not ensure that the all the inputs will be less or equal  MAX_INPUT, you have to convert to dynamic allocation instead.
and by that you have to do this:
typedef struct {
    char * text;
} lines;
lines *arrayoflines;
arrayoflines =  calloc(MAX_LINES, sizeof(lines));

and for every (n) element allocate THE_DESIRED_INPUT_SIZE for that particular element;
arrayoflines[n].text=calloc(THE_DESIRED_INPUT_SIZE, sizeof(char));

the (n) is in range of [0,MAX_LINES-1]

C reallocing a typedef?


What should the plenum temperature be on a modern furnace

Question: I had a tech out to review my furnace that's not keeping up - a Trane XV80. They poked around, and saw that the plenum temperature is 95F. They then told me that it should be around 140F, which is clearly, substantially more. The thing that confused me is that in the same breath, he said that the temp delta between the return and the plenum should be 20-30F, which would mean a return temp of 110-120, which is impossible.
So - which is it? And what causes a low plenum temp / how can it be remedied?
Answer: The proper delta T for a heat pump is 20-30*F.  For a forced air fossil fuel furnace I would expect to see 35-70*. If the return air was 50* you could easily have a plenum temp of 95* and if you had really good air flow across the exchanger, the return could be 60* and still have that discharge temp.  As to a remedy there are simply too many factors involved to address through correspondence.   In a nut shell the furnace has to put-out more Bu's than the floor, walls and ceiling loose for any given period.
Comment: This is a gas furnace, and the intake air was at 75, so he quoted me the wrong delta T. They want to do a combustion analysis (and charge for it, of course). Would that be the a reasonable next step, or am I getting fleeced?
Comment: No it is not the next reasonable step.  Something is seriously wrong.  Maybe a weak hi-limit, or flame sensor.  I don't think you are holding a consistent fire.  The furnace must be cycling off before reaching room temperature. I recommend consulting another service outlet.  Your service man is clearly out of his league.
Answer: Look on the furnace data sticker. Every furnace since at least the 1980s will list the delta on the name plate. It will be a little different for each furnace but will always be a range such as 30-60 degrees. Measure the supply air temperature and subtract the return air temperature. This is basic furnace commissioning 101. Too cold and you risk condensation and rust. To hot and you risk cracking the heat exchanger and damaging other components. A low delta T is typically caused by low gas pressure but there are many other reasons it could be. I always do a combustion analysis when starting up a new furnace. That will tell if the burners are firing properly but is beyond what a home owner could do.


bit fields vs. stdint definitions

Question: So I am programming in C++, and as far as I can tell there is no C++ equivalent to stdint.h. Which is no problem, seeing as you can just grab a copy of stdint and include it... but my question is basically this,
what is the difference between these two pieces of code:
struct FREQ{
    unsigned int FREQLOHI :16;
    //etc...

};

and
struct FREQ{
    uint16_t FREQLOHI;
    //etc...
}

other than the obvious limitations of bitfields, is there a performance/portability issue? Which is preferred?
Comment: #include  will include this header.
Comment: If your C++ compiler lacks [stdint.h], then use the Boost version.
Comment: You cannot simply "grab a copy". For example, grabbing a copy from your visual studio compiler and putting it in a mingw compiler can possibly have erroneous behaviour. Next to that, `cstdint` should be an available header from C++11 on.
Comment:  does not exist in 2008 or 2010 as far as I know. @Killian, I am working in visual studio, and you can find a copy here: [link](http://msinttypes.googlecode.com/svn/trunk/stdint.h) that is ISO C9x  compliant stdint.h for Microsoft Visual Studio
Comment: Both `` and `` definitely come with MSVC++ 2010.
Answer: The difference is that unsigned int may be of different size on different platforms while uint16_t is guaranteed to have 16 bit width. This means that an instance of the first (bitfield) struct may have different size on different platforms. Also, bitfield access is more expensive since it involves extra shift and mask.
For example on laptop where unsigned int is 32-bit wide the first struct is 32-bit wide while the second struct is 16-bit.
When it comes to portability, bit-fields are in a much cleaner situation since it is an old C language feature that was included in C++ when it was standardized in 1998 (ISO/IEC 14882:1998). On the other hand stdint.h was added to C only in 1999 (ISO/IEC 9899:1999 standard) and hence is not part of C++98 (ISO/IEC 14882:1998). The corresponding header cstdint was then incorporated into C++ TR1, but it put all the identifiers in std::tr1 namespace. Boost also offered the header. The most recent C++ standard (C++11 aka ISO/IEC 14882:2011 that went out in September 2011) includes the header cstdint and it puts all the identifiers into the std namespace. Despite this, cstdint is widely supported.
Comment: You didn't really address the fact that the `unsigned int` is a bitfield.
Answer: Compilers will generally tend to pack bitfields together in a single word, thus reducing the overall size of your struct. This packing is at the expense of slower access to the bitfield members. For example:
struct Bitfields
{
    unsigned int eight_bit : 8;
    unsigned int sixteen_bit : 16;
    unsigned int eight_bit_2 : 8;
};

Might be packed as
0            8                        24
-----------------------------------------------------
| eight_bit  | sixteen_bit            | eight_bit_2 |
-----------------------------------------------------

Each time you access sixteen_bit it incurs a shift and bitwise & operation.
On the other hand, if you do
struct NonBitfields
{
    uint8_t eight_bit;
    uint16_t sixteen_bit;
    uint8_t eight_bit_2;
};

then the compiler generally aligns the members at word boundaries and lays it out as something like:
0            8           16           24
-----------------------------------------------------
| eight_bit  |            | sixteen_bit             |
-----------------------------------------------------
| eight_bit_2|                                      |
-----------------------------------------------------

This wastes more space compared to bitfields, but the members can be accessed faster without bit-shifting and masking.

Here are some other differences:

You can't apply sizeof to a bitfield member.
You can't pass a bitfield member by reference.

In terms of portability, both options should work on any standards-compliant compiler. If you mean binary portability between different platforms when writing the struct out to a file or socket, then all bets are off for either case.

In terms of preference, I would opt for using uint16_t instead of bitfields, unless there a good reason for packing the fields together to save space. If I have many bools inside a struct, I'll generally use bitfields for compressing those boolean flags together in the same word.
Comment: Isn't there some keyword that 'requests' the compiler to align for 'speed'?
Comment: @muntoo: No, but there might be compiler-specific pragmas or attributes.

bit fields vs. stdint definitions


General security request setup

Question: Im trying to completely eliminate any chance of repainting or false signals in my script and just wanted some advice on the best way to set up a security request.
Is it best to have each bool statement defined outside the security request or is it the same as having them defined within the request,  below is the 2 options
Alerts are being set on the 1 Minute Chart
// EXAMPLE 1
f_get_SR2() => [close>open, close<open[1], open[1]]

[M5_Bullish , M5_Ab_Last_Open, m5_Lastopen] = request.security(syminfo.tickerid, '5' , f_get_SR2() ,  barmerge.gaps_off,  barmerge.lookahead_on)

//OR

Bullish       = close>open
Und_Last_Open = close<open[1]
Last_Open     = open[1]
f_get_SR2() => [Bullish , Und_Last_Open  , Last_Open   ]

[M5_Bullish , M5_Ab_Last_Open, m5_Lastopen] = request.security(syminfo.tickerid, '5' , f_get_SR2() ,  barmerge.gaps_off,  barmerge.lookahead_on)

Say i want to see if the last 1 minute bar is above the last 5m bar open
Do I have to request it within the tuple as close<open[1] or is it the exact same outcome if i request the open within the tuple and then write it as
// On the 1 minute chart
M5_Ab_Last_Open = close>m5_Lastopen and barstate.isconfirmed

//EXAMPLE 2
K_down      = k[1]<k[2]
Macd_down   = macd[1]<macd[2]
hist_down   = hist[1]<hist[2]
Long_Sell   = (K_down     or macd[1]<macd[2])  and  hist_down
f_get_tf4() =>
    [ Long_Sell    , K_down  ]

[TF4_L_SellSig_NR, TF4_lastk_Dn] = request.security(syminfo.tickerid, '60', f_get_tf4(),  barmerge.gaps_off,  barmerge.lookahead_on)

//OR

f_get_tf4() =>
    [(k[1]<k[2]  or macd[1]<macd[2])  and  hist[1]<hist[2], k[1]<k[2]]

[TF4_L_SellSig_NR, TF4_lastk_Dn] = request.security(syminfo.tickerid, '60', f_get_tf4(),  barmerge.gaps_off,  barmerge.lookahead_on)

I have it set to barmerge.gaps_off,  barmerge.lookahead_on  because some of the requests i need live data ( but they arent included in the alerts) only confirmed ones... [1] etc
//Would this repaint if set on a 1 minute chart?
Up_2perc = (close>(open*0.98))

[Hour_Up_2 ] = request.security(syminfo.tickerid, '60', UP_2perc ,    barmerge.gaps_off,  barmerge.lookahead_on)

if UP_2perc and barstate.isconfirmed
    strategy.entry('Long'..................

I know its probably best to do all calculations within the security request but some data figures might be used for a variety of different calculations.
I just want to check if there is any major difference in the way the data is received or if the end result would be the same any of the ways used above.
Thanks
Answer: To avoid repainting, use the f_secureSecurity() function from this library

General security request setup


STL reallocation C++

Question: I got that sample source:
std::string tmp1;
std::string tmp2 = "Test";

while(1)
{
    tmp1 += tmp2;
}

We see that tmp1 gets the content of tmp2 and each loop it adds "Test" at the end of the string. I know that this should be similar to strcat(), but strcat is a C function and it has got C function realloc()
How do std::string implements concatenation of strings?
Does it use some kind of reallocation of memory? If yes how do I reallocate in C++?
Answer: First off, strcat() doesn't allocate any memory! If you provide a too small buffer to strcat() you'll get a buffer overrun, not a reallocation.
The std::string class internally manages memory. It will reallocate memory using a suitable sequence of using new and delete operators. The way it is specified it will overallocate memory and not allocate new memory on each string addition.
If you need to use variable sized amounts of memory, you are probably best off to use std::vector<T> for a suitable type T. This class takes care of allocating and releasing memory. You just tell it how many elements you need. Under the hood it is also using combinations of new and delete operators (well, actually an allocator object) to maintain memory. There is no direct support for something like C's realloc().

STL reallocation C++


Externel Keyboard issue in Ubuntu14.04 on Asus-X450LA

Question: I'm using an external Logitec wired keyboard on Ubuntu 14.04 LTS in my Asus X-450LA. Suddenly I catch an issue in my external keyboard. When I press the backspace or space button, I got continuous dot (.......).
I already removed ibus .cache, .config and tried dconf-editor to solve my issue. But this failed to solve the issue. Note that, I don't feel any issue in my laptop keyboard.
Help please?
Comment: Problem went away after a keyboard replacement.
Answer: Actually this was not an software issue. It was hardware issue. I have changed my keyboard and everything is running fine.


Search column with comma separated string

Question: Currently I am using the query below together with a recursive function to print a menu.
"SELECT * FROM categories WHERE FIND_IN_SET('".$parent."', parentId)"

DB structure:

The result by printing this out is:
Smycken
--| Halsband
--|--| Guld
--|--|--| test
--|--|--|--| test2
--|--| Silver
--| Armband
Honung

Row 10, parentId. I got two values separated with a comma (I've read that this is not the ultimate way to store values, but I'll do it anyway), now I want row 10 to be printed out like a subcategory, just like my other rows are being printed out. The solution I found was to use FIND_IN_SET or use LIKE, I get neither of them to work as I wish...
Suggestions or a solution for my problem?
This is my function:
function getSubCat($level = 0, $parent = 0)
{

$hasChildren = false;
$outputHtml = '%s';
$childrenHtml = '';

$dbh = getdbh();

$getSubCategory = $dbh->prepare("SELECT * FROM categories WHERE FIND_IN_SET('".$parent."', parentId)");
$getSubCategory->execute();
$categories = $getSubCategory->fetchAll();
foreach($categories as $category)
{

    if ($category['parentId'] == $parent) {
        $hasChildren = true;
        $childrenHtml .= '<option value="'.$category['id'].'">';

        for($k = 0 ; $k < $level; $k++) {
            $childrenHtml .= '--|';
        }

        $childrenHtml .= ' '.$category['name'];
        $level++;
        $childrenHtml .= '</option>';
        $childrenHtml .= getSubCat($level, $category['id']);
        $level--;
    }
}

if (!$hasChildren) {
    $outputHtml = '';
}

    return sprintf($outputHtml, $childrenHtml);
}

Comment: `find_in_set` should work. Is the a space after the comma in the `parentid` column? That would prevent it from working.
Comment: there is no space in that column. Values are passed like: "1,2,3,4"
Comment: The problem isn't in your SQL, it's in PHP. `if ($category['parentId'] == $parent)` does an exact match, it doesn't work if `$category['parentId']` has a comma.
Comment: I tried to make a `foreach` there and `explode(',', $str_from_DB)`. It is possible that I made something wrong though.
Answer: Change this line:
if ($category['parentId'] == $parent) {

to:
if (in_array($parent, explode(',', $category['parentId']))) {

The == test won't look for an element in a comma-separated string.
Actually, you don't need this if at all. The WHERE clause in the SQL already guarantees that $parent is in $category['parentId'].
Comment: Thanks! I took away `if ($category['paren...` and now it works :)


Jest complains about Typescript syntax

Question: When I run yarn test Jest throws an error that says

'Const declarations' require an initialization value.

Which is not what I'm doing!
> 4 | const config: HardhatUserConfig = {
    |             ^
  5 |   solidity: "0.8.9",
  6 |   paths: {
  7 |     artifacts: "./src/artifects",

I think it is obvious that jest is having problem with TS syntax.
How can I fix that?
Comment: https://stackoverflow.com/q/58261143/438992, https://stackoverflow.com/q/56631104/438992, etc?
Comment: Does this answer your question? [Jest configure typescript without webpack](https://stackoverflow.com/questions/56631104/jest-configure-typescript-without-webpack)
Answer: You need to use ts-jest.

Install ts-jest: npm install ts-jest -D
Update your jest config to use: preset: 'ts-jest'

You still run your tests the same way - just run jest.
Comment: Thanks it worked! The problem with the second error was that I should use major versions for both `Jest` and  `ts-jest`
Comment: I got `TypeError: Jest: a transform must export a "process" function.`
Comment: Hmm, I'm not sure why that would be happening. Make sure to follow the instructions on the ts-jest project page and report back here (if you don't mind).
Comment: Sure!

Jest complains about Typescript syntax


RegisterClientScriptInclude: What does "type" parameter do?

Question: I'm currently looking into the RegisterClientScriptInclude method so I can be sure that I don't do something like include JQuery twice on one page. The Microsoft documentation states:

This overload of the RegisterClientScriptInclude method takes key and url parameters to identify the script, as well as a type parameter to specify the identification of the client script include. You specify the type based on the object that will be accessing the resource. For instance, when using a Page instance to access the resource, you specify the Page type.

I don't get what that actually does for me. Does it just identify in some way which page/control took precedence and registered the include? Can someone please explain why I would want to provide a type in addition to the key/url? Thanks in advance.
Answer: The type is used along with the key string to form a unique identifier. This is used to identify the include so that you can call RegisterClientScriptInclude several times with the same script, but it will only be included once in the page.
The type is needed so that controls can work independently of each other within the page. If you have two controls that makes includes that are not aware of each other, they may use the same key string by accident. If the type (in this case the type of the controls) was not used, one include would exclude the other although they were never intended to interfer with each other.
Comment: @Ocelot20: Yes, that is correct. You could use `Page.GetType()` as type if you want the include to be unique for the page. (There is also an overload of the method that doesn't need the type parameter, but the documentation only says that it calls the overload with the type parameter, but not which type it uses.)
Comment: If I follow correctly, does this mean if I called `RegisterClientScriptInclude(MyPageType, "JQuery", "jquery.js")` and `RegisterClientScriptInclude(MyControlType, "JQuery", "jquery.js")` there would be two references to jquery included? If that's the case, sounds like I wouldn't want to use that for my particular concern.


Select options with new lines issue

Question: I have the following rails code (it uses simple form):
<%= f.input :color, collection: custom_colors.split(/\n/).reject(&:empty?) %>
custom_colors comes from a text area where users are asked to enter entries seperated by new lines.
The issue: This displays correctly, however, when a user goes to edit, the color is not saved and the select is empty. I'm using a typical rails scaffold.
The issue (continued): The reason I believe this is not working, is that when saved, the color looks like blue\r\n. However, when I do:
<%= field.options.split(/\n/).reject(&:empty?) %> it returns blue\r, which means the input won't match, as blue\r\n clearly does not equal blue\r
How do I fix this?
Comment: post rails stack trace
Comment: @Nithin, to be clear, this isn't producing an error, it simply isn't selecting the correct dropdown option when a user goes to edit. I could post the results of `Thread.current.backtrace` but it looks normal.
Comment: You mean to say, the save is happening properly?
Comment: @Nithin, yes the save is happening properly. Actually, now you say that, I think I have found the issue, however, I'm not sure how to solve it. When it's saved, the colors are saved like: `blue\\r\\n`, leading it to not match the array in simple form. How would I get it to save without the returns?
Comment: @Nithin, sorry it's actually saving `blue\r\n` not what i posted before. But same issue I believe.
Comment: I guess the fix should come from collection object, I guess that's what is appending additional chars and stored into db.
Answer: Try this in your form.
<%= f.input :color, collection: custom_colors.split(/\n/).map(&:strip).reject(&:empty?) %>

Select options with new lines issue


Clarify on enriched categories

Question: The teacher mentioned that, given a category $\mathbb C$ enriched in a (monoidal) category $\mathbb V$,the category $\mathbb C^{op}$ is enriched in $\mathbb V$ iff $\mathbb V$ is commutative. However I don't see where actually is requested the commutativity of the product of $\mathbb V$; for example, in the case of a usual category (i.e. enriched in sets) $\mathbb C$, when I verify that the definition of $\mathbb C^{op}$ gives raise to a category, I don't see where I use that the product of sets is commutative. Thanks in advance
Answer: The composition in the opposite category is
$$C^\mathrm{op}(x,y)\otimes C^\mathrm{op}(y,z)=C(y,x)\otimes C(z,y)\cong C(z,y)\otimes C(y,z)\xrightarrow{\circ}C(z,x)=C^\mathrm{op}(x,z)$$
and to define it you need the symmetry isomorphism in the middle.

Clarify on enriched categories


Show data gradually or all at once?

Question: I'm building a site that shows military allowance for housing (BAH). My site not only computes the BAH allowance, but shows estimated costs if one were to buy a house in that area. You can see the site here: http://bahcalculator.org/
I'm worried I'm confusing the user with too much data at once. The user needs to select a state, base, and grade (rank) to see their actual numbers. Should I change the site and put a very simple form that says Select State > Select Base and Grade, then have a hidden panel show up with all the numbers using jQuery? Or do you think I'm on track by showing everything at once?
Answer: I think your instincts are right. There is too much information.
My Personal Experience

I had to search for the action area - from a graphic design point of view, the boxes (with the big colourful headings) draw more attention than the form, which is the task entry point.
I had to make sense of what the boxes actually stand for, so you made me think unnecessarily.
There was a default option, so information that has nothing to do with me was given. I had to make sense of it and you took control from me (regarding what is it that I want)

Some Assumptions
See many of these and related here.

Users will enter your site with a specific task in mind. Spare them any information that is not relevant. One the form is filled, so the results.
Users don't read, they scan. You made me scan for the form, making my job harder.
By giving more information than needed you promote cognitive overload. Why display irrelevant information before the user has taken an action?

Information Prioritising
From a information design point of view, the additional expenses section draws more attention than the BAH rate/Home Purchase as it has a bigger heading in close proximity and it takes 100% width of the screen. This is counter what I believe is the really important information. You should really drop the BAH rate/Home Purchase to be above the additional section and have a heading as big.
I suggest you only show both sections after the user has filled the form.
If I'm being really picky, you can further reduce redundancy if instead of providing with dependents and without dependents radio buttons, you simply have a heading called dependents (under the Grade combo - for which you can remove 'select'), and just have two vertically aligned radions saying with and without:

download bmml source – Wireframes created with Balsamiq Mockups
A Visual Analysis
Comment: Wow thank you so much for this helpful reply. You are spot on that the BAH rate is the only info the user "needs" and everything else is extra. One thing, the map is for display only, to show the user that the BAH rate is for the right area they are searching. Do you think that's necessary? I love your idea of moving the Home Purchase text down. I will try to make that a panel that can be clicked to show all the numbers. I'll make some edits over the next few days and will repost here to see what you think.
Comment: I can only assume that if I was looking for a place, I'd like to see the area on the map (nearby stations, parks, centres, etc.). What is important is that the map is part of the search result; so I would only have it displayed once a base has been selected.
Comment: Ok I'll keep the map. I'll redo the map to start with a zoomed out view of the US, then zoom in once the user submits a search.
Comment: Izhaki - if you have time could you please look at my updated design which I posted in [this](http://ux.stackexchange.com/questions/44184/followup-show-data-gradually-or-all-at-once/) question?
Answer: If you are worried about distraction, a hidden panel may still be more extreme than you need.  Placing the lower-priority information lower on the page (as you seem to be doing already) should be enough.  Some users may appreciate not having to dig for information, especially since it looks like users may need to look at information for multiple locations (which would multiply any digging required).
Actually, given what is there already, you have the opportunity for more information to mean less work for the user by explicitly giving a single metric that users could use to compare multiple areas:
"BAH" divided by housing price
You could even provide a metric that is potentially even more helpful, but not comparable across time, and which would require more work.  You could give "BAH" divided by a typical mortgage cost over the same period as the "BAH" (monthly?), using the house price, a typical mortgage length and down payment amount (which you could choose once and not revisit for long periods of time), and a typical mortgage interest rate (which you would probably want to fetch a new value of every month or so).
Comment: No problem.  Not to add *even more* work for you, but that map would be more useful if it showed the border of the area covered by the current BAH.  ;)  Users might like to know that a tiny change in move could trigger a different BAH.  This would not take up any extra area, and is another example of more information potentially being easier to use rather than more difficult.
Comment: A.M. that's a great idea to highlight the BAH coverage area. I'll have to see if I have the data to support that.
Comment: I *might* even go so far as to say that without the BAH coverage area being marked, the map is not very useful.  (Users are likely to already know *where* they are talking about.)  A couple of *other* ideas for making the map worthwhile, though, would be (a) allowing users to **select** the location *from* the map, and (b) showing **base** locations on the map.
Comment: A.M thanks for the helpful advice. I'll see what I can do on this part.
Comment: @caseym no problem, and welcome to the site.  By the way, you just got the up-voting privilege here.  ;)
Answer: Some improvements could be:

Autofocus search field on load. Currently focus is on the Google map. Focused field sets the starting point for a user.
Drop-down list while search is good, but after item selection one should press Search or press Enter to perform search. Simplify this action by immediate search.
To minimize visual distraction, hide bottom panel Home Purchase Additional Expenses until user performs first search. As the panel contains a set of eye-catching elements, it will be better not to show it at the beginning to narrow user's attention to search task.
Remove frames around numbers in BAH Rate and Home Purchase. The
frames create feel of editable fields, but those are just labels.
Comment: Thanks Alexey. I'm going to try and autofocus the search to the search bar. What is your opinion on removing the Browse by State > Base and replace it with a combo search box and drop down like this: http://baymard.com/labs/country-selector? What do mean by the frames around the BAH Rate and Home Purchase?
Comment: I think your current design is good enough, Search allows typing experience while drop down allows picking experiense (for those who don't like to type). So you provide two different input means, which is good. Of course, more objective is to test interface with users. Under frame I meant border around numbers that is implemented with background image *bg-price.gif*
Comment: Good idea. Once this gets going I'll track whether the user is using search or drop down, then make a decision to alter based on that data. I see what you're talking about now concerning the wire frame.
Answer: Leave it how it is now. While in some situations required user-interaction can be overwhelming, you most definitely aren't overwhelming the user with a few inquiries.
For the most part, users don't like surprises. When I'm using a website that dynamically loads more questions (probably trying not to overwhelm me), I just find myself frustrated in wondering, "WHEN WILL IT EVER END?"
By displaying all of the required fields at once, you are giving the user a sense of control. They can visually interpret what is expected of them and then decide whether or not they wish to partake.

Show data gradually or all at once?


May a correct program be incorrectly synchronized?

Question: In answer of Does a correctly synchronized program still allow data race?(Part I), it gives us a good example: all executions of a program appear to be sequentially consistent, but it still has data race. It tells us why another direction of following conclusion in JLS is not true:

If a program has no data races, then all executions of the program will appear to be sequentially consistent.

Now take a look at another conclucsion in JLS:

A program is correctly synchronized if and only if all sequentially consistent executions are free of data races.

According to this conclusion,above example is not correctly synchronized, so may a correct program be incorrectly synchronized?
Comment: Now **THAT**'s what I call "soon"!
Answer: You would probably need to define first what a correct program is (not easy). JCiP proposes (in a different context):

a program is correct if it conforms to its specifications.

Using that definition, the example provided is correct. However, it is not correctly synchronized (there is a data race on hash).
==> a correct program may be incorrectly synchronized, as proved by that example.
Answer: While this doesn't appear to answer the OP's question, I am keeping it for the comments.

You can get a number of race conditions using synchronized collections. e.g.
Vector<Integer> vector = ...
vector.add(1);

vector.set(0, 1 + vector.get(0));

Each method is synchronized and yet there is a race condition.  This is because you can have threads T1 and T2 doing.
T1: int tmp1 = vector.get(0);
T2: int tmp2 = vector.get(0);
T1: vector.set(0, 1 + tmp1);
T2: vector.set(0, 1 + tmp2);

In this case tmp1 == tmp2 which is not normally the case.
To synchronize this correctly you would do the following to ensure you hold the lock the whole time.
synchronized(vector) {
    vector.set(0, 1 + vector.get(0));
}

Comment: Not according to the strict definitions of the JLS, which the OP has in mind. You in fact demonstrate the opposite of OP's request: a **correctly synchronized** program ([JLS 17.4.5](http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5)) which is **incorrect**.
Comment: BTW as your program is correctly synchronized, all its executions will appear to be sequentially consistent, even though the behavior will not be as intended (it will be incorrect from a requirements standpoint).
Comment: Peter, you are not demonstrating an instance of a *data race*, which is what OP is asking about. OP is really bent on the precise usage of terms, he's been reading and re-reading the JLS in the past days to the last letter :)
Comment: @MarkoTopolnik Ok, can you tell what the difference between a `race condition` and a `data race` ?
Comment: A *data race* is only a very narrow kind of a *race condition* involving conflicting inter-thread actions on non-volatile variables that are not ordered by the *happens-before*. In your code all accesses are ordered.
Comment: Do you mean where you have `a = 3; b = 5;` and you see that `b = 5` before you see `a = 3` ?
Comment: Thank you for clearing up that point, but I thought the question was " may a correct program be incorrectly synchronized?"
Comment: The point is, **your program is correctly synchronized** as it **doesn't contain data races**. OP wants an incorrectly synchronized program, but that is still *correct*.
Comment: @MarkoTopolnik It is correct in term of a data race, but still using synchronized incorrectly and fails the `sequentially consistent executions` test.
Comment: @PeterLawrey, I have made further edit on your answer. Please don't roll it back but correct it, so readers like me and beginner can learn more from your modification.
Comment: @PeterLawrey. I'm not sure whehter my understanding is correct or not, if it is not correct, please correct it. Your program is correct if call on vector.set() is atomic. As call on vector.set() like vector.set(0, 1 + vector.get(0)) is not atomic, this program is not correct. However, according to definition in JLS, this program is correctly synchronized. The reason why this program is not correct is that this program contains race condition, whereas it is out of the scope of JMM defined in JLS. Is my understanding correct? Thanks a lot.
Comment: @newman That sounds right. Whether this is an example of incorrect synchronization is under question. IMHO its synchronized incorrectly but I don't know if that is what the author had in mind.