Search JSON for item and display value

Question: I have the following JSON data, what I am trying to do is search through the [lastStarport][Commodities] key and return one of the values based upon the commodity name.
i.e.  I want to search for the item "Clothing" and return the "cost_mean" value, I have looked at some other examples of searching JSON but do not seem to be able to adapt them for my purpose.
As usual any help is always appreciated.
{
"commander": {
    "id": 1111111,
    "name": "xxxxxxxx",
    "credits": 12345678,
    "debt": 0,
    "currentShipId": 2,
    "alive": true,
    "docked": false,
    "rank": {
        "combat": 3,
        "trade": 4,
        "explore": 5,
        "crime": 0,
        "service": 0,
        "empire": 0,
        "federation": 0
    }
},
"lastSystem": {
    "id": "12342356464335",
    "name": "xxxx xxx xxxx"
},
"lastStarport": {
    "id": "234234234234",
    "name": "xxxx xxxxx",
    "faction": "xxxxxxx",
    "commodities": [
        {
            "id": "128049204",
            "name": "Explosives",
            "cost_min": 300,
            "cost_max": 456,
            "cost_mean": "378.00",
            "homebuy": "60",
            "homesell": "56",
            "consumebuy": "4",
            "baseCreationQty": 180.32,
            "baseConsumptionQty": 0,
            "capacity": 49669,
            "buyPrice": 222,
            "sellPrice": 207,
            "meanPrice": 378,
            "demandBracket": 0,
            "stockBracket": 2,
            "creationQty": 49669,
            "consumptionQty": 0,
            "targetStock": 49669,
            "stock": 27813,
            "demand": 0,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Chemicals",
            "volumescale": "1.1400"
        },
        {
            "id": "128049202",
            "name": "Hydrogen Fuel",
            "cost_min": 125,
            "cost_max": 168,
            "cost_mean": "147.00",
            "homebuy": "74",
            "homesell": "71",
            "consumebuy": "3",
            "baseCreationQty": 200,
            "baseConsumptionQty": 200,
            "capacity": 137743,
            "buyPrice": 111,
            "sellPrice": 106,
            "meanPrice": 147,
            "demandBracket": 0,
            "stockBracket": 2,
            "creationQty": 110179,
            "consumptionQty": 27564,
            "targetStock": 117069,
            "stock": 68589,
            "demand": 0,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Chemicals",
            "volumescale": "1.3000"
        },
        {
            "id": "128049203",
            "name": "Mineral Oil",
            "cost_min": 192,
            "cost_max": 325,
            "cost_mean": "259.00",
            "homebuy": "47",
            "homesell": "42",
            "consumebuy": "5",
            "baseCreationQty": 0,
            "baseConsumptionQty": 1585.15,
            "capacity": 873251,
            "buyPrice": 0,
            "sellPrice": 193,
            "meanPrice": 259,
            "demandBracket": 1,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 873251,
            "targetStock": 218312,
            "stock": 0,
            "demand": 163734.75,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Chemicals",
            "volumescale": "1.0300"
        },
        {
            "id": "128049241",
            "name": "Clothing",
            "cost_min": 315,
            "cost_max": 474,
            "cost_mean": "395.00",
            "homebuy": "61",
            "homesell": "57",
            "consumebuy": "4",
            "baseCreationQty": 17.85,
            "baseConsumptionQty": 171.5,
            "capacity": 26095,
            "buyPrice": 0,
            "sellPrice": 454,
            "meanPrice": 395,
            "demandBracket": 2,
            "stockBracket": 0,
            "creationQty": 2459,
            "consumptionQty": 23636,
            "targetStock": 8368,
            "stock": 0,
            "demand": 17727,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Consumer Items",
            "volumescale": "1.1500"
        },
        {
            "id": "128049240",
            "name": "Consumer Technology",
            "cost_min": 6561,
            "cost_max": 7500,
            "cost_mean": "7031.00",
            "homebuy": "93",
            "homesell": "92",
            "consumebuy": "1",
            "baseCreationQty": 0,
            "baseConsumptionQty": 27,
            "capacity": 6512,
            "buyPrice": 0,
            "sellPrice": 7503,
            "meanPrice": 7031,
            "demandBracket": 3,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 6512,
            "targetStock": 1627,
            "stock": 0,
            "demand": 4885,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Consumer Items",
            "volumescale": "1.1000"
        },
        {
            "id": "128049238",
            "name": "Domestic Appliances",
            "cost_min": 527,
            "cost_max": 734,
            "cost_mean": "631.00",
            "homebuy": "70",
            "homesell": "67",
            "consumebuy": "3",
            "baseCreationQty": 10.71,
            "baseConsumptionQty": 102.41,
            "capacity": 9709,
            "buyPrice": 0,
            "sellPrice": 692,
            "meanPrice": 631,
            "demandBracket": 2,
            "stockBracket": 0,
            "creationQty": 1476,
            "consumptionQty": 8233,
            "targetStock": 3534,
            "stock": 0,
            "demand": 6175,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Consumer Items",
            "volumescale": "1.2500"
        },
        {
            "id": "128049177",
            "name": "Algae",
            "cost_min": 135,
            "cost_max": 265,
            "cost_mean": "200.00",
            "homebuy": "27",
            "homesell": "20",
            "consumebuy": "7",
            "baseCreationQty": 0,
            "baseConsumptionQty": 642.6,
            "capacity": 81180,
            "buyPrice": 0,
            "sellPrice": 136,
            "meanPrice": 200,
            "demandBracket": 1,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 81180,
            "targetStock": 20295,
            "stock": 0,
            "demand": 15221.25,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Foods",
            "volumescale": "1.0000"
        },
        {
            "id": "128049182",
            "name": "Animal Meat",
            "cost_min": 1286,
            "cost_max": 1633,
            "cost_mean": "1460.00",
            "homebuy": "81",
            "homesell": "79",
            "consumebuy": "2",
            "baseCreationQty": 0,
            "baseConsumptionQty": 97,
            "capacity": 12032,
            "buyPrice": 0,
            "sellPrice": 1287,
            "meanPrice": 1460,
            "demandBracket": 1,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 12032,
            "targetStock": 3008,
            "stock": 0,
            "demand": 2256,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Foods",
            "volumescale": "1.4000"
        },
        {
            "id": "128049189",
            "name": "Coffee",
            "cost_min": 1286,
            "cost_max": 1633,
            "cost_mean": "1460.00",
            "homebuy": "81",
            "homesell": "79",
            "consumebuy": "2",
            "baseCreationQty": 0,
            "baseConsumptionQty": 97,
            "capacity": 3900,
            "buyPrice": 0,
            "sellPrice": 1287,
            "meanPrice": 1460,
            "demandBracket": 1,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 3900,
            "targetStock": 974,
            "stock": 0,
            "demand": 731.5,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Foods",
            "volumescale": "1.4000"
        },
        {
            "id": "128049183",
            "name": "Fish",
            "cost_min": 403,
            "cost_max": 583,
            "cost_mean": "493.00",
            "homebuy": "66",
            "homesell": "63",
            "consumebuy": "3",
            "baseCreationQty": 0,
            "baseConsumptionQty": 271,
            "capacity": 35482,
            "buyPrice": 0,
            "sellPrice": 404,
            "meanPrice": 493,
            "demandBracket": 1,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 35482,
            "targetStock": 8870,
            "stock": 0,
            "demand": 6653,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Foods",
            "volumescale": "1.2000"
        },
        {
            "id": "128049184",
            "name": "Food Cartridges",
            "cost_min": 141,
            "cost_max": 270,
            "cost_mean": "206.00",
            "homebuy": "31",
            "homesell": "24",
            "consumebuy": "7",
            "baseCreationQty": 230.52,
            "baseConsumptionQty": 222.5,
            "capacity": 33794,
            "buyPrice": 44,
            "sellPrice": 34,
            "meanPrice": 206,
            "demandBracket": 0,
            "stockBracket": 3,
            "creationQty": 31749,
            "consumptionQty": 2045,
            "targetStock": 32259,
            "stock": 30540.025009,
            "demand": 0,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Foods",
            "volumescale": "1.0000"
        },
        {
            "id": "128049178",
            "name": "Fruit And Vegetables",
            "cost_min": 315,
            "cost_max": 474,
            "cost_mean": "395.00",
            "homebuy": "61",
            "homesell": "57",
            "consumebuy": "4",
            "baseCreationQty": 0,
            "baseConsumptionQty": 350,
            "capacity": 14069,
            "buyPrice": 0,
            "sellPrice": 316,
            "meanPrice": 395,
            "demandBracket": 1,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 14069,
            "targetStock": 3516,
            "stock": 0,
            "demand": 2638.25,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Foods",
            "volumescale": "1.1500"
        },
        {
            "id": "128049180",
            "name": "Grain",
            "cost_min": 207,
            "cost_max": 342,
            "cost_mean": "275.00",
            "homebuy": "50",
            "homesell": "45",
            "consumebuy": "5",
            "baseCreationQty": 0,
            "baseConsumptionQty": 584,
            "capacity": 80485,
            "buyPrice": 0,
            "sellPrice": 208,
            "meanPrice": 275,
            "demandBracket": 1,
            "stockBracket": 0,
            "creationQty": 0,
            "consumptionQty": 80485,
            "targetStock": 20120,
            "stock": 0,
            "demand": 15091.25,
            "rare_min_stock": "0",
            "rare_max_stock": "0",
            "market_id": null,
            "parent_id": null,
            "statusFlags": [],
            "categoryname": "Foods",
            "volumescale": "1.0500"
        }
    ]
}
}

Comment: Thank you @jonrsharpe, I appreciate the help. For someone who has just embarked on the journey of attempting to learn something completely new (and probably out of my depth) the pointers in the right direction where inspiring enough for me to relook at the examples I had and try to understand them better so much so I can answer my own question...
Comment: *"Hey, great, a thousand lines of JSON and no attempt at code"* < nobody.
Comment: that's great! Just take it one step at a time and build on what you know.
Answer: After looking though some of the examples I had I realised I was one key to high and needed to parse the key for the JSON list
This achieved what I was looking for:
data = json.loads(JSON_String)['lastStarport']
com = raw_input('Commodity:')
    comPrice = [item["cost_mean"] for item in data['commodities']
    if item['name'] == com]
print comPrice

Search JSON for item and display value


How to automatically take a picture using SMS string as input

Question: I was wondering if someone could help me with study material or idea on how to automatically take a picture using an input string from an SMS on android application,same case as of Whatsapp activation mechanism.
Answer: You can write a background android service separately or within your app(waiting for activation). It will be monitoring and analyzing sms from one or more numbers. If the sms contains the expected valid string this service will activate the camera. This service will need some permission to preform these task i.e Permission to activate camera, permission to read contacts, permission to monitor sms.
You can look at the following links for help:
https://developer.android.com/reference/android/Manifest.permission.html
https://developer.android.com/guide/topics/media/camera.html


Facebook and MSN not connecting in Ubuntu 13.10

Question: In 12.04LTS it all works fine but in 13.10 neither Facebook nor MSN connects. Seriously I wish Ubuntu will go back to Pidgin that just works fine without any issues.
Comment: You can still install Pidgin from the Software Center.
Comment: Yes, fb problem for me too.. but it should be reported as bug.
Answer: I have the same problem with Empathy and Facebook and this have been the case for a long time now.
Also since 13.10 I have been having problem with both Google Hangouts and MSN.
For Google Hangout : I get the notification that I have a new message but when opening the chat dialog I get now message (but can see it i gmail, g+ etc). Also the title bar says something about me having -1 unread messages.
For MSN: Does not even connect anymore.
It feels strange to have a default chat application in Ubuntu that really does not work very well. Remove it all together as default or fix it. In lots of forums people are recommended to use Pidgin instead, if that's the case Pidgin ought to be the default in Ubuntu from the beginning.


(Beginner Question) facing errors when trying to install parcel.js

Question: I'm new to programming and facing some difficulties when trying to install parcel.js
Here are the errors I'm getting:
npm WARN deprecated firstname.lastname@example.com: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.

npm WARN deprecated firstname.lastname@example.com: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.

npm WARN deprecated email@example.com: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.

npm WARN deprecated firstname.lastname@example.com: https://github.com/lydell/resolve-url#deprecated

npm WARN deprecated firstname.lastname@example.com: Please see https://github.com/lydell/urix#deprecated

npm WARN deprecated firstname.lastname@example.com: request has been deprecated, see https://github.com/request/request/issues/3142

npm ERR! code EACCES

npm ERR! syscall symlink

npm ERR! path ../lib/node_modules/parcel-bundler/bin/cli.js

npm ERR! dest /usr/local/bin/parcel

npm ERR! errno -13

npm ERR! Error: EACCES: permission denied, symlink '../lib/node_modules/parcel-bundler/bin/cli.js' -> '/usr/local/bin/parcel'

npm ERR!  [OperationalError: EACCES: permission denied, symlink '../lib/node_modules/parcel-bundler/bin/cli.js' -> '/usr/local/bin/parcel'] {

npm ERR!   cause: [Error: EACCES: permission denied, symlink '../lib/node_modules/parcel-bundler/bin/cli.js' -> '/usr/local/bin/parcel'] {

npm ERR!     errno: -13,

npm ERR!     code: 'EACCES',

npm ERR!     syscall: 'symlink',

npm ERR!     path: '../lib/node_modules/parcel-bundler/bin/cli.js',

npm ERR!     dest: '/usr/local/bin/parcel'

npm ERR!   },

npm ERR!   errno: -13,

npm ERR!   code: 'EACCES',

npm ERR!   syscall: 'symlink',

npm ERR!   path: '../lib/node_modules/parcel-bundler/bin/cli.js',

npm ERR!   dest: '/usr/local/bin/parcel'

npm ERR! }

npm ERR!

npm ERR! The operation was rejected by your operating system.

npm ERR! It is likely you do not have the permissions to access this file as the current user

npm ERR!

npm ERR! If you believe this might be a permissions issue, please double-check the

npm ERR! permissions of the file and its containing directories, or try running

npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:

npm ERR!     /Users/cavingayle/.npm/_logs/2020-06-09T20_46_00_855Z-debug.log

Comment: Calvin, can you tell us about what operating system you are using? I think you should try to run this command as elevated permissions.
Comment: Hi Christopher,

Im currently running mac OS Catalina. My apologies but how is it possible to run as elevated permissions
Comment: prefix your command with sudo;
For example, sudo npm install xxx
Comment: I just wanted to circle back to this comment two years later, this helped me get my first dev environment setup to beginning learning. Im now a Software Engineer, thanks again
Answer: Cavin,
I believe that you are having an issue related to administrative elevation in NPM.
Attempt to prefix NPM with sudo in your command.
for example:
sudo npm install parcel


how to make function validation alert if not selected

Question: I already succeeded in making alert if the box is left empty or not filled in. All of my codes are working except for the GENDER and GRADE. For GENDER they have to tick to select. For Grade they have to select on the drop down menus.
Here are my codes.
    function validation()
{
    if(document.form1.first_name.value=="")
    {
       alert("Please enter your first name.");
       document.form1.first_name.focus();
       return false;
    }
    if(document.form1.last_name.value=="")
    {
       alert("Please enter your last name.");
       document.form1.last_name.focus();
       return false;
    }
    if(document.form1.gender.value=="")
    {
       alert("Please select your gender.");
       document.form1.gender.focus();
       return false;
    }
 if(document.form1.grade.value=="")
    {
       alert("Please select your grade.");
       document.form1.grade.focus();
       return false;
    }

First name, last name and others are working except for Grades and Gender. Please help me.
Comment: A checkbox doesn't have a value, it is checked, and a select box got a selected value, and a selected index. You should search about it
Answer: Select dropdown validation with html
<select required="required">
<option value=""></option>
<option value="A">A</option>
<option value="B">B</option>
</select>

Fiddle
With javascript
<form onSubmit="return checkForm();">
<select id="grade" >
    <option value=""></option>
    <option value="A">A</option>
    <option value="B">B</option>
    </select>
    <input type="submit" />
</form>

function checkForm(){
    var e=document.getElementById("grade").value;//alert(e);
    if(e===""){
        alert("nothing selected");
        return false;
    }
}

Fiddle
Checbox validation with html
<input id="remember" name="remember" type="checkbox" required="required" />

Fiddle
With javascript
function check(){
var e=document.getElementById("remember").checked;
    //alert(e);
    if(!e){
    alert("not checked");
        return false;
    }
  }

Fiddle
Radio button validation in javascript
<form onsubmit="return check();">
<input id="remember" name="remember" type="radio" />Male
<input id="remember" name="remember" type="radio" />Female
<input type="submit" />
</form>
function check(){
var e=document.getElementById("remember").checked;
    //alert(e);
    if(!e){
    alert("not selected");
        return false;
    }
  }

Fiddle
Comment: I used your code but instead of alert I used         document.getElementById('message').innerHTML = ("Please select a option part "); - my question is that how this text can be disappeared once user select all the options and submits them?
Answer: Try this:
if(!document.getElementById('gender_male').checked && !document.getElementById('gender_female').checked)

and
if(document.form1.grade.selectedIndex == -1)

Use selectedIndex against -1 for select elements.
And use checked for radio buttons, on individual radio elements.
Answer: put breakpoint in validation() function and see what is coming for
document.form1.gender.value and document.form1.grade.value.
Check for that result in if.
Comment: Don't you think you are not posting an answer. You are giving a suggestion , you may post it as a comment.
Comment: sorry my fault: The gender is radio button. One is selected by default i must be wrong it must not be compulsory. The only problem left is the Grade where there is a drop down menu namely Grade 7, Grade 8, grade 9, etc.. The default is the word "SELECT". What i wanted is the user will be alerted that he/she must select valid Grade in case of leaving it default
Comment: You got an answer in suggestion.


Dynamic Pivot Columns with related tables in Sql Server

Question: I am attempting to use a Pivot to dynamically create columns and am not getting the proper results I am looking for. I need to show all possible answers in its own column for each question (row), and there are multiple questions in a course. How can I generate each possible answer as a column name, and filter by courseId and the questionId for each row? The number of possible answers varies based on the question. Should this be done via cursor instead of pivot?
DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX),
        @courseID float(24) = 1

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(questionID)
            FROM answers
            INNER JOIN questions ON questions.questionID = answers.questionID
            WHERE questions.courseId = @courseID
            order by 1
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)')
                        , 1, 1, '');

set @query = 'SELECT * from
            (
                select Q.courseId, C.courseName, Q.question, Q.questionID, A.answer
                from questions Q
                inner join courses C ON Q.courseId = C.courseId
                inner join answers A  ON A.questionID = Q.questionID
                where (Q.courseId = ''' + Str(@courseID) + ''')
           ) x
            pivot
            (
                max(answer)
                for questionId in (' + @cols + ')
            ) AS p'

execute(@query)

When running the above I am getting:
[1],[10],[11],[12],[13],[14],[15],[16],[2],[3],[4],[5],[6],[7],[8],[9]

As the generated columns which are the questionIds and not 'Answer 1, Answer 2 ... etc', and they are not displaying in order.
For the sake of brevity here are the related columns in the database tables:
Courses
courseId

Questions
questionId   question     courseId

Answers
AnswerId    questionId    answer

Any help is appreciated.
Answer: You didn't provide a many details on your table structure, but if you want the answers as the columns i.e. Answer1, Answer2, etc then you need to create the columns using row_number() against the number of answers per question similar to the following:
SET @cols = STUFF((SELECT ',' + QUOTENAME('Answer'+cast(seq as varchar(10)))
            FROM
            (
                select row_number() over(partition by q.questionid
                                            order by a.answer) seq
                from answers a
                INNER JOIN questions q
                    ON q.questionID = a.questionID
                WHERE q.courseId = @courseID
            ) d
            group by seq
            order by seq
                    FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)')
                    , 1, 1, '');

This creates a sequence for each answer per question and then that sequence number is used to create the new columns names.  Then you will alter your PIVOT code to:
set @query = 'SELECT *
            from
            (
                select Q.courseId, C.className, Q.question, Q.questionID, A.answer,
                    ''Answer''+cast(row_number() over(partition by q.questionid
                                                        order by a.answer) as varchar(10)) seq
                from questions Q
                inner join classes C
                    ON Q.courseId = C.courseId
                inner join answers A
                    ON A.questionID = Q.questionID
                where (Q.courseId = ''' + Str(@courseID) + ''')
           ) x
            pivot
            (
                max(answer)
                for seq in (' + @cols + ')
            ) AS p'

execute(@query)

Comment: Sorry about the lack of detail. I edited my question to include some of the table structure. In any case your example worked perfectly. Thank you!


Can or should you flag questions with even a minor negative tone?

Question: I think Stack Exchange has worked a lot in recent years in improving the overall positivity of the site, and it's been effective.
I've noticed they try to be a little more subtle about showing you your downvotes so it doesn't hit so hard - I think downvotes subtract a smaller amount of reputation points than upvotes add. Also, there seem to be more protocols in place to help new people ask better quality questions or editing them to improve quality.
Anyway, I recently noticed you can't edit other people's comments, as an editor. I feel like this could actually be beneficial. It seems like comments don't currently have the "self-regulating" aspect of much of the rest of the site. You can be a lot more free in how you write them, and they basically seem to stick around forever.
You can flag comments, though, so I'm wondering if the top moderators can actually edit and/or delete comments.
I feel like one remaining "pain point" for me as a user, being a sensitive person, is that sometimes people still express a bit of negativity in the comments. Sometimes it's a natural, well-intended expression of sentiment that a question isn't well-formatted, or is unclear, or the premises of the question do not appear to make sense, or the question appears to be either obvious or nonsensically asking for something either impossible or tautological, etc.
Those little comments like "I have no idea what you are asking", "I am confused", "Do you really think that?", etc, still kind of add up for me, as well as downvotes.
Barring Stack Exchange maybe allowing more comment editing and maybe even making downvotes more hidden - like something for moderators to see but there being no need for an asker to see their question is at -13 instead of just having no upvotes -
I was wondering if you can / should just regularly flag any comment that does not seem optimal. Not abusive or a breach of conduct or anything like that, just small stuff like there's one small, minorly negative choice of word in there that could be improved; or a comment that asked for clarifying information in the past but is now irrelevant since the post was updated in response to it.
Comment: A good read: https://stackoverflow.blog/2019/07/18/building-community-inclusivity-stack-overflow/
Answer:
You can flag comments, though, so I'm wondering if the top moderators can actually edit and/or delete comments.

The site moderators can edit and delete comments. Comments are actually meant to be volatile and we mods are always on the lookout to remove redundant comments wherever possible. Comments are basically only used to ask for clarifications or suggestions to improve a post. 'Thank you' comments are frowned upon and should be removed for instance. Flagging comments is fine. Don't overkill though; flagging one comment in a post, instead of every single comment, and adding info that the comment string seems redundant will do fine :) Flagging a rude post is also fine.

Those little comments like "I have no idea what you are asking", "I am confused", "Do you really think that?", etc, still kind of add up for me, as well as downvotes.

You shouldn't take things personally, especially not so on scientific stacks. Regarding downvoting - I upvote and downvote a lot, and I recommend every user to do the same, including downvoting when necessary. Downvotes help to push low-quality answers to the bottom and also help the mod team to identify problematic posts. Bad questions that have received net negative vote counts are automatically removed after a while, which keeps the site clean and tidy. Downvotes are useful and necessary.

Barring Stack Exchange maybe allowing more comment editing and maybe even making downvotes more hidden - like something for moderators to see but there being no need for an asker to see their question is at -13 instead of just having no upvotes

Comment editing is not very useful; comments are to ask for clarifications, primarily. If there's rudeness or unusefulness in play - flag the comment for mod attention. Per above reply, downvotes should not be hidden. They are an integral part of the SE philosophy and necessary and useful for the mod team.

I was wondering if you can / should just regularly flag any comment that does not seem optimal.

As said, sure thing, please feel free to flag any redundant or inappropriate content on the site, but don't overkill. Critical comments are a good thing and don't take things too personally.

...just small stuff like there's one small, minorly negative choice of word in there that could be improved;

No - do not overkill, handling nitty gritty semantic stuff is not what mods are here for. We are here to keep the site free of inappropriate posts and spam, but also to keep it clean.

...or a comment that asked for clarifying information in the past but is now irrelevant since the post was updated in response to it.

Yes - redundant comments should be removed and therefore flagged for mod attention. Don't overkill though; for instance, recent comments that have been dealt with by OP may still be useful for other users to see and especially for the mod team to assess the history of a post. Old, redundant comments can be flagged for removal, sure.
Comment: Comment down voting has already been raised https://meta.stackexchange.com/q/3615/349643
Comment: @ChrisRogers - yes, the comment votes have come across my mind too, but in the end, comments are basically meant for clarifications or tips to improve a post. Voting on those kinds of things can be useful in some cases, but it may be a bit over the top. It's a Q&A site after all, not a Q,A&comments site :)
Comment: *"I upvote and downvote a lot, and I recommend every user to do the same, including downvoting when necessary."* I agree. To add to that, sometimes the downvotes are more important than the upvotes because they nudge the person receiving them to improve the situation. I do wonder though whether comment downvotes ought to be added for disagreement with a comment. That then adds a utility value to the comment as well as the question/answer being commented on. I might raise that in the main meta


Ceiling fan mounting bracket issue

Question: first time poster.  I need to replace a Casablanca ceiling fan in my house that we've owned for a year.  The house was custom built in 2002.   I bought a Hunter ceiling fan to replace the old one, but the holes in the junction box (which match the Casablanca fan) are too narrow for the Hunter mounting bracket.  Can someone take a look at the attached pic and make a suggestion as to what options I have?  I'm confident that the junction box was installed when the house was built and would be really surprised if the box wasn't rated for a ceiling fan.
Thanks
Stan
Comment: That is a moist centered fan rated ceiling box. I installed one of these during my remodel 2 years ago. It is a standard mount, so I'm not sure what you mean by the mounting doesn't fit. Show picture of the fan mounting plate. The box shuld have 2 holes on each side. Looks like one is partially covered by ceiling texture.
Comment: Jeff, thanks. You're exactly right. The paint covered the holes I needed to use.  Thanks.
Comment: That's strange...I take it there's a joist behind the middle of the box?
Comment: why are you telling us how long you have owned the house?
Comment: ThreePhaseEel, don't know.  Box is on the lower level so there's no attic access. Jsotola, wanted to make clear that we're not original owners so we have no knowledge as to how the box was installed.
Comment: @StanMcFarland -- post that as an answer and I'll give you a +1 for it
Comment: I believe the long wood screws for the Hunter bracket will go through holes in the box and deep into the ceiling joist. Screw these in *firm* but do not over-tighten. I don't think you would crack the box, but you could if you over-tightened by a lot. I have installed several of these fans but it has been some time. I think the instructions are to drill a pilot hole, but the instructions seem to err on the low side for the drill diameter. To make the screws go in easier I use wax on the screws to reduce the torque required to drive the screws.
Comment: @jeff Cates please make your comment an answer so the op can accept it and this could help others with the same issue.
Answer: That is a joist centered fan rated ceiling box. I installed one of these during my remodel 2 years ago. It is a standard mount, so I'm not sure what you mean by the mounting doesn't fit. Show picture of the fan mounting plate. The box should have 2 holes on each side. Looks like one is partially covered by ceiling texture. Your mounting bracket should have elongated holes also, to help center the bracket over the holes.
Answer: First ascertain that the box is securely fastened to a building member.  Then drill holes and tap the back of the box to match the new bracket.

Ceiling fan mounting bracket issue


Query date in CQL

Question: I want to run an CQL query in Cassansdra DB by limiting the result by date, when i run a simple query without filtering i get the below result:
select * from bssapi.call_detail_records where subscription_id = '116377120' and year = 2020 and month = 3;

The result which i get is the below:
subscription_id | year | month | event_at                 | id                             | account_unit_type | b_number   | balance_after | balance_before | balance_id | basic_service_code | billable_amount | billable_unit | billing_item__code | call_case | call_destination | call_destination_type | cell_id  | created_at               | customer_id | data_amount | dc_event    | direction_type | duration | event_type | invoice_sequence_id | lac  | mcc | msisdn     | network_code | product_code | reference_price | roaming_indicator | service_category | service_type | subscription_type | technical_call_case | total_with_vat | transaction_amount
-----------------+------+-------+--------------------------+--------------------------------+-------------------+------------+---------------+----------------+------------+--------------------+-----------------+---------------+--------------------+-----------+------------------+-----------------------+----------+--------------------------+-------------+-------------+-------------+----------------+----------+------------+---------------------+------+-----+------------+--------------+--------------+-----------------+-------------------+------------------+--------------+-------------------+---------------------+----------------+--------------------
       XXXXXXXX | 2020 |     3 | 2020-03-01 07:45:51+0000 | POSTPAIDÿ3489472270ÿ2020-03-01 |                 0 | XXXXXXXX |           0.0 |            0.0 |       null |                 11 |              60 |       seconds |           BNATCALL |         0 |              066 |              national |     2730 | 2020-03-01 07:58:48+0000 |   XXXXXXXXXX|           0 | CALLNAT600R |            MOC |       16 |       CALL |             3626608 | 0A2A | 603 | XXXXXXXXX |        DZAOT |         null |             5.0 |                 0 |             null |            1 |          XXXXXXX|                1011 |            0.0 |                0.0

What i want is to get the result only for one day, for example the result only for today "2020-03-19 07:45:51+0000", i tried several query but i am not able to get a correct result, for example i tried the below:
select * from bssapi.call_detail_records where subscription_id = '116377120' and created_at > '2020-03-19 00:00:00' allow filtering;

The error returned is:
InvalidRequest: code=2200 [Invalid query] message="Partition key part year must be restricted since preceding part is"

Answer: Hm, I think you just need to provide your requirement for the field event_at like this:
select *
from bssapi.call_detail_records
where subscription_id = '116377120'
and year = 2020
and month = 3
and event_at = '2020-03-19 07:45:51+0000';

Comment: It's working fine thanks, now i want to get the count(*), when i am lunching the below query:
`
select count(*)  from bssapi.call_detail_records  WHERE  year = 2020  and month = 3 and event_at > '2020-03-01 07:45:51+0000' ;
`
Comment: i am getting this error :
`
InvalidRequest: code=2200 [Invalid query] message="Partitioning column "year" cannot be restricted because the preceding column (
"ColumnDefinition{name=subscription_id, type=org.apache.cassandra.db.marshal.UTF8Type, kind=PARTITION_KEY, componentIndex=0, inde
xName=null, indexType=null}") is either not restricted or is restricted by a non-EQ relation"
`
Comment: But when i user the filter by subscription_id, the count is given correctly
Comment: I suggest you create a new question for that, so that the title matches your issue and other people can help you there as well.

This question of yours here is resolved, so can you please accept my answer by ticking the checkmark? Thank you :)

Query date in CQL


How do I install a GFCI receptacle with two hot wires and common neutral?

Question: In my kitchen, I want to replace a regular 120V receptacle with a GFCI-protected receptacle. The instructions describe what to do with a regular 2-wire + ground feed, with and without daisy chaining to other receptacles, but not how to do it with a 3-wire + ground feed. Please describe how I should connect the new receptacle.
Here's a diagram of how the non-GFCI receptacle is currently wired, in my best 6-year-old artistry:

I think it's connected this way so that each receptacle in the kitchen has their two sockets supplied by different breakers. At the service panel the circuit is controlled by a joined pair of 15A breakers. I assume the white and black are separate 15A lines and the red is a common neutral (?).
Here are the instructions for connecting in a 2-wire scenario.

How do I connect this? Or should I consult an electrician?
EDIT
From The complete guide to home wiring
Comment: i just want to add one thing about when all the metal is hot in a home that should be grounded and its hot, it shocks people. i have found that most of the time all you need to do is put the bonding screw in the panel and the breaker of the problem circuit will trip. i have found this problem in many mobile homes as they have a main and then the panel. it has to be bonded somewhere or it never gets grounded.
Comment: Also relevant is the blog post [Demystifying the mystifying GFCI](http://diy.blogoverflow.com/2013/07/demystifying-the-mystifying-gfci/)
Answer: The first problem is that you may be using the wrong cable and breakers.  NEC calls for 2 20Amp small appliance circuits in the kitchen, to accomplish this you'll need to switch to 20Amp breakers and #12 wire.
The next problem. You'll have to pull new wire anyway, if you want to hook up GFCI receptacles. GFCI receptacles will not work properly with a shared neutral, you'll end up with nuisance tripping with a shared neutral.  GFCI receptacles work by monitoring the balance between hot and neutral, so if the neutral is shared the GFCI will not work properly.
To wire up the kitchen properly, you'll have to pull 2 new 12/2 cables from the breaker to the kitchen (all #14 wire on that circuit will have to be replaced). Then install 2 20Amp breakers, to supply the kitchen.  You'll install the GFCI's as the first receptacle on each circuit, which will protect all downstream receptacles.
You can share a neutral between 2 GFCI receptacles.  The catch is you'll have to pigtail the neutral to the receptacles, not use the neutral from the load side of the first GFCI to feed the second.
So you should be able to do something like this...

But not like this...

You'll then be able to use the load side of each receptacle to feed other devices, like this.
Comment: You have to pigtail neutral for TWO reasons: first GFCI as discussed, and second pigtailing neutrals is required on any multi-wire branch circuit, GFCI or not.  Removing a device must not sever the neutral to the other leg of the circuit.
Comment: Or you could pull 3-rope into a junction box (shared neutral, 2 20A breakers back in the panel) and then pull 2 rope from the J box to the GFCI outlets, if that helps keep it all straight. But it's the same thing whether you do that, or pigtail the neutral through the GFCI boxes themselves: the hot and neutral legs going to each GFCI device form a new branch circuit, so the neutral on that new branch is not shared with the neutral any other sibling branches, and the current flowing on the hot and neutral should always be the same (otherwise the GFCI is supposed to trip).
Answer: Most of what Gregmac has said is correct, however I have to correct a couple of small items. It is totally acceptable and often done to use a three wire circuit (black/red hot, white neutral & bare ground) like you have to "alternate" kitchen receptacles, thus giving you two circuits. It is not a code requirement to split the top and bottom of the recpts, however it is fine to do that, but it complicates the GFI functions. Splitting the top and bottom would require two GFI's upstream, one feeding each of the legs. More common would be two single pole GFI breakers in the panel.
With that said, your situation is different. I bet you will find that the the black feeds every other recpt, and likewise the red does the same thing with alternate recpts. Once you confirm that, simply install a GFI on the first powered recpt of each string (color). As a matter of fact, this is the most common way kitchens are wired and meets NEC.
Comment: The GFCI does ***not*** look at the difference between neutral and ground. It looks at the difference in current flowing on the hot vs neutral wires. Ground is not involved at all.
Comment: I finally installed my GFCI. I tried it both the way you describe, shirlock, and the way Tester101 describes. It must be done according to Tester, as your method shirlock does result in instant tripping of the GFCI protection.
Comment: Wouldn't the first GFCI constantly trip?
Comment: No it won't because it is looking at the difference between neutral and ground in reference to the local branch hot. Since both neutral and ground are supposed to be at the same potential throughout the house. The internal breaker is powered by the hot side on that branch only. So if the fault occurs in  recpt in that branch, only that GFI will trip.
Answer: I suspect that some writers are confusing the old Voltage Operated GFCIs with the new Current Operated GFCIs. The modern type contain a little toroidal transformer that the live and neutral are threaded through.  Normally the go and return currents are equal so the transformer does nothing.  If the currents are not equal the transformer produces voltage which operates the trip relay and cuts off the power.
The old type of GFCI uses an earth rod.  The house earth wires connect to one end of the trip-coil of the GFCI.  The other end of the trip coil connects to the earth rod.  If anything in the house leaks current the GFCI will turn off the power.  The problem with this type of GFCI is that electrical storms can blow the trip coil.  This leaves everything in the house un-earthed and with no GFCI.
One delightful property that I was asked to "look at" was giving everyone electric shocks. The floors were concrete and the bungalow had a voltage operated GFCI with a blown coil.  I suspected that the immersion heater element had also corroded and was now pumping current into the hot water system.  Water taps, light switches, the kitchen range and anything metal that was supposed to be earthed were all live!  The property was owned by a penniless widow and there was no money to do the job properly.  Power was supplied from a pole-transformer dropping the 11,000 volts to 240 and with these the neutral is always earthed at the pole.  After checking all the legal stuff it was decided to use PME (Protective Multiple Earthing) A heavy duty wire link was connected between the Neutral and the Protective Conductor (AKA "Earth") on the fuse-board where the power entered the building.  Result no more electric shocks! I did that "bodge" about thirty years ago and its still working fine.  Sadly the widow passed away long ago. She died of old age not electrocution.
IMHO those voltage operated GFCIs that date from the 1950s and 1960s ought to be banned. They probably are but people still use them.
One old house that had its wiring fixed by a friend had a two wire (live and neutral but no earth) system where the wires were let into grooves in wooden conduits.  A mouse had caused a short and blown a fuse.  If the Electricity Board had seen the antique wiring they would have demanded a full re-wire which would have cost thousands!  Take care!
Comment: I would think there'd be one situation where having a suitably-designed voltage-operated GFCI in addition to a current-operated one might be useful.  On "no equipment ground" outlets, a faulty appliance which connects its chassis to hot would not trip a current-based GFCI unless or until someone touches it.  A detector that watched for voltage between the ground pin and neutral, however, might be able to trip in such cases before anyone receives a shock, rather than merely limiting the duration of any shock thus received.
Answer: It depends what you want to protect.
If you just want to protect that outlet then it's easy. Pigtail the Black and white wires and connect them to the feed side of the GFCI. Leave the load side of the GFCI disconnected.
Where it gets tricky is if you want to also protect downstream outlets. Current that flows out through a GFCI must return through the same GFCI. Otherwise it will trip. So to protect both hots using GFCI outlets you would need two such outlets and you would need to keep the neutrals downstream of the GFCIs seperate which would likely require some rewiring.
An alternative may be to use a double pole GFCI breaker at the panel.
Another alternative is just to install a seperate GFCI at each outlet.
Answer: This "shared neutral" circuit is actually one circuit called a Multi-Wire Branch Circuit or MWBC.  You must comply with their rules.
Rule: You must pigtail neutrals. You can't use the 2 neutral screws to daisychain through the receptacle as you illustrated.
Shared-neutral circuits must use the same 2-pole breaker
(Okay. There's an exception involving handle-ties. But ignore that, because this segways into a very helpful thing!)
The two "hots" that share the neutral must be landed on a 2-pole breaker. This 2-pole breaker assures common maintenance shutoff (an MWBC rule) and that the hots are on opposite 120V poles (a very absolute MWBC rule).
Protect a shared-neutral with a 2-pole GFCI breaker
As it happens, they make 2-pole GFCI+breakers, which accept 2 hots and a neutral.  And that's what your cable is.
You fit the 2-pole GFCI breaker, attach its neutral pigtail, and bring all 3 wires: both hots and neutral to the GFCI breaker.  And you're done.
This will fully protect any legal configuration of MWBC/shared neutral circuit. You don't have to worry about how neutral is shared and firewalling line from load.  It just works.
"Oh, but 2-pole GFCI breakers are expensive" -- so are four GFCI+receptacles, as you show in the drawing in your edit.
If you must use many GFCIs - just don't use LOAD
If you absolutely insist on using GFCI+receptacle devices, well.... okay.   You can do as in your last drawing (in your edit).
This makes it a very simple rule: Don't remove the warning tape from the LOAD terminals.  Simple as that.  Of course, you'll be sitting there tempted, right? 2 wires in your hand and 2 screws you can't use--- nuh uh don't touch that tape!  You have to figure it out another way. Hands off!
This will lead you to a concept called pigtailing, which I remind you, you need to do with the neutrals anyway because of MWBC rules.  So, now you're doing it with the hots too.  Pigtail every connection onto the LINE hot and neutral, and voila.  You have GFCI protection everywhere you choose to fit a GFCI+receptacle.  And it didn't explode your brain.
Answer: Dont over complicate this.  It is very simple problem.  Just leave the red wire alone. No one here knows for sure what it is used for but it doesnt matter. Every electrician/homeowners wire things a little different. It could be right or wrong but if everything works dont worry about it.
Without using the red wire you can use the diagram you provided. The only thing to figure out is what wires is the hot feed. The easiest way to find this out is to turn off the breaker and disconnect one set of black and wire wires. Then put a separate wire nut on each and turn the breaker back on. if the outlet still works then the wires connected are hot. If not then obviously the wires you took off and capped are.  Now you have to decide if you want the rest of the outlets on this series to be protected by the GFI and connect your load wires up accordingly.  It will be label on the back of the gfi which load connection point is protected.
Comment: The phrasing I've used for this is "line" vs "load". Line is the power source (think of it as the power line from the utility pole) and the load is what is receiving power after that point.
Comment: If the wires form part of a multi-wire branch circuit then doing what you suggest will result in the GFCI tripping as soon as someone tries to use a socket on the red phase downstream of the GFCI.
Answer: BMitch's post is partly correct and dangerously wrong. 3 wire circuits of (2) 120V circuits sharing one neutral should be connected to lines with a 2-pole breaker, and MUST be on opposite phase (even/odd circuit breaker positions, 240V across breakers). Shared neutral carries unbalanced load such that 15 amps on one circuit, 5 amps on the other, results in 10 amp neutral current. 15 amps on each opposite phase circuit balance, cancelling neutral current to zero (0) amps. Sharing neutral on 2 same phase circuits (even/even - odd/odd circuit positions, 120 V across breakers) should NOT be done as it results in additive neutral current where 15 amps on each circuit result in 30 amps on neutral, dangerously overloading conductor. Adjacent single pole breakers should not be used, and skipping panel spaces for even/opposite circuit positions, should NOT be done - for safety reasons where turning one breaker off to work on a circuit can result in dangerous condition if shared neutral splice is opened, being energized via the shared circuit. Both circuits must be OFF.
Comment: Which post are you referring to? I edited an email address out of user15295's post, and shared a link in the comments to a blog on the topic of how gfic's work. Completely agree that a multi-wire branch circuit needs to have two different phases for the shared neutral.
Answer: Pigtail the neutral and the hot. This is the correct way to install any receptacle, GFCI or not.
Comment: Hi. You'll notice that the other answers to this question are a lot more detailed about what to do in this situation.
Comment: Also, the brevity of "pigtail the neutral and the hot" sounds at first blush as if you're saying pigtail the hot and the neutral *together*. Yes, I realize you mean pigtail the neutral, and then also pigtail the hot, separately, so that you actually create new little branch circuits. Really, though, you'd only need to pigtail the neutral, and you can't GFCI-protect regular downstream receptacles if you pigtail the hot. You have to feed them *through* the GFCI, using the "load" terminals. FWIW.
Answer: white, black, red wires/GFI receptacle
white carries unused power back.
Black n Red carry power in (to power your crap)
But be careful ( if black wire is attached to a breaker at the electrical panel that is labeled an even number and the Red is attached to an odd number (hard to notice stamped numbering on cover beside breakers) Odd to odd OK     Odd to even Not ok = 240 boom!
So if Black X  and red Y then proceed with:
black to Line holes on gfi (crap hooked up to Load)
Red wire dont hook up, twist together to pass to next location. Next location hook red to LINE on gfi and dont connect black.
just don't land black and red on same location, red gfi = microwave  black gfi = fridge red gfi = blender black gfi = coffee maker
White wire should go directly to each gfi without detour. don't use white from load or line off gfi but twist a bunch so 1 white hits black gfi 1 one white hits red gfi 2, back gfi 2, red gfi 2 ....etc.
regular non-gfi rules
you can share the white wire coming from any receptacle with the same color as long as the same colored wire and it's brother white wire are hooked up to a known even or odd label (stamped next to breakers) odd to even cross 120+120=240 even to even 120+120=0 since its the same Phase (odds are phase 1 separated from power on phase 2 evens) odds are all virtually the same 120 evens are virtually common with each other at 120. red and black make 240, red and red make 120 did i miss anything?
Comment: Extremely difficult to understand what you're trying to say, the existing answer with photos does a much better job. You're also failing to describe the problem of using load side of the GFCI when there's a shared neutral.
Comment: "White carries unused power back"?  ;-)
Comment: This isn't even wrong. You understand sharing neutral but you don't understand that the red and black **must be 240V apart** or else the neutral **will** overload.  You talk like they need to be 0v apart, and that is the disaster.  Look: just land black and white on a single 2-pole breaker, on every panel design known, that will force them to be correct.


Should a calendar date picker widget show leading zeroes in the selected date and month?

Question: In many -- possibly most -- calendar date picker widgets for U.S. users which display the selected date in month/day/year format, leading zeroes are shown when showing a single-digit month and/or day value. For example, the date March 1, 2018 would be rendered as 03/01/2018.
For example, here's the date picker on the expedia.com homepage (as of Feb 27, 2018):

However, most people (at least in the U.S.) don't actually write dates that way. They omit the leading zeroes, like 3/1/2018.
Is there a good reason that the MM/DD/YYYY format is in such common use in calendar date picker widets?  Have there been any usability analyses done that point to one displaying leading zeroes -- or not -- as being superior from a UX perspective?
Comment: Possible duplicate of [Do American users also confuse the day and the month in dates like 01/02/2013](https://ux.stackexchange.com/questions/39905/do-american-users-also-confuse-the-day-and-the-month-in-dates-like-01-02-2013)
Comment: @Garik, this question doesn't look like a duplicate of the question you mentioned. What do you find similar?
Comment: @Wanda, this question is about reason of leading zeros in dates' presentation (`3/1/2018` vs `03/01/2018`) in a date picker, not about the order of days and moths.
Comment: You're right. I'm not sure why I misread the question the first time. Apologies!
Answer: A possible reason might be that such format is already commonly used, easy to be specify in a form for people to understand in what format a date is expected.
Most people would understand what MM/DD/YYYY or DD/MM/YYYY means, and how to fill a form that has a box where such format written in a light gray color in its background, whether it's on a paper sheet or a web site.
It's vice to take advantage of that, and allow a user just type a date not using a calendar date picker extra functionality.
Though there is no reason not to recognize a date like 3/3/18 automatically converting it to 03/03/2018 in a text field, it's reasonable to encourage some generic format, that is most commonly used.
That's said, the format MM/DD/YYYY use is quite questionable itself. Perhaps, it's isn't the best possible format, since it's not that easy to analyze briefly looking at it, especially, for international use, when flights formatted as DD/MM/YYYY used in a country and there is a probability that the days and moths should be read contrariwise. The more universal one seems to be YYYY-MM-DD that is lexicographical ordered by default.
Answer: The leading zeroes are from the days of paper forms, where each digit had its own box and data entry was more manual. The emphasis there wasn't necessarily the usability of the form for the person filling it out, it was on the data entry step that would follow.
In the digital context, the emphasis is on the usability of the form. No one has to decipher the user's entry and enter it somewhere else. So, unless there's a reason why a digital date-picking (or form-filling) experience would benefit from leading zeros, I'd advise leaving them out in favor of the more legible 3/3/2018 format.
The 3/3/2018 format feels more human, not only because its easier to read quickly, but also because it's what most (Americans) would probably write freehand. 03/03/2018 feels mechanical, like we're communicating with a system. We are, of course, but we certainly don't want our users to feel that way.


Authenticate user after redirect

Question: I have two separate servers (s1 and s2) with two separate web applications running. The user is authenticated on s1 and by clicking a link gets redirected to s2. Is it possible to authenticate the user on s2 without having the user to enter his/hers credentials again?
My first thought was to encrypt a password with a secret key known by both servers and pass the encrypted string with the request. Is that enough? Is there a smarter way to go about doing this?
<code>  _________                             __________
  |   s1  |  GET (with encrypted pw)?   |   s2   |
  |       |  ----------------------->   |        |
  |_______|                             |________|
Authenticated                   Need to be authenticated
</code>
Thanks.
Comment: That just fine. You can make it a bit reusable by creating a web service like interface in s2.
Comment: Is it possible to get the secret key if you know the password (let's say it's a md5 hash)?
Comment: md5 is quite weak hashing algorithm. It can be cracked using brute force. use SHA256/SHA512 instead. Also make sure that you append a secret key to the password, such as "MyPassword" + "ASuperSecretKey" and you'll be secured
Answer: Yes, you can pass credentials in the querystring or use cross domain cookies.
http://www.15seconds.com/issue/971108.htm
http://anantgarg.com/2010/02/18/cross-domain-cookies-in-safari/

Authenticate user after redirect


Factorising a cubic

Question: Ok, so my question is relatively simple. I'm unsure how to factorise a cubic. Even simple ones i don't understand how to factorise them so i can eventually solve them.
I have two cubic functions in questions:
One is factorise: $2x^3 - 13x^2 + 22x - 8$
The other is solve: $x^3 -2x^2 -5x + 6x = 0$
If someone could explain in simple steps how to do these, and also if theres a certain process to factorising/solving cubics in general, it would be appreciated. Thanks
Comment: The second one has a solution $x=0$, and so reduces to a quadratic.
Comment: Rational roots theorem works well here.
Comment: I don't think i've learnt that theorem yet :/
Comment: I presume the second one should be $\cdots-5x+6=0$.
Comment: https://math.stackexchange.com/questions/2052616/is-there-anything-like-cubic-formula
Comment: http://www.maa.org/press/periodicals/convergence/how-tartaglia-solved-the-cubic-equation-tartaglias-solution-in-modern-notation
Answer: Here's the theorem: if a cubic $ax^3 + ... + d = 0$ with integer coefficients has a root, $r$ (or a factor $(x-r)$, which is the same thing) and that root is a rational number, then it's of the form
$$
r = \frac{p}{q}
$$
where $p$ is a divisor of $d$ and $q$ is a divisor of $a$. (Each can be positive or negative).
So in your first example, where $a = 2$ has positive divisors $1, 2$ and $d = 8$ has positive divisors $1, 2, 4, 8$, the only possible rational roots are
\begin{align}
\pm\frac{1}{1}\\
\pm\frac{2}{1}\\
\pm\frac{4}{1}\\
\pm\frac{8}{1}\\
\pm\frac{1}{2}\\
\pm\frac{2}{2}\\
\pm\frac{4}{2}\\
\pm\frac{8}{2}\\
\end{align}
If none of those are roots, you have to use Cardano's formula for the roots of a cubic, which is a pain in the neck.
To find whether any of those listed are roots...you just try each one. Fortunately, in that list there are several duplicates, which can save you some time.
Comment: Another divisor of $8$, is $8$.
Comment: Need more coffee. Fixed.

Factorising a cubic


Dependent drop down is not working

Question: In this below code i have 2 dropdown in one dropdown i get course code from course subject table and in another drop relevant subject code for selected course code from course subject table should be displayed. But i cant get the dependent dropdown subject code .Pls any one help me.
Controller:student_site
function search_by_course()
{
  $this->load->model('subject_model');
  $id = $this->input->post('subject_id');

  //get your data from model
  $res_subject = $this->subject_model->subject_list($id);
  $html_string = "";
  $html_string .= "<select id='subject_code_id'>";
  for($x=0;$x<count($res_subject);$x++)
  {
     $html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
  }
  $html_string .= "</select>";

  echo json_encode(array('html_string'=>$html_string));
}

model:student_model
function subject_list($id)
    {
        //echo "exam_name inside get_subject_records".$exam_name;
        //$this->db->select('course_code,subject_code');
        //$this->db->where('exam_name',$exam_name);
        $this->db->where('course_code',$course_name);
        $query = $this->db->get('coursesubject');
        return $query->result();
    }

view:student_detail_view

<?php

        $js = 'class="dropdown_class" id="course_code_id'.$row->id.'"    ';
        $js_name = 'course_code_id'.$row->id;
        echo form_dropdown($js_name, $data, $row->course_code, $js);

?>

Answer: Changes to do:
In view:

    <select id="subject_code_id"></select>

In controller:
function search_by_course(){
    $this->load->model('subject_model');
    $id = $this->input->post('subject_id');

    //get your data from model
    $res_subject = $this->subject_model->subject_list($id);
    $html_string = "";
    //$html_string .= "<select id='subject_code_id'>";
    for($x=0;$x<count($res_subject);$x++)
    {
     $html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
    }
    //$html_string .= "</select>";

    //echo json_encode(array('html_string'=>$html_string));
    echo $html_string;
}

Comment: the course code  dropdownis not calling javascript function @Nil'z
Comment: Do you get any js error in your console? Check your `console` and let me know.

Dependent drop down is not working


CorePlot Pie Chart: How to hide X and Y axes?

Question: The Following Code For Pie Chart CorePlot in ios:
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:hostingView];

    graph = [[CPTXYGraph alloc] initWithFrame:self.view.bounds];
    hostingView.hostedGraph = graph;

    CPTPieChart *pieChart = [[CPTPieChart alloc] init];
    pieChart.dataSource = self;
    pieChart.pieRadius = 100.0;
    pieChart.identifier = @"PieChart1";
    pieChart.startAngle = M_PI_4;
    pieChart.sliceDirection = CPTPieDirectionCounterClockwise;
    self.pieData=  [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:90.0],
                    [NSNumber numberWithDouble:20.0],
                    [NSNumber numberWithDouble:30.0],
                    [NSNumber numberWithDouble:40.0],
                    [NSNumber numberWithDouble:50.0], [NSNumber numberWithDouble:60.0], nil];
    [graph addPlot:pieChart];
    [pieChart release];

That's Output not hide x and y axis in the pie Chart....!
I need to hide X and y axis...!
Help Me ....!
Answer: The best way to do this is to remove the axes entirely.
graph.axisSet = nil;

Comment: @EricSkroch  Hi, Could you please have a look at my question? Thank you so much. http://stackoverflow.com/questions/25997224/the-axis-is-drawn-under-the-plot-in-core-plot


Weird error when testing `has_many` association with a conditional scope with Rspec & FactoryBot

Question: I am admittedly not great with Rsec & FactoryBot, so this could very well be due to my lack of experience, but I running into a weird issue when trying to test a has_many association with a where condition in which the unscoped association passes, but scoped association is empty but still has the correct count.
Here is the simplified setup:

Ruby 2.7
Rails 6.0
Rspec 3.12
FactoryBot 6.2

Models
class Club < ApplicationRecord
  has_many :members,
    inverse_of: :club,
    dependent: :nullify,
    autosave: true

  has_many :active_members,
    -> { where(active_status_id: [1, 2]) },
    inverse_of: :club,
    dependent: :nullify,
    autosave: true
end

class Member < ApplicationRecord
  belongs_to :active_status,
    inverse_of: :members

  belongs_to :club,
    inverse_of: :members,
    optional: true
end

Factories
FactoryBot.define do
  factory :club do

  end
end

FactoryBot.define do
  factory :member do

  end
end

Spec
RSpec.describe Club, type: :model do
  before do
    @club = create(:club)
  end

  describe 'clubs' do
    it 'a club is created' do
      expect(@club).to be_present # pass
    end
  end

  describe 'club members' do
    before do
      @member = create(:member, club: @club, active_status_id: 1)
    end

    context 'a new member' do
      expect(@member.approval_status_id).to eq(1) # pass
      expect(@member.club).to eq(@club) # pass

      expect(@club.members.count).to eq(1) # pass
      expect(@club.members.first).to eq(@member) # pass

      expect(@club.active_members.count).to eq(1) # pass
      expect(@club.active_members.first).to eq(@member) # fail ???

      # And when inspected, `@club.active_members` is: #<ActiveRecord::Associations::CollectionProxy []>
    end
  end
end

Why/how is the @club.active_members.count passing, but the @club.active_members.first fails?
Answer: Could you try reloading @club i.e @club.reload.active_members.first?
By calling @club.reload, you refresh the association and ensure that the newly created @member is included in @club.active_members.
Comment: This does work, but because doing so it's necessary in production, does reloading in the test create an unreliable or false precedent?
Comment: it's fine, in fact, it's very common in a Rails app - if you search for `reload` in the test files in the Rails repo, you'll see extensive use of reloads


How to print the comment author profile link

Question: I want to show comment author profile link inside the loop of my WordPress website.
I've tried get_comment_author_url() but it shows Facebook profile link of the comment author, instead I want to print his profile link in my WordPress website.
The final result should be something like example.com/author/john-smith
I cannot print only the nickname because John Smith (in camel case with space) is the nickname and displayed name and it should be formatted (users might be named with accents or special characters).
Answer: function force_comment_author_url($comment)
{
    // does the comment have a valid author URL?
    $no_url = !$comment->comment_author_url || $comment->comment_author_url == 'http://';
if ($comment->user_id && $no_url) {
    // comment was written by a registered user but with no author URL
    $comment->comment_author_url = 'http://www.example.com/?author=' . $comment->user_id;
}
return $comment;

}
add_filter('get_comment', 'force_comment_author_url');


TypeScript Duck Typing, not showing error on property string into number

Question: Not Duplicate
This is not the duplicate question because here my issue is in index signature not in object literal or type annotation. Please read carefully my question.
In few days I started to learn TypeScript. While when I reached at topic duck typing. I am confused in some of its basic rules.
Overview
In below code I have complete understanding. That, why we are using duck typing.
//Object declaration & initialization
let obj1 : {id:number, name:string};
obj1 = {id: 1,name: "Ahmer Ali Ahsan"};
//Error, missing property name
obj1 = {id:1};

let obj2 : {id:number, [obj2: string]:any};
obj2 = {id: 1, firstname: "Ahmer"};
//We add new property members due to index signatures
obj2 = {id: 2, firstname: "Ahmer", middlename:"Ali", lastname: "Ahsan"};
//We erase property members due to index signatures
obj2 = {id:2};

Problem
I have a question that if TypeScript is a type safety language. Then in below code I have all parameter types are number and index signature type is also a number.
let obj3 : {id:number, [obj3: number]: number};
obj3 = {id: 1, rollno: "Why error is not showing here?"};

Question
Why is there no error due to the [obj: number]: number index signature when I assign rollno to a string value?
Please explain briefly with your answers. If my concepts of index signature is still not clear.
Comment: Possible duplicate of [Type definition in object literal in TypeScript](http://stackoverflow.com/questions/12787781/type-definition-in-object-literal-in-typescript)
Comment: @Sheepy this is not a duplicate question because I am not taking about type annotation or object literal. My issue is related to index signature. Please ready carefully my question and complete detail of it. Thanks
Answer: Your interpretation: All keys of this object must be numeric, and all values must be of type number
Actual interpretation: All values reached by numeric keys must be of type number
Consider Array<boolean>. It has a numeric index signature to type boolean because e.g. accessing arr[0] produces a value of type boolean. But arr.toString (a key which is a string type) has type () => string, which is clearly not the same as boolean.

Edit to add based on comments.
Let's consider a declaration:
var x: { [n: number]: boolean; };

This is a numeric index signature. A numeric index signature says that properties with numeric names match a particular type. They have no effect on properties with non-numeric names.
Numeric index signatures only constrain properties with numeric names (not string names)
Numeric index signatures only constrain properties with numeric names  (not string names)
Numeric index signatures only constrain properties with numeric names  (not string names)
In other words, these are OK, because their key names are not numeric:
x = { hello: 100 }; // OK! 'hello' is not numeric
x = { rollno: 'wat!'}; // OK! 'rollno' is not numeric
x = { lookThisIsNotNumeric: false }; // OK! 'lookThisIsNotNumeric' is not numeric

Conversely, these are not OK, because the numeric-named properties do not fit the index signature type:
x = { 1: 'hello' }; // Error! 1 is a number and 'hello' is not a boolean
x = { 10: 653 }; // Error! 10 is a number and 653 is not a boolean
x = { 25: 'hello' }; // Error! 25 is a number and 'hello' is not a boolean

Finally, this is OK, because the numeric-named property has a boolean value:
x = { 42: true };

Comment: In other words, if a sign on a door said "All people wearing hats must be wearing shoes" and someone came through the door with *no hat* and *no shoes*, that's not a violation of the sign. Same here, the rule implied by the index signature is "All properties with numeric keys must be numbers".
Comment: I appreciate your answer. But its easy to me for understand. If you reference my index signature example in your answer.
Comment: In my example parameter rollno has type number but in below line I put string instead of number. Why its not showing me an error?
Comment: `rollno` is not a number, it's a string. string-keyed values are not subject to the constraints of the numeric index signature because you can't seen through a numeric key.
Comment: I understand your last comment but not understand your second last comment. If my rollno is not a number then in my index signature why I am using type number `[obj3: number]`. Please clear my miss understanding.
Comment: Added a bunch of examples. I cannot clarify further.
Comment: Finally this is the answer.Which I was looking for. Thanks for your precious time.


Ruby on Rails Test Database Not Committing New Records

Question: Is there a way to use Factory Girl to commit new changes to the test database in Ruby on Rails?
I have the following factory:
Factory.define :shipping_info do |si|
    si.name "Foo Bar"
    si.street "12 Candy Lane"
    si.country "US"
    si.zip "12345"
    si.state "IL"
end

And I have the the following test:
require File.dirname(__FILE__) + '/../../spec_helper'

describe CgCart::ShippingInfo do

   before(:each) do
      @order = Factory(:order)
      @order.order_line_item = Factory(:order_line_item)
      @shipping_info = Factory(:shipping_info)
   end

    it "order should not be nil" do
        @shipping_info.should_not be_nil
    end
end

When I run this test it passes. However, no new records are created in my test database. I need data in there for a Dameon to work with.
Any suggestions?
Answer: Using Factory.create(:order) should write that object to your database.
If you have transactional fixture set to true, all data that gets written to database gets rolled back after the tests finish.
You cant tail -f log/test.log before running your tests and you will see a lot of activity there.
I hope that clears your situation.
Comment: Did you mean you can use `tail -f` or you can not?


Assign localparam with concatenation satement?

Question: Here's what I'm trying to do . . .
localparam nine1 = {3{4'b0000}, 4'b1001};
localparam nine2 = {2{4'b0000}, 2{nine1}};

Is it possible to assign a localparam with a concat satement and then use that localparam in another localparam assignment? It seems like it would work, but I might have fuddled something up. This is not system verilog by the way.
Answer: Well, the error was that I wasn't wrapping my replication statements in {} inside the concatenation.
localparam nine1 = {{3{4'b0000}}, 4'b1001};
localparam nine2 = {{2{4'b0000}}, {2{nine1}}};

Subtle, but important.


How to use custom manager with related objects?

Question: I have a custom manager. I want to use it for related objects. I found   use_for_related_fields in docs. But it does not work the way I used it:
class RandomQueryset(models.query.QuerySet):

    def randomize(self):
        count = self.count()
        random_index = random.randint(0, count - 1)
        return self.all()[random_index]

class RandomManager(models.Manager):

    use_for_related_fields = True

    def get_query_set(self):
        return RandomQueryset(self.model, using=self._db)

    def randomize(self):
        return self.get_query_set().randomize()

I used it for one model:
>>> post = PostPages.default_manager.filter(image_gallery__isnull=False).distinct().randomize()

And tried to do the same with m2m related object:
>>> post.image_gallery.randomize()

Got an error:
AttributeError: 'ManyRelatedManager' object has no attribute 'randomize'

Is it possible to use a custom manager in the way I did it? If so, how do you make it work?
Edit
My models:
class ShivaImage(models.Model, ImageResizing):
    image = models.ImageField(upload_to='img')
    slide_show = models.BooleanField()
    title = models.CharField(max_length=100)
    text = models.TextField(max_length=400)
    ordering = models.IntegerField(blank=True, null=True)

    objects = RandomManager()

class PostPages(models.Model):
    image_gallery = models.ManyToManyField(ShivaImage, blank=True,
                                       related_name='gallery',)
    # all the other fields...

    objects = RandomManager()

Answer: For completeness of the topic, Django 1.7 (finally) supports using a custom reverse manager, so you can do something like that (just copying from the django docs):
from django.db import models

class Entry(models.Model):
    objects = models.Manager()  # Default Manager
    entries = EntryManager()    # Custom Manager

b = Blog.objects.get(id=1)
b.entry_set(manager='entries').all()

Answer: THIS IS ONLY SUGGESTED FOR Django 1.09 or older - Docs proof
Setting use_for_related_fields to True on the manager will make it available on all relations that point to the model on which you defined this manager as the default manager. This is documented here
class MyManager(models.Manager):
    use_for_related_fields = True
    # ...

I suppose you have it only enabled on your PostPages model, not on your Gallery model (or whatever the model is called that is referenced through post_image_gallery). If you want to have additionally functionality on this realtion manager you need to add a custom default manager with use_for_related_fields = True to your Gallery model!
Comment: Warning, as of Django 1.10 this feature is deprecated in favor of setting Meta.base_manager_name on the model. See release notes in https://docs.djangoproject.com/en/1.10/releases/1.10/#manager-use-for-related-fields-and-inheritance-changes.
Comment: Other warning: the docs also says that managers aren't used when querying on related objects. https://docs.djangoproject.com/en/1.11/topics/db/managers/#django.db.models.Model._base_manager. This prevents from using that feature to filter out related objects implicitely.
Comment: The _first_ manager defined becomes the default manager, no matter if it's called `objects` or not...
Comment: I defined the manager in both models. If I right understood, `objects` is means default manager. See question edits, I added models in there.
Comment: Uoo hooo! It's works! Most likely there was some very stupid mistake. Because now it's ok.
Comment: @DavidGuillot: Thanks. Any idea how to work around that related object query restriction? Do you know what is used instead of managers?
Answer: In django 2.0 use_for_related_fields is deprecated https://docs.djangoproject.com/en/2.0/releases/1.10/#manager-use-for-related-fields-and-inheritance-changes
You should use base_manager_name: https://docs.djangoproject.com/en/2.0/ref/models/options/#django.db.models.Options.base_manager_name
Updated docs: https://docs.djangoproject.com/en/2.0/topics/db/managers/#using-managers-for-related-object-access
class MyModel(models.Model):
    field1 = ...
    field2 = ...
    special_manager = MyManager()

    class Meta:
        base_manager_name = 'special_manager'

Comment: `base_manager_name` expects the name of the manager in question as a a string, not the instance. See [this](https://github.com/django/django/blob/8dc675d90f14a84ef95f16c7cc8100d9a04459b3/tests/custom_managers/models.py#L158).
Comment: for me, setting `base_manager_name` was even necessary when overrding default `objects` attribute in my model (before, I thought this would only be needed if manager name differs from default `objects`)!
Answer: Also, in the custom manager, make sure to access the queryset via the self.get_query_set()
proxy method when implementing custom filters to be called from related manager:
class EventManager(models.Manager):

    use_for_related_fields = True

    def visible_events(self):
        today = datetime.date.today()
        # don't do this !!!
        # unsuitable for related managers as could retrieve extraneous objects
        # qs = super(EventManager, self).get_query_set()
        # Use queryset proxy method as follows, instead:
        qs = self.get_query_set()
        qs = qs.filter(visible_from__lte=today, visible_to__gte=today)
        return qs

class Event(models.Model):

    visible_from = models.DateField(_(u'visible from'), null=False, blank=False)
    visible_to = models.DateField(_(u'visible to'), null=False, blank=False)
    concepts = models.ManyToManyField(Concept, through='ConceptEventRegistration')

    objects = EventManager()

Sample usage:
my_concept = Concept.objects.get(id=1)
# retrieve all events related to the object
my_concept.event_set.all()
# retrieve all visible events related to the object
my_concept.event_set.visible_events()


NetBeans debug session from REST client

Question: I frequently use the NetBeans debugger to step through my PHP applications. However, I also want to use the debugger when working on things that do not run in a web browser, per se (specifically a REST API).
Does anybody know how to start a NetBeans debugger session that will allow me to use my REST client as the "browser"?
Misc. info: Mac OS X, CocoaRestClient, NetBeans 7.1.2.
Answer: You need several things:

activate remote debugging in your server config (xdebug.remote_enable = 1 in php.ini then restart server)
generate a Xdebug IDE key from netbeans (I don't know how to do this with netbeans, but it won't be hard to find)
ensure that Neatbeans is listening the the DBGP port (usually 9000)
add a request parameter in each request sent with your client with:

name : XDEBUG_SESSION_START
value : [your IDE key]
For me, works like a charm with PHPStorm.
Comment: Perfect! Thank you so much. The Xdebug IDE key is simply netbeans-xdebug, for anyone else who is looking. Also remember that the XDEBUG_SESSION_START should be in the request body, not in headers (something I was doing for a while).
Answer: To help with PHPStorm's recent REST Client - here's a screenshot of the appropriate settings. Make sure to, in settings, change the DBGP listening port from 9001 to 9000 if not set already. Thanks for the answer!
http://screencast.com/t/WsZzApBORssx

NetBeans debug session from REST client