Showing Div Boxes with content when clicking on link

Question: I am working on a portfolio website and on my homepage I am trying to set it up where you click on navigation links and content boxes appear. My CSS for my div boxes work, and I am able to hide them with JQuery.  The problem is the boxes don't appear when I click on the link.  I'm thinking it has something to do with my link href attributes, but I'm not sure.  I included the portions of my code that have to do with this issue.  Any help would be appreciated.
HTML

Skills

Resume

Work and Education

</div

Javascript/JQuery
$(document).ready(function(){
    $("#Skills").hide();
    $("#Resume").hide();
    $("#Education").hide();

    $("#skills").click(function(){
        $("#Skills").show();
        $("#Resume").hide();
        $("#Education").hide();
    });

    $("#works").click(function(){
        $("#Skills").hide();
        $("#Resume").show();
        $("#Education").hide();
    });

    $("#education").click(function(){
        $("#Skills").hide();
        $("#Resume").hide();
        $("#Education").show();
    });
});

CSS
#HomeNav {
     position: relative;
     width: 1200px;
     height: 750px;

}
#Navabsolute {
    position: absolute;
    top: 30px;
    left:110px;
}

#Skills {
    width: 300px;
    height: 300px;
    background-color: red;
}

#Resume {
    width: 600px;
    height: 600px;
    background-color: blue;
}

#Education {
    width: 300px;
    height: 300px;
    background-color: green;
}

Comment: @ObsidianAge - Well it may be illegal but work anyway in some browsers, I don't know. The OP's code worked for me once I fixed the missing `>` at the end of the HTML, so I guess the IDs did work in Chrome. Either way it makes the code hard to read.
Comment: Was the missing `>` on the end of ` at the end of the div tag for my education content box, so that wasn't causing the problem for me anyway.  I did go head and change the id values of my links to avoid the case sensitivity and the naming confusion.  That still didn't fix the issue for me.
Comment: So I am coding this in visual studio using ASP.NET MVC and can't get it to work.  It will work just fine with a regular text editor, but for some reason the jquery code won't work in visual studio.  I have no idea why that is.  The div boxes hide just fine, but they won't appear in visual studio like they would in another text editor.  Its pretty strange.
Answer: Hi looks like your id for div box is a bit confused. I have changed your div id and run Jquery it looks work to me.
just have look at following code it may help.

 skills

 works

 education

Comment: Thanks for the input, but I tried it in a regular text editor as well and it works like a charm.  The problem is I'm actually working with this in Visual Studio with ASP.NET MVC and its not working.  I have no clue what is going on there.  Is there a right way to get jquery to fully run properly with ASP.NET?


Fill multi-value field from comma separated values in a field

Question: I have data in xml which I want to import into drupal. Which works fine. But one field in the xml is filled with a comma separated list of terms. There is a target field in drupal which is a multi-valued field. I do not need those as a taxonomy, just as multi-value for solr search. I just want to expand the one,fourty,flower,... values to fill the multiple-value field.
It absolutely will not work. Any help?
Here is the latest iteration (I tried a lot in the last two days) which fails spectacularly with an error like so:
Error: Unsupported operand types in /var/www/dev.diercke.com/web/core/modules/migrate/src/Plugin/migrate/process/SubProcess.php on line 206 #0 /var/www/dev.diercke.com/web/core/modules/migrate/src/MigrateExecutable.php(399): Drupal\migrate\Plugin\migrate\process\SubProcess->transform(Array, Object(Drupal\migrate_tools\MigrateExecutable), Object(Drupal\migrate\Row), 'field_stichwort...')
#1 /var/www/dev.diercke.com/web/core/modules/migrate/src/MigrateExecutable.php(205): Drupal\migrate\MigrateExecutable->processRow(Object(Drupal\migrate\Row))
#2 /var/www/dev.diercke.com/vendor/drush/drush/includes/drush.inc(206): Drupal\migrate\MigrateExecutable->import()
#3 /var/www/dev.diercke.com/vendor/drush/drush/includes/drush.inc(197): drush_call_user_func_array(Array, Array)
#4 /var/www/dev.diercke.com/web/modules/contrib/migrate_tools/src/Commands/MigrateToolsCommands.php(958): drush_op(Array)
#5 [internal function]: Drupal\migrate_tools\Commands\MigrateToolsCommands->executeMigration(Object(Drupal\migrate\Plugin\Migration), 'karte', Array)
#6 /var/www/dev.diercke.com/web/modules/contrib/migrate_tools/src/Commands/MigrateToolsCommands.php(418): array_walk(Array, Array, Array)
#7 [internal function]: Drupal\migrate_tools\Commands\MigrateToolsCommands->import('karte', Array)
#8 /var/www/dev.diercke.com/vendor/consolidation/annotated-command/src/CommandProcessor.php(257): call_user_func_array(Array, Array)
#9 /var/www/dev.diercke.com/vendor/consolidation/annotated-command/src/CommandProcessor.php(212): Consolidation\AnnotatedCommand\CommandProcessor->runCommandCallback(Array, Object(Consolidation\AnnotatedCommand\CommandData))
#10 /var/www/dev.diercke.com/vendor/consolidation/annotated-command/src/CommandProcessor.php(176): Consolidation\AnnotatedCommand\CommandProcessor->validateRunAndAlter(Array, Array, Object(Consolidation\AnnotatedCommand\CommandData))
#11 /var/www/dev.diercke.com/vendor/consolidation/annotated-command/src/AnnotatedCommand.php(311): Consolidation\AnnotatedCommand\CommandProcessor->process(Object(Symfony\Component\Console\Output\ConsoleOutput), Array, Array, Object(Consolidation\AnnotatedCommand\CommandData))
#12 /var/www/dev.diercke.com/vendor/symfony/console/Command/Command.php(255): Consolidation\AnnotatedCommand\AnnotatedCommand->execute(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#13 /var/www/dev.diercke.com/vendor/symfony/console/Application.php(1027): Symfony\Component\Console\Command\Command->run(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#14 /var/www/dev.diercke.com/vendor/symfony/console/Application.php(273): Symfony\Component\Console\Application->doRunCommand(Object(Consolidation\AnnotatedCommand\AnnotatedCommand), Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#15 /var/www/dev.diercke.com/vendor/symfony/console/Application.php(149): Symfony\Component\Console\Application->doRun(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#16 /var/www/dev.diercke.com/vendor/drush/drush/src/Runtime/Runtime.php(118): Symfony\Component\Console\Application->run(Object(Drush\Symfony\DrushArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#17 /var/www/dev.diercke.com/vendor/drush/drush/src/Runtime/Runtime.php(48): Drush\Runtime\Runtime->doRun(Array, Object(Symfony\Component\Console\Output\ConsoleOutput))
#18 /var/www/dev.diercke.com/vendor/drush/drush/drush.php(72): Drush\Runtime\Runtime->run(Array)
#19 /var/www/dev.diercke.com/vendor/drush/drush/drush(4): require('/var/www/dev.di...')
#20 {main}
Error: Unsupported operand types in Drupal\migrate\Plugin\migrate\process\SubProcess->transform() (line 206 of /var/www/dev.diercke.com/web/core/modules/migrate/src/Plugin/migrate/process/SubProcess.php).
 [warning] Drush command terminated abnormally.

...
process:
...
  field_stichworte: tags
  field_stichworte_einzeln:
    - plugin: explode
      source: tags
      limit: 10000
      delimiter: ,
    - plugin: deepen
    - plugin: sub_process
      process:
        field_stichworte_einzeln:
          - plugin: extract
            index:
              - 0
...

Answer: I found a solution:
fields:
    ...
    -
    name: keywords_with_comma
    label: 'keywords'
    selector: keywords
    ...
process:
    ...
    field_keywords_multi:
        - plugin: explode
          delimiter: ','
          source: keywords_with_comma
        - plugin: single_value
        - plugin: multiple_values
    ...

Comment: Perfect, thx a lot!


Pass data between views in ExtJS

Question: I am reading data from store and populating main girdView. When any of the row is clicked, a windows appear and I want to fill the fieldset in that window with the same record which is clicked.
Can anyone tell me how to do it?
My popup window is like:
{
    extend: 'Ext.window.Window',

    height: 500,
    width: 1500,
    minWidth :1500,
    maxWidth :1500,
    layout: 'fit',
    controller: 'PopUpWindowController',

    initComponent: function () {

        var me = this;

        //console.log(me.myExtraParams);
        var Store = Ext.getStore('mainStore');

        Ext.applyIf(me, {
         /*   items: [{
                xtype: 'form',
                bodyPadding: 10,
                region: 'center'
            }]*/

        });
        me.callParent(arguments);
    },
        items: [
    {
        xtype: 'panel',
        title : 'Projektierung',
        bodyStyle : 'padding:5px',
        width : 1880,
        autoHeight : true,
        items:
        [
            {
                xtype  : 'kopfdatenView', // Have to populate this view
            }
        ]
}]}

and in Main view I am calling it as:
{
                region: 'center',
                xtype: 'gridpanel',
            listeners : {
                itemdblclick: function(dv, record, item, index, e) {

                    var extra = record.data;
                    win = Ext.create('App.view.PopUpWindow');

                    console.log(win.myExtraParams);

                    win.on('show', function(win) {

                     win.setTitle(record.get('ID'));
                    });

                    win.show();
                }
            },

             columns: [
                      ****
                    ],
            store: 'mainStore',
            height: 100,
            width: 400,

        }

I want to  populate fieldset in kopfdatenView. Kindly help
Comment: @xaume first of all, you should write such things in comments. Also I have added the code in my question
Answer: You can do something like this:
 win = Ext.create('App.view.PopUpWindow', {
           params: record
       });

Then, in your PopUpWindowController you can retrieve 'params' in the render event (for example).
Comment: first of all, you should write such things in comments. Also I have added the code in my question
Comment: I am marking your answer as useful cause you gave me a right answer but you didn't tell me how to access it in the other view(which @3rgo's answer does tell and that is why I am accepting that as "accepted answer").
Thanks a lot.
Answer: You directly pass your record to your window on creation :
win = Ext.create('App.view.PopUpWindow', {
    myRecord: record
});

And then inside the window's initComponent function (before the callParent) :
this.title = this.myRecord.get('ID');

Comment: Thanks,
It works, though there was not get function so I had to accept data as this.myRecord.ID.
But This helped me  a lot. Thanks

Pass data between views in ExtJS


Como utilizar a instrução Assert?

Question: A Docuentação informa que:

Durante o desenvolvimento, use uma declaração assert para
  interromper a execução normal se uma condição for falsa.

A instrução assert garante por exemplo, a manipulação de valores nulos durante o desenvolvimento, evitando possíveis erros em tempo de execução.
Exemplo:
void main() {
  Nome(null).imprimir();
}

class Nome {
  Nome(this.nome) : assert(nome != null && nome.isNotEmpty);
  final String nome;

  imprimir(){
    print('Meu nome é $nome');
  }
}

Imprime: Meu nome é null //mas deveria gerar uma exception

Qual o motivo desse exemplo não se comportar da maneira esperada?
https://dartpad.dartlang.org/d98ad76b6e985e6cff27ecc7aea07d29
Comment: A opção `--enable-asserts` deve ser passada juntamente com o arquivo que será executado, para ativar os `AssertionError`s. Já [tentaram pedir que oferecessem um meio de ativar essa opção pelo DartPad](https://github.com/dart-lang/dart-pad/issues/310).
Comment: Isto é, dependendo da ferramenta também que está sendo usada para executar o programa, conforme diz a documentação.
Comment: @GustavoSampaio Se possível coloque como resposta exemplificando o uso no console Dart, ficaria ainda melhor com print do resultado.
Comment: Ok, vou elaborar a resposta.
Answer: Antes de tudo, vamos só contextualizar um pouco.
Mecanismos de depuração durante desenvolvimento
Muitas vezes se faz necessário, durante o desenvolvimento de uma aplicação, adicionar certos mecanismos de depuração para poder se ter noção se cada parte dela está funcionando da maneira adequada.
Esses mecanismos, ou ferramentas, podem vir de forma separada, ou até mesmo como uma característica já presente (acho que posso dizer, nativa) na linguagem que está sendo usada para desenvolver a aplicação.
Exemplos que se encaixam no grupo das "ferramentas à parte" são as ferramentas para elaboração de testes, além dos sistemas de depuração embutidos em IDEs (e alguns editores de textos).
E um exemplo que se encaixa no outro grupo é exatamente esse que aqui se trata, isto é, a estrutura assert, que serve para, em modo de desenvolvimento na maioria das vezes, atribuir condições que devem se tornar verdadeiras. E caso não se tornem, gerem uma interrupção.
Usando a estrutura assert em Dart
Conforme citei acima, e até como diz a documentação do Dart, a estrutura assert pode ser usada na sua aplicação para que haja uma interrupção na execução caso uma expressão retorne valor booleano falso, isto é, false. Usando até o exemplo dado na questão, pode-se entender isso:
void main() {
  Nome(null).imprimir();
}

class Nome {
  Nome(this.nome) : assert(nome != null && nome.isNotEmpty);
  final String nome;

  imprimir(){
    print('Meu nome é $nome');
  }
}

Ou seja, a estrutura assert deve garantir (e mais uma vez lembro, durante o desenvolvimento) que o valor passado como argumento para o construtor da classe Nome (e que será guardado no campo nome):

Não é nulo (null);
E, sendo uma string, não é uma string vazia.

Além disso, você pode ainda fornecer uma mensagem customizada para caso a condição não seja atendida, dessa forma:
Nome(this.nome) : assert(nome != null && nome.isNotEmpty, "'nome' está se tornando nulo ou é uma string vazia");

Como executar da forma correta?
Dependendo de como o código-fonte será compilado, são feitos procedimentos diferentes, conforme diz a documentação.
Usando a ferramenta dartdevc
Essa ferramenta, assim como o dart2js, é utilizado para converter código Dart em código JavaScript, já que o Dart também pode ser utilizado na web. A diferença é que o dartdevc, como o nome pode sugerir, é usado para desenvolvimento somente, portanto, ele deixa as estruturas assert ativas. Dessa forma, basicamente, para compilar usando essa ferramenta, usa-se isso:
dartdevc <nome_do_arquivo_fonte>.dart -o <nome_do_arquivo_resultante>.js

Usando as ferramentas dart e dart2js
Já as ferramentas dart e dart2js (a última ainda mais por ser para produção) exigem que seja passada a opção --enable-asserts para que as estruturas assert funcionem. Assim, para compilar o código-fonte, faz-se:
dart --enable-asserts <nome_do_arquivo_fonte>.dart

// ou

dart2js --enable-asserts <nome_do_arquivo_fonte>.dart [-o <nome_do_arquivo_resultante>.js]

Caso não seja passada a opção, as estruturas assert que tiverem presentes não terão efeito.
E conforme pedido, aqui está uma screenshot do uso com e sem a opção:

E também com a mensagem customizada:

Usando asserções no Flutter
E para utilizar-se das asserções no Flutter, basta que o app esteja sendo executado no modo debug, que geralmente é o modo padrão durante o desenvolvimento.

Espero ter ajudado!

Como utilizar a instrução Assert?


Why does flipping not keep nice-sounding things nice?

Question: If you "flip" all of the notes (so that a half step up becomes a half step down), then the G-B-D-F chord (which sounds nice) turns into the B-D-F-A chord.
Well, I suppose I should say the A-F-D-B chord, since the G "flips" to the A, the B "flips" to the F, etc.
What are these chords called? But, more importantly, how come the first one sounds nice but the second one doesn't? They have all the same intervals, so shouldn't they sound equally pleasing?
Answer: Welcome to Music.SE!
This is tough to answer because everyone has a different interpretation of "nice." So whereas you might not think B D F A sounds "nice," plenty of others do!
What we can say is that they'll certainly sound different, since you're inverting the makeup of the chord. While G B D F is built (from the bottom up) with a major third and two minor thirds, B D F A is built (from the bottom up) with two minor thirds and a major third. Much like how tangrams create different images using the same pieces,

so too will these chords be different, despite being made of the same intervals.
But these chords are called inversionally symmetrical. In your case, all of the pitches invert (or "rotate") around the pitch axis of G♯:

G is a half step below G♯, so it inverts to A, a half step above
B is a minor third above G♯, so it inverts to F, a minor third (=augmented second) below
D is a tritone away from G♯, so it inverts to itself (D), also a tritone away
F is an augmented second below G♯, so it inverts to B, a minor third (=augmented second) above

Related Questions:

Negative harmony and "rotating around the axis"
Correct process for deriving the 'mirror' or 'negative' harmony of a progression
Is the IV chord a perfect fifth in disguise?
Answer: Chords are frequency components.  A seventh chord (with a "blue" seventh from the overtone series having a frequency ratio of 7/4 rather than the nominal 9/5) has the frequency relations 1 : 5/4 : 3/2 : 7/4 with a greatest common divider of 1/4, two octaves below the fundamental: if you indeed use these frequency ratios, the resulting signal has a periodicity of the note two octaves below the fundamental note.  Using a "proper" seventh and/or equal-tempered tuning breaks this mathematical relation but the sound is close enough to still hint at it.
Reverting the relations yields frequency ratios 1 : 4/5 : 2/3 : 4/7 with a greatest common divisor of 1/105.  Even if you use the last (lowest) note as reference, you get 7/4 : 7/5 : 7/6 : 1 with a common divisor of 1/60.  Neither ratio results in a periodicity that has a reasonably straightforward relation to the original pitch.
So chords that are to some degree modeled after overtone series result "almost" in a periodic signal with a period in reasonably straightforward relation to the chord fundamental.  Inverting the frequencies does not result in a similarly straightforward relation since the relation of "notes with overtones" cannot just be swapped to "notes with undertones".  For starters, the various notes could not have overtones themselves for that concept to work: you'd have to work with pure sines.  Those do not actually form chords as nicely as one would think as the blending of overtones is missing.  And the concept of "undertones" just does not have a similar mathematical connection to periodicity as "overtones" have.
Chords and scales don't exist in a vacuum, and the tradeoff between their symbolic musical meaning and the underlying physics falls apart when inverting the frequency relations: in that case, only the symbolic meaning remains.
And that, on its own, is more arbitrary than we are used to.
Answer: I agree that to the normal ear, B D F A does not sound particularly nice, however all chords such as these sound nice in their rightful place - the example you gave of flipping a Gmaj7 gives you a Bmaj7 diminished which is commonly used in jazz.
The reason simply inverting 'nice' chords doesn't always give you another 'nice' chord is because of which notes sound prominent. The bass note and the highest note tend to stand out.
In the case of the G chord, the bass note G stabilises 3rd, 5th and 7th so they do not sound like a diminished chord. If you have heard the rule that in orchestration you should not 'double the third' then you may understand this further. Putting the 3rd (B) at the top - as you have done in your flipping - is a bit like doubling the 3rd (B) in an orchestration. It makes it more prominent and takes over the rest of the chord, making it sound diminished.
The reason inverting intervals does not work in the way you want is because of the way degrees and intervals of a scale are found. For example: take the key of C. The 4th is F and the 5th is G. This is working up from C. However, F to the C an octave above is a 5th, similarly G to that same C is only a 4th. Just as velocity changes when direction changes even when the speed is the same; intervals change when the direction changes even if the notes used are the same.


Powershell getting stuck when doing webrequest

Question: I currently have to get the size of some files stored on a webserver for the implementation of an update mechanism. Getting the file size works with my script, but whenever I call the function multiple times, it gets stuck at WebRequest.GetResponse(). When it gets stuck, I can't even stop the script with Ctrl-C. Does somebody know why this is happening or if there is a better way of doing this?
In the example I'm getting a test text file
Powershell script:
function GetWebFileSize($fileurl) {
    try {
        Write-host "Getting size of file $fileurl"
        $clnt = [System.Net.WebRequest]::Create($fileurl)
        $resp = $clnt.GetResponse()
        $size = $resp.ContentLength;
        Write-host "Size of file is $size"
        return $size
    }
    catch {
        Write-host "Failed getting file size of $fileurl"
        return 0
    }
}

[int]$counter = 0;

while (1 -eq 1) {
    $counter++;
    GetWebFileSize "https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md"
    Write "Passed $counter"
}

Output of powershell (picture)
The output:
C:\> .\WebFileSizeTest.ps1
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Size of file is 1003
1003
Passed 1
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Size of file is 1003
1003
Passed 2
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Failed getting file size of https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
0
Passed 3
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Failed getting file size of https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
0
Passed 4
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Failed getting file size of https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
0
Passed 5
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md

Comment: Some websites block HTML scrapers and other bots. You may need to change your agent string and/or keep some (random) delay between requests to hide the fact you are a bot.
Comment: I tested this aswell on the local server i'm getting the file from, and there is no bot detection / blocking. I'm getting the same result there, even if i change the user agent or I add a delay of a second
Comment: I suggest to remove the try-catch block, so you get to see the actual error message.
Comment: There's still no additional output
Comment: The equivalent in C# doesn't get stuck. The only difference is I'm closing the response after using, so that stream is disposed. Even with that change above code doesn't work. Have you tried using Poweshell command `Invoke-WebRequest` ?
Answer: Thanks @derloopkat for the solution. I forgot to Dispose the WebRequest object. So the code that's now working for me is:
    Write-host "Getting size of file $fileurl"
    $clnt = [System.Net.WebRequest]::Create($fileurl)
    $resp = $clnt.GetResponse()
    $size = $resp.ContentLength;
    $resp.Dispose();
    Write-host "Size of file is $size"
    return $size


Excel: Calculate average daily usages of gas based on date and time

Question: awkward question to word. I'm using Excel and would like to calculate the average usage of gas in my house. I have got a list of times and dates which I write down when I get chance or remember, is there a good way to do this?
I would like to use cell formulas by the way.
An example of the data I have to work with:
<code>  Date/Time         Gas   Electric
25/01/15 01:48    £10.62    £3.38
                           +£5.00
26/01/15 01:48    £8.56     £6.92
26/01/15 02:00    £8.18     £6.45
27/01/15 13.19    £7.44     £6.03
27/01/15 18.00    £7.06     £5.57
27/01/15 19:50    £7.06     £5.41
27/01/15 21:14    £6.97     £5.26
</code>
Edit:
Using TriHard8's answer, this is what is produced

Does this mean that 0.70 pence is used each hour based on the two times?
Edit 2:
Still getting negative numbers :S
Comment: Do you want gas/hour?  gas/minute?  You can convert dates and times to integers to do math with them.
Comment: gas/day would be ideal. So maybe detect when it's a new day work out how much has been used, and maybe fill in the gaps when I didn't write down how much used throughout the rest of the day, if that makes sense?
Comment: I made a few mistakes, but it should be good now.  Is that what you were looking for?
Comment: The average is just (First reading - Last reading) / (Last time - First time) so the times and readings in between are irrelevant.
Comment: The units should be £ / day. As you used about £2 of credit in a day, the answer should be around 2 (or -2, since the credit is going down). That's what I got when I tried it, but I can't work out how it came to -.70 in the screenshot.
Answer: Gas used between 2 dates/times divided by ((Date2 + Time2) - (Date1 + Time1)).  (10.62 - 8.56) / ( (26/01/15 + 01:48) - (25/01/15 + 01:48) )
Put this formula into H6: =( F5 - F6 ) / ( (D6+E6) - (D5+E5) )
This will be use per day.  It doesn't matter if you compare 2 measurements from the same day, or over 20 days, it will be the average per day.
You need to make sure that you format the resulting cell to be a number, with whatever precision you'd like.
Comment: Why did you put SUM?  Should be =(10.62 - 8.56) / ( (25/01/15 + 01:48) - (26/04/15+01:48) )
Comment: @MartynBall I redid my answer.  I was in a hurry and kept switching signs.  You shouldn't end up with a negative number.
Comment: @MartynBall I noticed that earlier.  Something is wrong with your data.  On Jan 27 at 4:33AM you have 7.44 units of gas, but on Jan 27 at 1:26AM (before 4:33AM) you have 7.06 units.  So unless someone filled gas in that 3 hours, your data is incorrect.  Is 1:26AM supposed to be 13:26?  Also, you entered the formula incorrectly b/c H6 should be 2.23.  Which means you used 2.23 units per day based on the 2 dates.
Comment: Updated my post again


Finding true positive / negative and false positive / negative rates using R

Question: I have a data frame with two classes. I want to find the true positive and false positive rate and then plot the ROC curve.
I tried this:
new <- data.frame(ytrue=c(1,0,1,1,0,0,1,0,1,0),
                  ypred=c(0.98,0.94,0.86,0.74,0.73,0.64,0.53,0.39,0.34,0.31))
new
 ytrue ypred
1      1  0.98
2      0  0.94
3      1  0.86
4      1  0.74
5      0  0.73
6      0  0.64
7      1  0.53
8      0  0.39
9      1  0.34
10     0  0.31

library(ROCR)
pred <- prediction( new$ypred, new$true )
pred
An object of class "prediction"
Slot "predictions":
[[1]]
 [1] 0.98 0.94 0.86 0.74 0.73 0.64 0.53 0.39 0.34 0.31

Slot "labels":
[[1]]
 [1] 1 0 1 1 0 0 1 0 1 0
Levels: 0 < 1

Slot "cutoffs":
[[1]]
 [1]  Inf 0.98 0.94 0.86 0.74 0.73 0.64 0.53 0.39 0.34 0.31

Slot "fp":
[[1]]
 [1] 0 0 1 1 1 2 3 3 4 4 5

Slot "tp":
[[1]]
 [1] 0 1 1 2 3 3 3 4 4 5 5

Slot "tn":
[[1]]
 [1] 5 5 4 4 4 3 2 2 1 1 0

Slot "fn":
[[1]]
 [1] 5 4 4 3 2 2 2 1 1 0 0

Slot "n.pos":
[[1]]
[1] 5

Slot "n.neg":
[[1]]
[1] 5

Slot "n.pos.pred":
[[1]]
 [1]  0  1  2  3  4  5  6  7  8  9 10

Slot "n.neg.pred":
[[1]]
 [1] 10  9  8  7  6  5  4  3  2  1  0

perf <- performance( pred, "tpr", "fpr" )
perf
An object of class "performance"
Slot "x.name":
[1] "False positive rate"

Slot "y.name":
[1] "True positive rate"

Slot "alpha.name":
[1] "Cutoff"

Slot "x.values":
[[1]]
 [1] 0.0 0.0 0.2 0.2 0.2 0.4 0.6 0.6 0.8 0.8 1.0

Slot "y.values":
[[1]]
 [1] 0.0 0.2 0.2 0.4 0.6 0.6 0.6 0.8 0.8 1.0 1.0

Slot "alpha.values":
[[1]]
 [1]  Inf 0.98 0.94 0.86 0.74 0.73 0.64 0.53 0.39 0.34 0.31
plot(perf)

I am unsure of the output. And the ROC curve looks like a step function plot.
Answer: The plot is just fine. After you run prediction() from the package ROCR you get an object, pred, with several components. Two of them are pred$tp and pred$fp, which represent the number of true positives and false positives respectively. To calculate the rate you divide them by the maximum, which is 5 in this case:
tpr <- pred$tp/max(pred$tp)
fpr <- pred$fp/max(pred$fp)

plot(fpr, tpr, type = "l")

These values are the same you get after running performance(pred, "tpr", "fpr"). Check the x.values and y.values components in perf. These are the values plotted with plot(perf). You get an identical plot using plot(fpr, tpr, type="l"). The plots look like a step function because you only have five values.

UPDATE
It seems the structure of the object returned by prediction() has changed in recent ROCR versions. Now prediction() returns an S4 object, and so the information is stored in slots. This would be how the result from the OP data would look like now:
An object of class "prediction"
Slot "predictions":
[[1]]
 [1] 0.98 0.94 0.86 0.74 0.73 0.64 0.53 0.39 0.34 0.31

Slot "labels":
[[1]]
 [1] 1 0 1 1 0 0 1 0 1 0
Levels: 0 < 1

Slot "cutoffs":
[[1]]
 [1]  Inf 0.98 0.94 0.86 0.74 0.73 0.64 0.53 0.39 0.34 0.31

Slot "fp":
[[1]]
 [1] 0 0 1 1 1 2 3 3 4 4 5

Slot "tp":
[[1]]
 [1] 0 1 1 2 3 3 3 4 4 5 5

Slot "tn":
[[1]]
 [1] 5 5 4 4 4 3 2 2 1 1 0

Slot "fn":
[[1]]
 [1] 5 4 4 3 2 2 2 1 1 0 0

Slot "n.pos":
[[1]]
[1] 5

Slot "n.neg":
[[1]]
[1] 5

Slot "n.pos.pred":
[[1]]
 [1]  0  1  2  3  4  5  6  7  8  9 10

Slot "n.neg.pred":
[[1]]
 [1] 10  9  8  7  6  5  4  3  2  1  0

Also, each slot is a list, I guess to potentially include several predictions together. The code in my original response should therefore be adapted to this new format. Something like this:
tpr <- pred@tp[[1]]/max(pred@tp[[1]])
fpr <- pred@fp[[1]]/max(pred@fp[[1]])

plot(fpr, tpr, type = "l")


I need help to fix scraping graphql API

Question: I was able via Google Dev Tools - Networking to paste the graphql query into Insomnia (copy url bash) to make a working python request. Now something has been changed on the part of the provider. Now I can not even run the curl in insomnia. I only get response 400.
On my previous code I get error message, which I can not solve myself.
I would be very happy for a working solution.
My coder that worked so far is:
import requests
import json

def scrape_digitec():
    url = "https://www.digitec.ch/api/graphql"
    headers = {
        "authority": "www.digitec.ch",
        "accept": "application/json",
        "accept-language": "de-CH",
        "cache-control": "no-cache",
        "content-type": "application/json",
        "origin": "https://www.digitec.ch",
        "pragma": "no-cache",
        "referer": "https://www.digitec.ch/search?q=bang%20olufsen",
        "sec-ch-ua": '"Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36",
        "x-dg-country": "ch",
        "x-dg-mandator": "406802",
        "x-dg-portal": "25",
        "x-dg-testgroup": "Default"
    }

    search = 'lg'
    offset = '0'
    payload = '{"query":"query ENTER_SEARCH(\\t$query: String!\\t$sortOrder: ProductSort\\t$limit: Int = 9\\t$offset: Int = 0\\t$filters: [SearchFilter]\\t$include: [String!]\\t$exclude: [String!]\\t$searchQueryId: String\\t$siteId: String) {\\tsearch(\\t\\tquery: $query\\t\\tfilters: $filters\\t\\tsearchQueryId: $searchQueryId\\t\\tsiteId: $siteId\\t) {\\t\\tproducts(limit: $limit, offset: $offset, sortOrder: $sortOrder) {\\t\\t\\ttotal\\t\\t\\thasMore\\t\\t\\tnextOffset\\t\\t\\tresults {\\t\\t\\t\\t...ProductSearchResult\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\tfilters(include: $include, exclude: $exclude) {\\t\\t\\tproduct {\\t\\t\\t\\tidentifier\\t\\t\\t\\tname\\t\\t\\t\\tfilterType\\t\\t\\t\\tscore\\t\\t\\t\\ttooltip {\\t\\t\\t\\t\\t...FilterTooltipResult\\t\\t\\t\\t\\t__typename\\t\\t\\t\\t}\\t\\t\\t\\t...CheckboxSearchFilterResult\\t\\t\\t\\t...RangeSearchFilterResult\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\tmagazinePages(limit: 3) {\\t\\t\\tids {\\t\\t\\t\\tid\\t\\t\\t\\tscore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\ttotal\\t\\t\\t__typename\\t\\t}\\t\\tauthors(limit: 3) {\\t\\t\\tids {\\t\\t\\t\\tid\\t\\t\\t\\tscore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\ttotal\\t\\t\\t__typename\\t\\t}\\t\\tdiscussions(limit: 3) {\\t\\t\\tids {\\t\\t\\t\\tid\\t\\t\\t\\tscore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\ttotal\\t\\t\\t__typename\\t\\t}\\t\\tquestions(limit: 3) {\\t\\t\\tids {\\t\\t\\t\\tid\\t\\t\\t\\tscore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\ttotal\\t\\t\\t__typename\\t\\t}\\t\\tratings(limit: 3) {\\t\\t\\tids {\\t\\t\\t\\tid\\t\\t\\t\\tscore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\ttotal\\t\\t\\t__typename\\t\\t}\\t\\tproductTypes(limit: 24) {\\t\\t\\ttotal\\t\\t\\tresults {\\t\\t\\t\\tid\\t\\t\\t\\tname\\t\\t\\t\\tprimarySynonyms\\t\\t\\t\\tisVisible\\t\\t\\t\\tdescription\\t\\t\\t\\tmetaDescription\\t\\t\\t\\timageUrl\\t\\t\\t\\tsearchScore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\tbrands(limit: 24) {\\t\\t\\ttotal\\t\\t\\tresults {\\t\\t\\t\\tid\\t\\t\\t\\ttitle\\t\\t\\t\\tsearchScore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\thelp(limit: 3) {\\t\\t\\tids {\\t\\t\\t\\tid\\t\\t\\t\\tscore\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\ttotal\\t\\t\\thasMore\\t\\t\\tresults {\\t\\t\\t\\tsearchScore\\t\\t\\t\\ttitle\\t\\t\\t\\tid\\t\\t\\t\\turl\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\t_meta {\\t\\t\\tqueryInfo {\\t\\t\\t\\tcorrectedQuery\\t\\t\\t\\tdidYouMeanQuery\\t\\t\\t\\tlastProductSearchPass\\t\\t\\t\\texecutedSearchTerm\\t\\t\\t\\ttestGroup\\t\\t\\t\\tisManagedQuery\\t\\t\\t\\tisRerankedQuery\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\tredirectionUrl\\t\\t\\tportalReferral {\\t\\t\\t\\tproductCount\\t\\t\\t\\tportalName\\t\\t\\t\\turl\\t\\t\\t\\tproductImageUrls\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\t__typename\\t}}fragment ProductSearchResult on ProductSearchResultItem {\\tsearchScore\\tmandatorSpecificData {\\t\\t...ProductMandatorSpecific\\t\\t__typename\\t}\\tproduct {\\t\\t...ProductMandatorIndependent\\t\\t__typename\\t}\\toffer {\\t\\t...ProductOffer\\t\\t__typename\\t}\\t__typename}fragment FilterTooltipResult on FilterTooltip {\\ttext\\tmoreInformationLink\\t__typename}fragment CheckboxSearchFilterResult on CheckboxSearchFilter {\\toptions {\\t\\tidentifier\\t\\tname\\t\\tproductCount\\t\\tscore\\t\\treferenceValue {\\t\\t\\tvalue\\t\\t\\tunit {\\t\\t\\t\\tabbreviation\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\tpreferredValue {\\t\\t\\tvalue\\t\\t\\tunit {\\t\\t\\t\\tabbreviation\\t\\t\\t\\t__typename\\t\\t\\t}\\t\\t\\t__typename\\t\\t}\\t\\ttooltip {\\t\\t\\t...FilterTooltipResult\\t\\t\\t__typename\\t\\t}\\t\\t__typename\\t}\\t__typename}fragment RangeSearchFilterResult on RangeSearchFilter {\\treferenceMin\\tpreferredMin\\treferenceMax\\tpreferredMax\\treferenceStepSize\\tpreferredStepSize\\trangeMergeInfo {\\t\\tisBottomMerged\\t\\tisTopMerged\\t\\t__typename\\t}\\treferenceUnit {\\t\\tabbreviation\\t\\t__typename\\t}\\tpreferredUnit {\\t\\tabbreviation\\t\\t__typename\\t}\\trangeFilterDataPoint {\\t\\t...RangeFilterDataPointResult\\t\\t__typename\\t}\\t__typename}fragment ProductMandatorSpecific on MandatorSpecificData {\\tisBestseller\\tisDeleted\\tshowroomSites\\tsectorIds\\t__typename}fragment ProductMandatorIndependent on ProductV2 {\\tid\\tproductId\\tname\\tnameProperties\\tproductTypeId\\tproductTypeName\\tbrandId\\tbrandName\\taverageRating\\ttotalRatings\\ttotalQuestions\\tisProductSet\\timages {\\t\\turl\\t\\theight\\t\\twidth\\t\\t__typename\\t}\\tenergyEfficiency {\\t\\tenergyEfficiencyColorType\\t\\tenergyEfficiencyLabelText\\t\\tenergyEfficiencyLabelSigns\\t\\tenergyEfficiencyImage {\\t\\t\\turl\\t\\t\\theight\\t\\t\\twidth\\t\\t\\t__typename\\t\\t}\\t\\t__typename\\t}\\tseo {\\t\\tseoProductTypeName\\t\\tseoNameProperties\\t\\tproductGroups {\\t\\t\\tproductGroup1\\t\\t\\tproductGroup2\\t\\t\\tproductGroup3\\t\\t\\tproductGroup4\\t\\t\\t__typename\\t\\t}\\t\\tgtin\\t\\t__typename\\t}\\thasVariants\\tsmallDimensions\\tbasePrice {\\t\\tpriceFactor\\t\\tvalue\\t\\t__typename\\t}\\t__typename}fragment ProductOffer on OfferV2 {\\tid\\tproductId\\tofferId\\tshopOfferId\\tprice {\\t\\tamountIncl\\t\\tamountExcl\\t\\tcurrency\\t\\tfraction\\t\\t__typename\\t}\\tdeliveryOptions {\\t\\tmail {\\t\\t\\tclassification\\t\\t\\tfutureReleaseDate\\t\\t\\t__typename\\t\\t}\\t\\tpickup {\\t\\t\\tsiteId\\t\\t\\tclassification\\t\\t\\tfutureReleaseDate\\t\\t\\t__typename\\t\\t}\\t\\tdetailsProvider {\\t\\t\\tproductId\\t\\t\\tofferId\\t\\t\\tquantity\\t\\t\\ttype\\t\\t\\t__typename\\t\\t}\\t\\t__typename\\t}\\tlabel\\ttype\\tvolumeDiscountPrices {\\t\\tminAmount\\t\\tprice {\\t\\t\\tamountIncl\\t\\t\\tamountExcl\\t\\t\\tcurrency\\t\\t\\t__typename\\t\\t}\\t\\tisDefault\\t\\t__typename\\t}\\tsalesInformation {\\t\\tnumberOfItems\\t\\tnumberOfItemsSold\\t\\tisEndingSoon\\t\\tvalidFrom\\t\\t__typename\\t}\\tincentiveText\\tisIncentiveCashback\\tisNew\\tisSalesPromotion\\thideInProductDiscovery\\tcanAddToBasket\\thidePrice\\tinsteadOfPrice {\\t\\ttype\\t\\tprice {\\t\\t\\tamountIncl\\t\\t\\tamountExcl\\t\\t\\tcurrency\\t\\t\\tfraction\\t\\t\\t__typename\\t\\t}\\t\\t__typename\\t}\\tminOrderQuantity\\t__typename}fragment RangeFilterDataPointResult on RangeFilterDataPoint {\\tcount\\treferenceValue {\\t\\tvalue\\t\\tunit {\\t\\t\\tabbreviation\\t\\t\\t__typename\\t\\t}\\t\\t__typename\\t}\\tpreferredValue {\\t\\tvalue\\t\\tunit {\\t\\t\\tabbreviation\\t\\t\\t__typename\\t\\t}\\t\\t__typename\\t}\\t__typename}\",\"variables\":{\"limit\":100,\"offset\":'+offset+',\"query\":\"'+search+'\",\"filters\":[],\"sortOrder\":null,\"include\":[\"bra\",\"pt\",\"pr\"],\"exclude\":[\"off\"],\"searchQueryId\":\"4ce81461-09e2-4f7a-bb9a-8f6f8503fdc4\",\"siteId\":null},\"operationName\":\"ENTER_SEARCH\"}'

    response = requests.request("POST", url, data=payload, headers=headers)
    print(response)
    data = response.json()
    print(json.dumps(data, indent=2))
    print(json.dumps(data))

if __name__ == '__main__':
    scrape_digitec()

Answer: You need to format your payload into json format (python's dictionary/lists), then use the json parameter, as opposed to data:
import requests
import json

def scrape_digitec():
    url = "https://www.digitec.ch/api/graphql"
    headers = {
        "authority": "www.digitec.ch",
        "accept": "application/json",
        "accept-language": "de-CH",
        "cache-control": "no-cache",
        "content-type": "application/json",
        "origin": "https://www.digitec.ch",
        "pragma": "no-cache",
        "referer": "https://www.digitec.ch/search?q=bang%20olufsen",
        "sec-ch-ua": '"Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36",
        "x-dg-country": "ch",
        "x-dg-mandator": "406802",
        "x-dg-portal": "25",
        "x-dg-testgroup": "Default"
    }

    search = 'lg'
    offset = 0
    payload = [{
        "operationName":"ENTER_SEARCH",
        "variables":{
            "limit":24,
            "offset":offset,
            "query":search,
            "filters":[],
            #"sortOrder":null,
            "include":["bra","pt","pr","off"],
            "searchQueryId":"e1b620fc-bf9c-41c6-85c0-cc49e5d12e25",
            #"siteId":null},
            },
        "query":"query ENTER_SEARCH($query: String!, $sortOrder: ProductSort, $limit: Int = 9, $offset: Int = 0, $filters: [SearchFilter], $include: [String!], $exclude: [String!], $searchQueryId: String, $siteId: String) {\n  search(\n    query: $query\n    filters: $filters\n    searchQueryId: $searchQueryId\n    siteId: $siteId\n  ) {\n    products(limit: $limit, offset: $offset, sortOrder: $sortOrder) {\n      total\n      hasMore\n      nextOffset\n      results {\n        ...ProductSearchResult\n        __typename\n      }\n      __typename\n    }\n    filters(include: $include, exclude: $exclude) {\n      product {\n        identifier\n        name\n        filterType\n        score\n        tooltip {\n          ...FilterTooltipResult\n          __typename\n        }\n        ...CheckboxSearchFilterResult\n        ...RangeSearchFilterResult\n        __typename\n      }\n      __typename\n    }\n    magazinePages(limit: 3) {\n      ids {\n        id\n        score\n        __typename\n      }\n      total\n      __typename\n    }\n    authors(limit: 3) {\n      ids {\n        id\n        score\n        __typename\n      }\n      total\n      __typename\n    }\n    discussions(limit: 3) {\n      ids {\n        id\n        score\n        __typename\n      }\n      total\n      __typename\n    }\n    questions(limit: 3) {\n      ids {\n        id\n        score\n        __typename\n      }\n      total\n      __typename\n    }\n    ratings(limit: 3) {\n      ids {\n        id\n        score\n        __typename\n      }\n      total\n      __typename\n    }\n    productTypes(limit: 24) {\n      total\n      results {\n        id\n        name\n        primarySynonyms\n        isVisible\n        description\n        metaDescription\n        imageUrl\n        searchScore\n        __typename\n      }\n      __typename\n    }\n    brands(limit: 24) {\n      total\n      results {\n        id\n        title\n        searchScore\n        __typename\n      }\n      __typename\n    }\n    _meta {\n      queryInfo {\n        correctedQuery\n        didYouMeanQuery\n        lastProductSearchPass\n        executedSearchTerm\n        testGroup\n        isManagedQuery\n        isRerankedQuery\n        __typename\n      }\n      redirectionUrl\n      portalReferral {\n        productCount\n        portalName\n        url\n        productImageUrls\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n\nfragment ProductSearchResult on ProductSearchResultItem {\n  searchScore\n  mandatorSpecificData {\n    ...ProductMandatorSpecific\n    __typename\n  }\n  product {\n    ...ProductMandatorIndependent\n    __typename\n  }\n  offer {\n    ...ProductOffer\n    __typename\n  }\n  __typename\n}\n\nfragment FilterTooltipResult on FilterTooltip {\n  text\n  moreInformationLink\n  __typename\n}\n\nfragment CheckboxSearchFilterResult on CheckboxSearchFilter {\n  options {\n    identifier\n    name\n    productCount\n    score\n    referenceValue {\n      value\n      unit {\n        abbreviation\n        __typename\n      }\n      __typename\n    }\n    preferredValue {\n      value\n      unit {\n        abbreviation\n        __typename\n      }\n      __typename\n    }\n    tooltip {\n      ...FilterTooltipResult\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n\nfragment RangeSearchFilterResult on RangeSearchFilter {\n  referenceMin\n  preferredMin\n  referenceMax\n  preferredMax\n  referenceStepSize\n  preferredStepSize\n  rangeMergeInfo {\n    isBottomMerged\n    isTopMerged\n    __typename\n  }\n  referenceUnit {\n    abbreviation\n    __typename\n  }\n  preferredUnit {\n    abbreviation\n    __typename\n  }\n  rangeFilterDataPoint {\n    ...RangeFilterDataPointResult\n    __typename\n  }\n  __typename\n}\n\nfragment ProductMandatorSpecific on MandatorSpecificData {\n  isBestseller\n  isDeleted\n  showroomSites\n  sectorIds\n  __typename\n}\n\nfragment ProductMandatorIndependent on ProductV2 {\n  id\n  productId\n  name\n  nameProperties\n  productTypeId\n  productTypeName\n  brandId\n  brandName\n  averageRating\n  totalRatings\n  totalQuestions\n  isProductSet\n  images {\n    url\n    height\n    width\n    __typename\n  }\n  energyEfficiency {\n    energyEfficiencyColorType\n    energyEfficiencyLabelText\n    energyEfficiencyLabelSigns\n    energyEfficiencyImage {\n      url\n      height\n      width\n      __typename\n    }\n    __typename\n  }\n  seo {\n    seoProductTypeName\n    seoNameProperties\n    productGroups {\n      productGroup1\n      productGroup2\n      productGroup3\n      productGroup4\n      __typename\n    }\n    gtin\n    __typename\n  }\n  hasVariants\n  smallDimensions\n  basePrice {\n    priceFactor\n    value\n    __typename\n  }\n  __typename\n}\n\nfragment ProductOffer on OfferV2 {\n  id\n  productId\n  offerId\n  shopOfferId\n  price {\n    amountIncl\n    amountExcl\n    currency\n    fraction\n    __typename\n  }\n  deliveryOptions {\n    mail {\n      classification\n      futureReleaseDate\n      __typename\n    }\n    pickup {\n      siteId\n      classification\n      futureReleaseDate\n      __typename\n    }\n    detailsProvider {\n      productId\n      offerId\n      quantity\n      type\n      __typename\n    }\n    __typename\n  }\n  label\n  type\n  volumeDiscountPrices {\n    minAmount\n    price {\n      amountIncl\n      amountExcl\n      currency\n      __typename\n    }\n    isDefault\n    __typename\n  }\n  salesInformation {\n    numberOfItems\n    numberOfItemsSold\n    isEndingSoon\n    validFrom\n    __typename\n  }\n  incentiveText\n  isIncentiveCashback\n  isNew\n  isSalesPromotion\n  hideInProductDiscovery\n  canAddToBasket\n  hidePrice\n  insteadOfPrice {\n    type\n    price {\n      amountIncl\n      amountExcl\n      currency\n      fraction\n      __typename\n    }\n    __typename\n  }\n  minOrderQuantity\n  __typename\n}\n\nfragment RangeFilterDataPointResult on RangeFilterDataPoint {\n  count\n  referenceValue {\n    value\n    unit {\n      abbreviation\n      __typename\n    }\n    __typename\n  }\n  preferredValue {\n    value\n    unit {\n      abbreviation\n      __typename\n    }\n    __typename\n  }\n  __typename\n}\n"}]
    response = requests.post(url, json=payload, headers=headers)
    print(response)
    data = response.json()
    print(json.dumps(data, indent=2))
    print(json.dumps(data))

if __name__ == '__main__':
    scrape_digitec()

I need help to fix scraping graphql API


GLM with scores/principal dimensions from MCA

Question: I hope someone can help me understand how to run this analysis!
I have a dataset with many categorical variables (i.e. color, pattern, texture) associated to each animal in each interaction between pairs of animals (a set of categorical variables for each interaction of each animal in each pair).
I want to test the effect of each variable on animal contest outcome (binomial).
My sample size is really small compared to the number of variables/predictors (n = 10 pairs composed by 5 animals in total).
So, I would like to perform a "Multiple Correspondence analysis" (MCA) to reduce the dimensionality and select only the most relevant predictor variables to input in a Generalised Linear Mixed Effect Model (GLMM). This would also allow me to avoid including in the same GLMM model predictors with high collinearity, is that correct?
I read that you can input the scores from a PCA into a GLM with Factoextra.
Can you do the same with the scores from a MCA? Could I simply input the scores from the dimensions in the MCA into a GLMM model with lma4:glmer R function?
This would be the model with the original variables:
glmer(outcome ~ body color + texture + pattern +
                (1|individual_ID) + (1|pair_ID),
                family=binomial(link="logit"), dataset)

How would the model with the MCA scores look like?
If I input the MCA scores in the GLMM model, can I still know which original variable (i.e. color) is the strongest predictor of contest outcome?
I haven't found much information on how to run a GLMM with MCA scores, so any help including tutorial links or examples that you could recommend would be highly appreciated!
Comment: See https://www.hindawi.com/journals/jar/2013/302163/  for a paper combining mca, pca with regression analysis
Answer: Using the factors obtained in the MCA as predictors in GLM/GLMM is valid, especially considering your specific case (need for dimension reduction and multicolinearity reduction).
The interpretation of the coefficients will be the difficult part. I would try two approaches:

Having a good understanding and labelling of each factor, and interpreting the coefficients only in relative terms: "The augmentation of this factor is associated with a decrease (or increase) in my output".
Using model predictions and marginal effects. The idea is to have an observation used as a scenario, using the function predict.MCA from factoMineR to get is coordinates on the new factors and then predicting your outcome with the predict function and your GLM/GLMM. You can then do the same thing but with a new observation for which you change only one characteristic (scenario 2). You can then interpret the change between the two predictions. But keep in mind that it is not exactly "everything hold equal" because changing that characteristic will affect the other factors.

A last suggestion would be to think about your process (input data --> MCA --> GLMM --> result) as a global model. With a little bit of effort, you could use the functions from DALEX and analyze your whole model with tools used in machine learning.
Comment: another R library for interpreting machine learning models: https://uc-r.github.io/dalex
Comment: Thank you Jeremy! it seemed to have worked! Yes, I tried using the variables coordinate but it doesn't work with that because the data has then different length (var coordinates are not 300 as the observations) and I guess it makes more sense to use the observations. With dimdesc() I can see which are the variable categories that are significantly correlated with each Dimension.
Comment: Now, if I see that a series of variables (i.e. yellow color, stripes and standing) are significantly correlated with Dimension 1 and Dimension 1 predicts my dependent variable in a GLMM model, then I can also say that yellow, stripes and standing predict or are more highly associated with my dependent variable, is that correct?  Thanks anyways for all your help so far, really appreciated!
Comment: yes, you could say that. To have a better understanding on their effect, you could also do something like:
1) take one of your obseravtions (with the original variables)
2) predict its coordinates with the results of the MCA
3) predict the value expected from your GLMM on that observation by using the MCA coordinates
5) create a new observation (scenario) by changing by example the color of that observation
6) predict the coordinates of that new observations with the MCA
7) predict the expected output with your GLMM for it
And then compare the two predictions.
Comment: What is DALEX? ...
Comment: Hi Jeremy, thank you so much for your detailed reply and explanation.
I have been looking into this and asking around, and as far as I understood MCA creates new variables which could be given by 20% of the categorical variable A (i.e. color) and 50% by the categorical variable B (i.e. pattern). So that it would be a bit complicated to extract conlusions about the main effect of each categorical predictor from a MCA - gLMM analysis. Is that correct?
Comment: Would a Cluster analysis and then GLMM be better? As far as I understood Cluster Analysis does not create new variables like PCA/MCA but only groups together variables that are collinear or explain the variance in the dependent variable in a similar way...is that correct?
Comment: I have also been suggested recently to drop the GLMM model approach altogether, and use instead "Conditional Inference Models" which are better suited for small sample sizes & large number of categorical variables as in my case...do you think that would be a better approach?

I would really appreciate some advice & tutorial links as I feel a bit lost at the moment.
Thanks a lot!
Comment: Cluster Analysis does not aim to group variables but observations. The goal it to obtain groups of individuals that are similar. You would obtain a new categorical variable that will indicate for each observation to which group it belongs. I am not sure it would help you in that context. If I understand well, you have only 50 observations (5 * 10) ? This is a very low number to use factor analysis (MCA) and GLMM. Maybe using only bivariate tests between your Y and X variables would be more appropriate.
Comment: Hi Jeremy,and thanks again for replying.
I have over 300 observations, because I have repeated observations for each individual. So I guess I could try and use MCA first and see if specific groups of individual traits consistently explain variance in the dependent variable..?
I am also trying to eliminate collinear variavbles first, but I am having a hard time to find a function in R for multiple pairwise correlations between a bunch of categorical variables..thank again for you help!
Comment: Hi , just another doubt...I haven't found any example of how to use the MCA dimensions in a GLM model. I found examples only for PCA, where they include the individuals coordinate `score= as_tibble(factoextra::get_pca_ind(pca)$coord)` in the GLM. But with MCA would you use the coordinates of the variables categories (and not the individuals/observations coordinates) as dimensions scores to input in the GLM?
Thanks a lot for your help!
Comment: Hi @Dory33. You can use the coordinates of the individual of the MCA as predictors in your GLMM. Using the coordinates of the modalities would not make much sens. 300 observations sounds reasonable (depending on the number of categorical variables and their modalities).


RDLC 'export' option showing up behind the data

Question: I developed a few rdlc files that I am using in my asp.net/vb.net project.  the reports load great, but when I click 'export' in the toolbar, its showing up behind the data

I figure I could play around with Z indexes, but don't see any method explicitly for the toolbar.  Any thoughts on how to fix?  Below is how my code in the aspx page
<asp:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana"
    Font-Size="8pt" InteractiveDeviceInfos="(Collection)"
    WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Width="100%" AsyncRendering="true" SizeToReportContent="true">
    <LocalReport ReportPath="Report\myReport.rdlc" EnableHyperlinks="true">
        <DataSources>
            <asp:ReportDataSource DataSourceId="SqlDataSource1" Name="DataSet1"/>
        </DataSources>
    </LocalReport>
</asp:ReportViewer>

Answer: in case anyone runs into this at a later date, i added the following jquery to my .aspx file and it worked.


Firebase remove() entire nested array in database

Question: How does one delete an entire nested child from a Firebase database by referencing an entry to find the desired point of deletion?
For example, I have two entries nested under (list). (1) -KcxacywN4EkvwAzugfV and (2) -KcxaeBAIW-WgLAsajvV. I want to remove (2) -KcxaeBAIW-WgLAsajvV from the database using it's ID -KcxaeBAIW-WgLAsajvU-4-725391765511696 (See picture below).

I have a button setup for each database entry, to display a remove button. Each button, contains the data- or ID for each database entry.
rootRef.on("child_added", snap => {
    var title = snap.child("title").val();
    var link = snap.child("link").val();
    var type = snap.child("type").val();
    var id = snap.child("id").val();
      $("#table_data").append("

"+ title +"
"+ type +"
Download           Remove

");
  });

The onClick event and associated id for the button, trigger this function. My mental idea, is to then take the ID from data- to delete its nested child, (2) -KcxaeBAIW-WgLAsajvV from the database. Same process for all other nested entries.
function removeClick() {
  $(".user").click(function() {
        rvm = $(this).attr("data-name");
    });
  alert(rvm);
  firebaseRef.remove(rvm);
}

I've studied https://firebase.google.com/docs/database/web/read-and-write and can't seem to figure out the actual deletion of the nested entry. How can I use remove() or maybe another method to accomplish this?
I have been trying this, to get a better understanding.
firebaseRef.child(rvm).remove();

Since rootRef, is how I'm viewing data. I tried.
rootRef.child().remove();

This simply deletes the whole database...
Final running code:
function removeClick() {
  $(".user").click(function() {
        rvm = $(this).attr("data-name");
  });
  alert(rvm);
  var query = rootRef.orderByChild("id").equalTo(rvm);
  query.once("value", function(snapshot) {
   snapshot.forEach(function(itemSnapshot) {
       itemSnapshot.ref.remove();
   });
 });
}

Answer: You can only remove an item if you know its key. So given your current structure, you will first need to look up the key for the id you mention.
Assuming you have a variable ref that points to the root of the database:
var listRef = ref.child("list");
var query = listRef.orderByChild("id").equalTo("-KcxaeBAIW-WgLAsajvU-4-725391765511696");
query.once("value", function(snapshot) {
   snapshot.forEach(function(itemSnapshot) {
       itemSnapshot.ref.remove();
   });
});

If you have only a single child with the id, you should consider restructuring your database to use the id as the key. If you do that, you could remove the item with:
listRef.child("-KcxaeBAIW-WgLAsajvU-4-725391765511696").remove()

Comment: That worked! Thank you. I see now, you have to equate the reference somehow. I've posted to the question, the working code.


Postfix sending to wrong email (redirection?) New setup possibly wrong configuration

Question: I'm having a strange issue after possibly setting up DKIM signing (might have caused this?)
Originally I was receiving emails fine (I was tricking my machine into thinking the website was on the new server via the hosts file)
Sep 11 12:10:01 mail postfix/pickup[4549]: 1B87110E7264: uid=48 from=<apache>
Sep 11 12:10:01 mail postfix/cleanup[4747]: 1B87110E7264: messageid=<email@example.com>
Sep 11 12:10:01 mail postfix/qmgr[4550]: 1B87110E7264: from=<firstname.lastname@example.com>, size=884, nrcpt=1 (queue active)
Sep 11 12:10:01 mail postfix/smtp[4750]: 1B87110E7264: to=<email@example.com>, relay=ASPMX.L.GOOGLE.COM[184.108.40.206]:25, delay=0.36, delays=0.06/0.01/0.06/0.24, dsn=2.0.0, status=sent (250 2.0.0 OK 1473592201 k65si980592wmd.53 - gsmtp)
Sep 11 12:10:01 mail postfix/qmgr[4550]: 1B87110E7264: removed

Which seemed to work fine.
However since setting up DKIM signing and switching the DNS A record to point the domain to the new server. I now get the following log:
Sep 11 13:10:23 mail postfix/pickup[5894]: 3471710EB9DE: uid=48 from=<apache>
Sep 11 13:10:23 mail postfix/cleanup[5900]: 3471710EB9DE: message-id=<email@example.com>
Sep 11 13:10:23 mail opendkim[4425]: 3471710EB9DE: DKIM-Signature field added (s=default, d=companyemail.co.uk)
Sep 11 13:10:23 mail postfix/qmgr[5895]: 3471710EB9DE: from=<firstname.lastname@example.com>, size=855, nrcpt=1 (queue active)
Sep 11 13:10:23 mail postfix/local[5903]: 3471710EB9DE: to=<email@example.com>, orig_to=<email@example.com>, relay=local, delay=0.06, delays=0.05/0.01/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
Sep 11 13:10:23 mail postfix/qmgr[5895]: 3471710EB9DE: removed

Now the main difference I can see is the opendkim line and that the to= field has been changed and now there is an orig_to. I think this might be the issue as I seem to be receiving emails on the server now (as it keeps saying: You have new mail in /var/spool/mail/root)
Any ideas where I may be going wrong?
Answer: This log entry
relay=local

indicating that you put companyemail.co.uk in mydestination configuration. Check your main.cf.
If you want email to companyemail.co.uk go to somewhere else, remove it from that parameter.


Generating custom legend (and only a legend) in matplotlib Python2

Question: I'm trying to make a custom legend using matplotlib.  The example in the matplotlib documentation doesn't work on my set up.  Neither does this follow.
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches

fig, ax = plt.subplots()

patch1 = mpatches.Patch(color='#a6cee3', label='Blue')
patch2 = mpatches.Patch(color='#1f78b4', label='Bluerish')
patch3 = mpatches.Patch(color='#33a02c', label='Greener')
patch4 = mpatches.Patch(color='#fdbf6f', label='Kind of orange')
patch5 = mpatches.Patch(color='#ff7f00', label='Orange')

all_handles = (patch1, patch2, patch3, patch4, patch5)

leg = ax.legend(all_handles)

ax.add_artist(leg)
plt.show()

How can I make it produce the desired legend?
I'm using Mac OSX 10.10.3, Python 2.7.6, Matplotlib 1.3.1.
Edit: @xnx's solution below works for Python 3, and works for Python 2.7.11 if using Matplotlib 2.1.1 (thanks @DavidG).
Comment: Have you tried with newer versions of matplotlib? The solution below works for me on Python 2.7, matplotlib 2.1.1 (although I am on windows....)
Comment: This works, I've accepted the answer below.  Good call @DavidG - thanks for the help.
Answer: You should set the handles argument to ax.legend explicitly:
leg = ax.legend(handles=all_handles)

I think the issue with your code is that the first (positional) argument to legend is otherwise taken to be a sequence of objects you wish to label and you don't have any.
Comment: That gives me `AttributeError: 'NoneType' object has no attribute 'set_axes'`.
Comment: I don't get any error but this still doesn't work for me either without calling a `plt.draw` afterward. @P-robot, in which function is that error?
Comment: From `ax.legend()`, the bad call traces `ax.add_artist(leg)` which gives an error from `/Library/Python/2.7/site-packages/matplotlib-override/matplotlib/axes.pyc in add_artist(self, a)` in the following line (1454) `a.set_axes(self)`.  Does that help?
Comment: I'm using IPython 3.1.0.  If that makes a difference.  I just updated to IPython 4.0.0, and it still gives the same error.
Comment: I've updated python, numpy, scipy, matplotlib, sympy, nose, but the problem persists with the same error.
Comment: I can reproduce this with the system Python on Mac OS X. I don't have a fix for you, but can tell you that it works under [Anaconda](https://store.continuum.io/cshop/anaconda/) which might be the way to go if you don't have a particular attachment to the system Python.
Comment: On the other hand, it does seem that this issue is related to the fact that you don't have any objects plotted on your axes, so you could try adding them (before adding the legend!)
Comment: This works in Python 2.7.11 with matplotlib version 2.1.1.  Thanks all for the help.
Answer: I had a similar issue.
This solved it for me:
leg = **plt**.legend(all_handles)


Como obter marcadores próximos da localização do usuário?

Question: Boa noite
Quem conhece o aplicativo Tinder sabe que não é mostrado um mapa, mas sabe que ele pega a localização do usuário e utiliza para procurar pessoas que estejam próximas em um determinado raio. Gostaria de fazer a mesma coisa em minha aplicação Android, procurei por posts antigos no Stackoverflow e na internet sobre isso porém não encontrei respostas.
EDIT
No Google Maps API do Android ou na documentação do mesmo existe algum recurso nativo quanto a isto como existe no Google Maps API para JavaScript ou o desenvolvedor terá que realizar um select e cálculo para a solução?
Agradeço desde já.
Comment: no tinder creio que nao seu usa o mapa, ele acha os pontos proximos por um calculo e um select no banco mesmo.
Comment: no tinder fnciona assim, ele pega sua localizacao e fica chamando um servico enviando sua localizacao, e no servidor ele busca os pontos (pessoas) proximos a sua localizacao e te exibe, todo esse trabalho fica no servidor. ok? :)
Comment: Isso, mas queria um código como exemplo partindo do Google Maps API do Android. Obrigado pelo comentário.
Comment: O objetivo do SO é tirar dúvidas e também com certeza propor soluções concretas. No caso o que você tem pra nos mostrar, já tentou fazer alguma coisa? Como a sua pergunta está, pode parecer que você quer o código pronto.
Comment: Tentei procurando exemplos na Internet, porém nada concreto. Irei editar a pergunta colocando como base a documentação, se existe algum recurso na própria API que trata sobre esta questão. Obrigado.
Answer: Estou estudando o mesmo problema no momento e encontrei esse paper:
Finding Points Within a Distance of a Latitude/Longitude Using Bounding Coordinates - Por Jan Philip Matuschek
Ele aborda o problema de encontrar pontos geográficos que estão a uma certa distância(um raio) de um determinado ponto geográfico.
Já tem uma implementação em Java que é uma mão na roda, mas não é problema trivial e exige um pouco de matemática.
Comment: Obrigado Túlio, interessante que ainda não existe algum recurso nativo do Android que trate isso.


Prove existence of the limit

Question: Let $f(x)$($>0 \forall x \in \mathbb {R}$) be a function which satisfies the following properties,

$f(x)=k$ for some $k>0$ and for infinitely many values of $x$.
If $f(x_2)=f(x_1)=k$, with $x_2>x_1$ then $f(x)$ is strictly decreasing for all $x_1<x<x_2$.
The difference $(x_2-x_1)$ has no upper bound. $x_2$, $x_1$ denoting the same meaning as in 2.

Then is it true that the limit $\displaystyle \lim_{n \to \infty} f(x)$ exists?
I think that some more information about the function $f(x)$ is needed to solve the problem. I don't have any idea as to how to begin with. Any help will be appreciated.
Answer: Assuming (2) and (1) don't intentionally exclude every possible function, yes and no.
What the caveat is about:  Take $f(x_1) = f(x_2) = f(x_3) = k$.  Strictly decreasing between $x_1$ and $x_3$ contradicts $f(x_2) = k$.
Yes instance:  $f(x) = 2-\frac{1-\text{sawtooth}(x)}{|x|+1} , k = 2, \{x_i\}_i =  \mathbb{Z}$.  Limit is 2 because $1 - \text{sawtooth}(x)$ is bounded below by $0$ and above by $1$.
No instance: $f(x) = 1+\text{sawtooth}(x), k = 2, \{x_i\}_i =  \mathbb{Z}$.  Endlessly cycles from $2$ down to $1$, so the limit does not exist.
See sawtooth wave, although the decreasing requirement above means we should use the sawtooth leaning the other way: $\lfloor t \rfloor -t$.

Prove existence of the limit


MySql select multiple columns when has value

Question: I need to select some columns from a table and also some other columns depending on a value from one column. For example:
 SELECT
    col_a, col_b, col_c
FROM user_table

INNER JOIN col_d, col_e, col_f ON col_type = 1
INNER JOIN col_g, col_h, col_i ON col_type = 2

WHERE id = :id
AND active = 1

Since I'm new to mysql, I don't how how i should do this. I tried using CASE WHEN but was able to select a single column and I need to select multiple columns.
Answer: I think you misunterstood INNER JOIN and you want something like that
SELECT
    col_a, col_b, col_c,
    IF( col_type = 1, col_d, NULL ) AS col_d,
    IF( col_type = 1, col_e, NULL ) AS col_e,
    IF( col_type = 2, col_g, NULL ) AS col_g,
    IF( col_type = 2, col_h, NULL ) AS col_h
FROM user_table

WHERE id = :id
AND active = 1

But i prefere to load all cols and handle it with your other language (PHP?).
Comment: This is what I'm trying to avoid, because if I have 20 columns to select, I need to do the if 20 times just for one case (and yes, PHP in the backend).
Comment: Then is PHP the way to go. You can build there very comfortable and flexible functions to load your entry like this.


how to open desktop node link shared on facebook onto mobile device (mobile website version)

Question: I have a desktop link:
mysite.com/node/22
When I share this link onto facebook, and try to open it on desktop prowser it's work good.
But when I try to open it (from facebook) onto mobile it's back me to webiste (mobile version) home.
mobi.mysite.com
how can i make it on mobile go to
mobi.mysite.com/node/22
I use (mobile switch) and (mobile tools) modules, and they are works good
thanks
Answer: the solution is very simple, I just don't see it.
its in advanced sitting for mobile switch module, Multisite shared content must be checked.


Check if JavaScript is enabled with PHP

Question: Is there a way to check if JavaScript is enabled with PHP? If so, how?
Comment: Nope. Well. Not on the first visit. On the second+ yes. Use AJAX to set a session var. If it is set on page 2, you have JS. If not, you don't. This could work on a front login page... but if you need it on the first page load, you can't have it.
Comment: Even if it's set in a variable session, you can disable it after. So it's unreliable.
Comment: Agree with @DampeS8N. I've made this simple script to check for. http://stackoverflow.com/a/29136452/2480481 (an answer below link).
Comment: Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming)
Answer: perhaps a more simple option...

   This page needs JavaScript activated to work.

my content

Comment: Your solution is clever and efficient, but it does not validate W3C's HTML5 standards: `Element style not allowed as child of element noscript in this context. (Suppressing further errors from this subtree.)` You can keep this simplicity but still be valid, with `

my content
`.
Comment: It is valid HTML5 to put a `
Comment: This doesn't tell you about the script, just warns the user. This is also a good way to autocheck for javascript. Just need to refresh url to the current phpsessid/session and you'll get the confirmation about is not present. No matter if you do w or w/o the javascript, check for it is just easy.
Comment: This is great if you just need to hide a portion of the page if there is no JS, but that's not what the OP was asking. He asked specifically for a way to check for JS from PHP.
Comment: as @Clément said (it does not validate W3C's HTML5 standards) but if you move the code to the head tag, it will be a validate W3C's HTML5 standard and you can use the style in the noscript tag without any problem :)
Comment: Watch at @Chris Thompson.
Comment: This doesn't answer the OPs question so unfortunately can't upvote it, however it's a really nice little trick which I hadn't thought of and and I wanted to say thank you for this @Andy
Answer: No, that is not possible, because PHP is a server side language, it does not access the client's browser in any way or form (the client requests from the PHP server).
The client may provide some meta info through HTTP headers, but they don't necessarily tell you whether the user has JavaScript enabled or not and you can't rely on them anyway,
Comment: A good rule of thumb is to create pages and assume javascript is off.  Once loaded, use javascript to "write" to your page.  This allows for progressive enhancement.
Comment: As many others have pointed out it IS possible it just is not simple. I can not understand why THIs is the accepted answer.
Comment: http://stackoverflow.com/a/29136452/2480481 a two moves way to make Javascript tell you it is.
Answer: Technically no because as the other answers have said, PHP is strictly server-side, but you could do this...
In the PHP page on the server, output (a lot of HTML has been deleted for brevity)

Then in myPage.php set a session variable to indicate the client supports JS
<?php
   session_start();
   $_SESSION['js'] = true;
?>

But really, just use  tags, much, much less effort...
Comment: GOD. This is actually the solution i was thinking for. You ONLY need to check for it. Chris, think about is not the same thing do something using script noscript directive on the client then just KNOW about that and store the data.
Answer: //Here is a solution:
//it works perfect
<?php

if(!isset($_SESSION['js'])||$_SESSION['js']==""){
  echo "<meta http-equiv='refresh' content='0;url=/get-javascript-status.php&js=0'> ";
   $js = true;

 }elseif(isset($_SESSION['js'])&& $_SESSION['js']=="0"){
   $js = false;
   $_SESSION['js']="";

 }elseif(isset($_SESSION['js'])&& $_SESSION['js']=="1"){
   $js = true;
   $_SESSION['js']="";
}

if ($js) {
    echo 'Javascript is enabled';
 } else {
    echo 'Javascript is disabled';
}

?>

//And then inside get-javascript-status.php :
$_SESSION['js'] = isset($_GET['js'])&&$_GET['js']=="0" ? "0":"1";
header('location: /');

Comment: So this would imply (correct me if I'm wrong) that each time a user sees the front page for the first time, it "forces" a redirection so the page is re-loaded an then you check on the reload, if it's javascript enabled? It sounds like it's bringing in an elephant to kill a mouse. But you're right: it works. It would be maybe safer to add a warning before showing the code.
Comment: Seems copied code from another webpage, but not complete. @
Chris Thompson has the correct and easies way to do that.
Comment: Much cleaner than mine, same principle.
Answer: You can't tell if a browser has JS enabled, but you can tell if the browser supports JS http://php.net/manual/en/function.get-browser.php
$js_capable = get_browser(null, true)=>javascript == 1
Having said this, that's probably not of much use. You should reconsider detecting JS from PHP. There should be no need for it if you use progressive enhancement, meaning that JS only adds functionality to what's already on the page.
Comment: Reading the comments from that page actually tells you that it'll tell you whether the browser type in the HTTP headers supports JS, not whether it's enabled.
Comment: I hate being mean, but did you read the link? There are notes about configuring it. I don't suggest using it, by the way, it's not truly reliable for many things.
Comment: @SublymeRick I reworded the answer so it's more obvious that it doesn't solve the problem at hand, but it's still good information to know.
Comment: Do the end users need to configure their systems to use this?
Comment: Progressive enhancement takes on a new meaning when your entire application is written in client-side JavaScript code (Ember or Angular). I'm working on a way to have these sorts of web apps work without JavaScript, and have everything rendered by the server as well as the client-side code.
Comment: @nnyby Consider something like https://developers.google.com/closure/templates/?csw=1 which can render the HTML on the server or the client
Comment: @JuanMendes thanks, I've found out that this can be done pretty easily with PhantomJS (e.g. https://github.com/stephanebisson/ngseo)
Answer:
    <?php if(basename($_SERVER['REQUEST_URI']) != "disable.html"){ ?>
        <meta http-equiv="Refresh" content="0;disable.html">
    <?php } ?>

Place above code in your header file after title tag and set appropriate like[disable.html] for redirection.
Answer: before try you have to disable your browsers javascript...
after then
Try This code :

<meta http-equiv="refresh"content="0; url=script-disabled.html">

congrats ! Your Browser Have Java Script Enabled

Write something in script-disabled.html
its work
Answer: You can try with 2 metod:

setting cookies with JS and detecting them from PHP
creating a form with a hidden field and an empty value; and then assigning some value to it with JS, if the field gets the value – JS is ON, otherwise it's off. But the form had to be submitted first before PHP can request that hidden field's value.

if you want detect if JS enable enable setting before the loading of the page you can try this (I don't konw if it works):
<?php
if (isset($_POST['jstest'])) {
  $nojs = FALSE;
  } else {
  // create a hidden form and submit it with javascript
  echo '<form name="jsform" id="jsform" method="post" style="display:none">';
  echo '<input name="jstest" type="text" value="true" />';
  echo '';
  echo '</form>';
  // the variable below would be set only if the form wasn't submitted, hence JS is disabled
  $nojs = TRUE;
}
if ($nojs){
  //JS is OFF, do the PHP stuff
}
?>

there is a fine tutorial on this issue on address http://www.inspirationbit.com/php-js-detection-of-javascript-browser-settings/
Answer: Here is a small include I made up that I have on top of my pages to detect if js is enabled. Hope this helps out...
<?php
//Check if we should check for js
if ((!isset($_GET['jsEnabled']) || $_GET['jsEnabled'] == 'true') && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])){

   //Check to see if we already found js enabled
   if (!isset($_SESSION['javaEnabled'])){
      //Check if we were redirected by javascript
      if (isset($_GET['jsEnabled'])){
         //Check if we have started a session
         if(session_id() == '') {
            session_start();
         }

         //Set session variable that we have js enabled
         $_SESSION['javaEnabled'] = true;
      }
      else{
         $reqUrl = $_SERVER['REQUEST_URI'];
         $paramConnector = (strpos($reqUrl, "?"))? "&" : "?";

         echo "

               <meta HTTP-EQUIV='REFRESH' content='0; " . $reqUrl . $paramConnector . "jsEnabled=false'>

         ";

         //Break out and try again to check js
         exit;
      }
   }
}
?>

Comment: This works perfect! The only thing is about the URL. Once you get true or false, the state is perpetued, because you are reading the current GET params. So, if i check that, and block javascript the result is faked with the URL params. Running from the entry point is working perfect. Thanks for that example :)
Answer:

<?php
  if(!isset($_REQUEST['JS'])){?>

      <meta http-equiv="refresh" content="0; url='<?php echo basename($_SERVER['PHP_SELF']);?>?JS='"/>
    <?php
  }
?>

<?php
  if(isset($_REQUEST['JS'])) echo 'JavaScript is Disabled';
  else echo 'JavaScript is Enabled';
?>

Answer: PHP can't be used to detect whether javascript is enabled or not. Instead use  to display an alternate message / do something.
Comment: Browsers don't load separate JavaScript-files if JavaScript is disabled. This is something PHP could detect. Resp.: Htaccess could set a cookie based on the request.
Answer: To get rid of bots with JS disabled:
<?php
session_start();
@$_SESSION['pagecount']++;
?>

<?php
if (!isset($_COOKIE['JSEnabled']) || strlen($_COOKIE['JSEnabled'])!=32 ) {
  $js_cookie=md5(md5(@$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']);
  echo '';
  echo '<meta http-equiv="refresh" content="0;url=http://example.com"/>';
}
?>

<?php
 $js=$_COOKIE['JSEnabled'];
 if ($js!=md5(md5(@$_SESSION['pagecount']-1) . $_SERVER['REMOTE_ADDR'])) {
 $js_cookie=md5(md5(@$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']);
  echo '';
     echo "Sorry, this website needs javascript and cookies enabled.";
     die();
 } else {
  $js_cookie=md5(md5(@$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']);
  echo '';

 }

?>

No one can use for example curl -H "Cookie: JSEnabled=XXXXXXXXXXXXXXXXXX"
because they don't know your algo of computing the hash.
Answer: This is the way I check whether javascript and cookies are enabled or not http://asdlog.com/Check_if_cookies_and_javascript_are_enabled
I copy/paste it here
<?
if($_SESSION['JSexe']){     //3rd check js
    if($_COOKIE['JS'])  setcookie('JS','JS',time()-1);//check on every page load
    else            header('Location: js.html');
}               //2nd so far it's been server-side scripting. Client-side scripting must be executed once to set second cookie.
                //Without JSexe, user with cookies and js enabled would be sent to js.html the first page load.
elseif($_COOKIE['PHP'])     $_SESSION['JSexe'] = true;
else{               //1st check cookies
    if($_GET['cookie']) header('Location: cookies.html');
    else{
                setcookie('PHP','PHP');
                header('Location: '.$_SERVER['REQUEST_URI'].'?cookie=1');
    }
}
?>

Comment: This includes 3rd party right? Seems that but is not advised.
Answer: Recently, I had the following dilemma:
I use a PHP function that generates a QR image related to the current URL, which is very useful for mobile devices. The function works fine, but having my site on a shared hosting, there are some limits for CPU and RAM usage. This function is to heavy and it consumes a lot of CPU time and RAM, so the hosting guys asked me to decrease the usage.
After some tries, I finally reached the idea that I can save some CPU & RAM usage from search engine bots. It is difficult to recognize a bot by browser identification, but all the bots have no JS enabled and that's the main criteria I used to detect if it is a real browser or it is a bot. To explain how significant it is to prevent executing code which will not give anything more for Search Engines (QR, in my case, does not affect search engines), I can say that just Google bot for example makes about 16000 crawls a day on my site.
So I've made this very simple thing which helped a lot:

This code uses JS to write a line of PHP code, so this line will be written only when JS is enabled.
Of couse you can use 'noscript' tag if you want to show something when JS is disabled, but this method shows how to execute some PHP only when JS is enabled.
Hope this helps.
Comment: Does not work. The PHP code is always executed, instead use `no JS` to detect
Comment: PHP code is always executed - righ, but `document.write` which actualy adds it to the document structure - not. `` could or couldn't be managed by a bot - depends on the bot ... but javascript normally is disabled in all bots I know.
Comment: You should clarify that `drawQR` writes out an `` tag with a `SRC` pointing at the QR generation script - otherwise, it looks like you generate the QR code and then write out a link to it only if the user has JS enabled.
Answer: Create a cookie using JavaScript and read it using PHP.
Comment: Yes, this is basically the raw answer. You can do that using php session functions wich is in fact a cookie managed by PHP. But, do not limit your code to cookies. One thing is check for javascript technology and the other is about cookie permissions. Using javascript GET we can check for more things than a cookie. We can write to a server file instead a cookie, as example.
Answer: Please despite all the people telling you cant check for a client-side scripting technology. If the target technology has http functions, you can do ALWAYS, just write out a verify step. That means literally, the way to check javascript is to run javascript. If javascript is disabled on the browser side it's not possible to check if the client is Javascript capable (like Dillo with it's default config or others)
UPDATED: I've develop this script because i test some of the examples here and seems that everybody does copypasting without any sort of tests. Code is also on the Gist https://gist.github.com/erm3nda/4af114b520c7208f8f3f (updated)
//function to check for session after|before PHP version 5.4.0
function start_session() {
    if(version_compare(phpversion(), "5.4.0") != -1){
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
    } else {
        if(session_id() == '') {
            session_start();
        }
    }
}

// starting the function
start_session();

// create a script to run on the AJAX GET request from :P Javascript enabled browser
echo
    '
    ;

// Ajax GET request handle
if ($_REQUEST['sessionstart'] == 1){
    $_SESSION['js'] = 1; // save into session variable
  } else {
    session_destroy(); // force reset the test. otherwise session
  }

// If the session variable has not saved by the AJAX call, loads again.
if (!isset($_SESSION['js'])){
    header("Refresh: 1"); // thats only for the first load
    echo "Javascript is not enabled
"; // Return false
} else {
    echo "Javascript is enabled
"; // Return true
}

This solution do not need more files, just a iteration if you run a Javascript capable browser. The value is passed back to PHP using a GET with a simple variable but anyone can fake the output doing cURL to url + ?sessionstart=1 unless you add more logic to it.
Comment: I have fixed it mostly, but in some cases it wasn't working, don't even remember. Then, I simply switched to server-side 2nd round verification. However, dropped it completely given the GDPR and all.
Comment: Unfortunately, this is not working for me. I have tested script in Chrome and FF, and always receive "Javascript is not enabled", despite the fact that it is. Also, line 53 is generating undefined sessionstart index notice. Could you explain a little how we can use this script? Thanks.
Comment: Maybe late, sorry. I've tested again using Firefox with those results: https://vid.me/8a8b. Also tried with Chrome and failed. I'll try to update asap.
Comment: @dev101 late again. There are many options there that works, no need to edit more. Example, an answer below, https://stackoverflow.com/a/13130211/2480481
Comment: Im sorry but curious about how does affect GDPR to a Javascript check. Is about cookies? Yep, 2nd round is more hidden and doesn't need for sessions.
Answer: With this basic ajax you can separate data that the client see based on javascript or not.
index.php
    <!DOCTYPE html>

    no javascript

jscheckCon.php
<?php
echo 'we have javascript!';//you can do that you like to do with js!
?>

Answer: Make your main php page assume jscript is off, and add a  immediately after you close you main #container div and before your noscript tag. (if you're using jquery of course).
Doing it this way will show the HTML for the non-js enabled browsers automatically, and then the js enabled browsers will only see the js site.
If you're worried about over-bloating the page size with too much mark up, then you could do the same but instead leave

 empty, then with the js code instead of just showing the div use an ajax call to fetch the content for it.
On a  side note, I would probably include additional css files for the non-js site within the noscript tag to save on bandwidth.
Answer: Since PHP is server side you can't know in PHP whether the client has Javascript enabled unless you use sessions (or some other way to store data across requests) and first send some code to which the client responds.
If you put the following at the start of your PHP file the client is redirected to the same URL with either 'js=0' or 'js=1' appended to the query string, depending on whether they have Javascript enabled or not. Upon receiving the redirected request the script records the result in a session variable and then redirects back to the original URL, i.e. without the appended 'js=0' or 'js=1'.Upon receiving this second redirect the script proceeds as normal, now with the session variable set according to the clients Javascript capability.
If you don't care about how your query string looks in the user's address bar you can skip the second redirect and just set the session variable. While these redirects are taking place the user is shown a short informative message (also something you could skip if you don't care about that).
<?php
session_start();
if (!isset($_SESSION['js']) && !isset($_GET['js'])) {
    $url=$_SERVER['SCRIPT_URI'];
    $qry='?'.($q=$_SERVER['QUERY_STRING']).($q?'&':'').'js';
    die('<!DOCTYPE html><meta charset="utf-8" /><title>js check</title>'.
        ''.
        '<meta http-equiv="refresh" content="0; url='.$url.$qry.'=0" />'.
        'Hold on while we check whether you have Javascript enabled.');
} elseif (isset($_GET['js'])) {
    $_SESSION['js']=$_GET['js'];
    $qry = preg_replace('%&?js=(0|1)$%', '', $_SERVER['QUERY_STRING']);
    $url = $_SERVER['SCRIPT_URI'].($qry?'?':'').$qry;
    die('<!DOCTYPE html><meta charset="utf-8" /><title>js check</title>'.
        '<meta http-equiv="refresh" content="0; url='.$url.$qry.'" />'.
        'Hold on while we check whether you have Javascript enabled.');
}

if ($_SESSION['js']) {
    //Javascript is enabled
} else {
    //Javascript is disabled
}
?>

Answer: Yes.
Ensure you have the latest jQuery.js
//javascript
$(function(){
$('#jsEnabled2').html('Yes it is')
})

//php
$js - 'No';
$jscheck = 'Javascript Enabled: ';
$jscheck .= ''.$js.'';
print $jscheck;

Comment: That will tell the USER if JS is enabled, it won't tell the PHP script. And why does it need the __latest__ jQuery, it looks like it should work in practically any version?  You don't even need PHP for this. Just put the SPAN diectly in your HTML. Finally, your assignment to `$js` has a typo.
Comment: I believe the question was to use php to check if it was enable. In this example, a php variable is printed, it will be no unless javascript is enabled; no?

Check if JavaScript is enabled with PHP