How to organize resources (styles, ...) in a complex WPF scenario?

Question: How can WPF resources - including styles, templates, etc. - be organized, so that I can use them across Windows, Pages or even Projects. What options do I have to achieve maximum re-usability of my resources and a maintainable structure (for example one file per Template)?
For example: I am creating a WPF application and I want to use a TabControl, but I want to make major changes to it. So I could create a style in  and apply it to the TabControl and TabItem. That's ok, but where can I place my resources to keep my Window XAML clear and have the style accessible from other Windows or projects as well?
I found that I can add it to App.xaml but that is only a solution for one project and allows sharing just between items of this project. Also, I think it would be better to have these templates a little separate from other code, than placing it all in some page or app.xaml?
Comment: You can create a ResourceDictionary and add it on an ClassLibrary. You have to reference it on your App.xaml and you can use the Library in many projects
Answer: I usually create a seperate styling project, which I reference from the projects, which I want to style. The styling project has a fixed structure like this:

For every control, I create a styling ResourceDictionary. For example for my buttons:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

</ResourceDictionary>

In one main ResourceDictionary, I merge all the other dictionaries, in this case in the file IncaDesign.xaml, which you can see in the picture above:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:controls="clr-namespace:Commons.Controls;assembly=Commons">

    <ResourceDictionary.MergedDictionaries>

        <ResourceDictionary Source="Converter/Converter.xaml" />
        <ResourceDictionary Source="Styles/Button.xaml" />
        <ResourceDictionary Source="BitmapGraphics/Icons.xaml" />

    </ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

Notice how I defined the default styles, which are applied automatically, unless you specify otherwise. In every window or control, that you want to style, you only need to reference this one ResourceDictionary. Note the definition of the source, which is a reference to the assembly (/Commons.Styling;component...)
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Commons.Styling;component/IncaDesign.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

Default styles will be set automatically now, and if you want to access a resource explicitly, you can do this, using StaticResource.
<Viewbox Height="16" Width="16" Margin="0,0,10,0">
    <ContentControl Content="{StaticResource FileIcon32}" />
</Viewbox>

This is very nice solution in my opinion, which works for very complex solutions, including modular solutions, for example built with PRISM.
Comment: The most important thing is to avoid cross references and unsystematic merging of dictionaries. This is what really causes trouble, as you create duplicates of all your resources all the time, not the ResourceDictionary itself. I think this is the point, the article you've linked is referring to. I don't see a way of avoiding ResourceDictionaries in a complex project... And this is exactly the idea of the styling project: To avoid merging dictionaries in many places...
Comment: Keep in mind that ResourceDictionary instances are resource heavy and you are better off avoiding them if possible. [See VI.](http://pelebyte.net/blog/2011/07/11/twelve-ways-to-improve-wpf-performance/)
Comment: Exactly what I was looking for :) Thank you. I just must read more about that possible problems with this.
Comment: This is an old question/answer but what project type do you use for your common project?
Comment: @WBuck Its a class library. Just add the required references to PresentationCore, PresentationFramework,System.Xaml,WindowsBase and it should work well.
Comment: I partly agree with Nathan. As Marc described, ResourceDictionary do (nothing but) organizing your xaml into different files. Referencing all relevant ResourceDictionaries in your App.xaml makes them globally available for all Windows and UserControls. In a UserControl -> adding a reference to a ResourceDictionary that is already referenced in App.xaml creates new instances with every UserControl instance. This is resource heavy and not required. Working with modular architectures like PRISM the WPF designer might require such a reference, but not at application runtime.
Comment: And how use resources from Colors/colors.xaml into others xaml like Button.xaml for example ?
Comment: Ok, I found solution, it just add to source the color file like that :
Comment: This seems to be very good solution ! But how integrate the styling in an app ?
    I add my styling project to the reference and add followings lines to my app.xaml... It's ok in conceptor, but it crash at execution ...

Answer: A ResourceDictionary is for what you are looking.
Here is an explanation for how to use them within and across projects.
Comment: The link is broken. Any backup?
Answer: You can create a project that contains Resource Dictionaries, either in your solution or in a separate one. Your project will be a Class Library type and can then easily be .dll referenced from any other project. Here is an article describing this: Resource Dictionary Article


Como fazer um menu que ao clicar abre outra div?

Question: EXEMPLO: eu quero criar um menu que terá quatro links, e cada link abre uma determinada div com conteudos diferentes em cada div. tipo o desse site aqui http://www.futebol.com/ a parte que tem TODOS / FINALIZADOS / AO VIVO / PROXIMOS.
OBS: Desculpem qualquer coisa pois estou aprendendo ainda!!!
Answer: Aqui tem um exemplo que como fazer, existem várias maneiras.

$('.seccao:gt(0)').hide(); // para começar vamos esconder todas as seccoes excepto a primeira
$('.menu-item').on('click', function() { // quando clicamos num item do menu
  $('.seccao').hide(); // escondemos todas
  var seccao = $(this).data('open'); // aqui vamos obter o id da seccao a aparecer ex: '#todos'
  $(seccao).show(); // e finalmente mostramos a seccao que tem o mesmo id do atributo data-open do item em que clicamos
});
.seccao {
 background-color: green;
}

  TODOS

  FINALIZADOS

  AO VIVO

  PROXIMOS.

    TODOS OS JOGOS APARECEM AQUI

    TODOS OS JOGOS finalizados APARECEM AQUI

    TODOS OS JOGOS AO VIVO APARECEM AQUI

    TODOS OS JOGOS PROXIMOS APARECEM AQUI

Answer: Caso queira ver o exemplo ao vivo: http://codepen.io/leofontes/pen/aBmKzG
Aqui vai um Codepen com um exemplo bem básico, só pra você ter uma ideia do caminho, mas recomendo entender o que está acontecendo e tentar fazer um você mesmo:
HTML

  Menu1
  Menu2
  Menu3
  Menu4

CSS
div {
  display: none;
  height: 200px;
  width: 200px;
}

#um {
  background-color: red;
}

#dois {
  background-color: blue;
}

#tres {
  background-color: purple;
}

#quatro {
  background-color: green;
}

Javascript
$('#linkUm').click(function() {
  $('#um').fadeIn();
});

$('#linkDois').click(function() {
  $('#dois').fadeIn();
});

$('#linkTres').click(function() {
  $('#tres').fadeIn();
});

$('#linkQuatro').click(function() {
  $('#quatro').fadeIn();
});

Comment: pow muito obrigado man era isso mesmo que eu tava procurando


how to access the following json in php I am accessing following way

Question: data base pic that containd duplicate valuesThis Is my JSON half i have posted
 {
    "gstin": "29AAHCS4690J1ZQ",
    "fp": "072017",
    "b2b": [{
            "ctin": "01AAACJ4126D1ZE",
            "cfs": "Y",
            "inv": [{
                "itms": [{
                    "num": 1,
                    "itc": {
                        "tx_cs": 0,
                        "elg": "ip",
                        "tx_i": 112.5
                    },
                    "itm_det": {
                        "csamt": 0,
                        "rt": 18,
                        "txval": 625,
                        "iamt": 112.5
                    }
                }],
                "val": 738,
                "inv_typ": "R",
                "flag": "N",
                "updby": "S",
                "pos": "29",
                "idt": "31-07-2017",
                "rchrg": "N",
                "cflag": "U",
                "inum": "FL-17000069",
                "chksum": "4d3e41facf5002f418e1ac605d9888d74ee21652e19de6db624fc7106e3c5866"
            }]
        },

        {
            "ctin": "29AACFI3027K1ZC",
            "cfs": "Y",
            "inv": [{
                "itms": [{
                    "num": 1800,
                    "itc": {
                        "elg": "ip",
                        "tx_c": 171.59,
                        "tx_s": 171.59
                    },
                    "itm_det": {
                        "samt": 171.59,
                        "rt": 18,
                        "txval": 1906.5,
                        "camt": 171.59
                    }
                }],
                "val": 2250,
                "inv_typ": "R",
                "flag": "N",
                "updby": "S",
                "pos": "29",
                "idt": "06-07-2017",
                "rchrg": "Y",
                "cflag": "U",
                "inum": "0042",
                "chksum": "aa1187a2bb7d6098c39c4c992bd391ab7fd59e7eeefcea5b91fc9881ba4423d8"
            }]
        },
        {
            "ctin": "29AAACT7966R2Z6",
            "cfs": "Y",
            "inv": [{
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 20,
                            "tx_s": 20
                        },
                        "itm_det": {
                            "samt": 20,
                            "rt": 5,
                            "txval": 800,
                            "camt": 20
                        }
                    }],
                    "val": 800,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "06-07-2017",
                    "rchrg": "Y",
                    "cflag": "U",
                    "inum": "507002834",
                    "chksum": "64b19ecd192545bcfeac89f9ef7e30965122d5159be6a66d4c7888a8b6e1b6ae"
                },
                {
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 20.38,
                            "tx_s": 20.38
                        },
                        "itm_det": {
                            "samt": 20.38,
                            "rt": 5,
                            "txval": 815,
                            "camt": 20.38
                        }
                    }],
                    "val": 815,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "26-07-2017",
                    "rchrg": "Y",
                    "cflag": "U",
                    "inum": "507015095",
                    "chksum": "c76544937d5f7b8513bb64d45ba5708ff4f67197652b6ba06a605931b7ce58b6"
                }
            ]
        },
        {
            "ctin": "29AACCM4309H1ZI",
            "cfs": "Y",
            "inv": [{
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "tx_cs": 0,
                            "elg": "ip",
                            "tx_c": 329,
                            "tx_s": 329
                        },
                        "itm_det": {
                            "samt": 329,
                            "csamt": 0,
                            "rt": 28,
                            "txval": 2350,
                            "camt": 329
                        }
                    }],
                    "val": 3008,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "11-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "021/RS/17000016",
                    "chksum": "096e525d241d942cdf7695976d1dfc0ada181ab01d85dc6d6506d4865983a491"
                },
                {
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "tx_cs": 0,
                            "elg": "ip",
                            "tx_c": 452.38,
                            "tx_s": 452.38
                        },
                        "itm_det": {
                            "samt": 452.38,
                            "csamt": 0,
                            "rt": 28,
                            "txval": 3231.25,
                            "camt": 452.38
                        }
                    }],
                    "val": 4136.01,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "21-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "021/RS/17000026",
                    "chksum": "196ff72d3507ea9fe69448cce2df27f9f3bf6ef05c2b691e47f245cb10f53747"
                }
            ]
        },
        {
            "ctin": "29ABRPH6549P1ZK",
            "cfs": "Y",
            "inv": [{
                    "itms": [{
                        "num": 1800,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 114.39,
                            "tx_s": 114.39
                        },
                        "itm_det": {
                            "samt": 114.39,
                            "rt": 18,
                            "txval": 1271,
                            "camt": 114.39
                        }
                    }],
                    "val": 1500,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "31-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "10",
                    "chksum": "5e2c5b651c027f5707fddd422de3301e71d3a713169c9de00da7de688742b030"
                },
                {
                    "itms": [{
                            "num": 500,
                            "itc": {
                                "elg": "ip",
                                "tx_c": 132.5,
                                "tx_s": 132.5
                            },
                            "itm_det": {
                                "samt": 132.5,
                                "rt": 5,
                                "txval": 5300,
                                "camt": 132.5
                            }
                        },
                        {
                            "num": 1200,
                            "itc": {
                                "elg": "ip",
                                "tx_c": 24,
                                "tx_s": 24
                            },
                            "itm_det": {
                                "samt": 24,
                                "rt": 12,
                                "txval": 400,
                                "camt": 24
                            }
                        }
                    ],
                    "val": 6013,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "24-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "9",
                    "chksum": "8aa3acd295c97aad72b174bfd98a521914e5c869608cafbc1f07ed1472f269ca"
                }
            ]
        },
        {
            "ctin": "29AAXFM9455A1ZO",
            "cfs": "Y",
            "inv": [{
                "itms": [{
                    "num": 1,
                    "itc": {
                        "elg": "ip",
                        "tx_c": 385.56,
                        "tx_s": 385.56
                    },
                    "itm_det": {
                        "samt": 385.56,
                        "rt": 28,
                        "txval": 2754,
                        "camt": 385.56
                    }
                }],
                "val": 3526,
                "inv_typ": "R",
                "flag": "N",
                "updby": "S",
                "pos": "29",
                "idt": "28-07-2017",
                "rchrg": "N",
                "cflag": "U",
                "inum": "1718/508",
                "chksum": "03bbeb45778a4ea3019d7c7a2a71d2d3e48ed2433fe4e027606fb2dba59d4a64"
            }]
        },
        {
            "ctin": "29AAACE3688F1ZG",
            "cfs": "Y",
            "inv": [{
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 882.42,
                            "tx_s": 882.42
                        },
                        "itm_det": {
                            "samt": 882.42,
                            "rt": 28,
                            "txval": 6303,
                            "camt": 882.42
                        }
                    }],
                    "val": 8068,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "19-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "EEPLB1718/1208",
                    "chksum": "7afd73b6b9aeada9113b54ec7151ba08fb2ca0a8e23fc89ac3126d8c9722ff66"
                },
                {
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 1137.08,
                            "tx_s": 1137.08
                        },
                        "itm_det": {
                            "samt": 1137.08,
                            "rt": 28,
                            "txval": 8122,
                            "camt": 1137.08
                        }
                    }],
                    "val": 10396,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "24-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "EEPLB1718/1267",
                    "chksum": "5079a0d6c289ee0077fb2fd167fd88691f2a1557cff0d2789912bc9460d35f98"
                },
                {
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 549.36,
                            "tx_s": 549.36
                        },
                        "itm_det": {
                            "samt": 549.36,
                            "rt": 28,
                            "txval": 3924,
                            "camt": 549.36
                        }
                    }],
                    "val": 5023,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "26-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "EEPLB1718/1289",
                    "chksum": "6480112156a400f0ca2380c577c7a59c7a4321da5e845f577be992b6324219ee"
                },
                {
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 888.16,
                            "tx_s": 888.16
                        },
                        "itm_det": {
                            "samt": 888.16,
                            "rt": 28,
                            "txval": 6344,
                            "camt": 888.16
                        }
                    }],
                    "val": 8120,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "28-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "EEPLB1718/1322",
                    "chksum": "4d0f2654fd0c1c1bf0c1a2fceb18adeb74123ec62d2556f569f22372f9ece4e1"
                },
                {
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 602.98,
                            "tx_s": 602.98
                        },
                        "itm_det": {
                            "samt": 602.98,
                            "rt": 28,
                            "txval": 4307,
                            "camt": 602.98
                        }
                    }],
                    "val": 5513,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "29-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "EEPLB1718/1323",
                    "chksum": "a3f0dba67b1352affd1877d45a9eabfe99a60f67cda693881c24ab1f2c967a6d"
                },
                {
                    "itms": [{
                        "num": 1,
                        "itc": {
                            "elg": "ip",
                            "tx_c": 939.68,
                            "tx_s": 939.68
                        },
                        "itm_det": {
                            "samt": 939.68,
                            "rt": 28,
                            "txval": 6712,
                            "camt": 939.68
                        }
                    }],
                    "val": 8591,
                    "inv_typ": "R",
                    "flag": "N",
                    "updby": "S",
                    "pos": "29",
                    "idt": "29-07-2017",
                    "rchrg": "N",
                    "cflag": "U",
                    "inum": "EEPLB1718/1324",
                    "chksum": "77f0c25a4b574129b882395d5a79955cfe23c80cd7edf9accef0afd798696478"
                }
            ]
        }
    ]
 }

This is my PHP code. All the tables are connected with foreign keys.
<?php
$jsondata = file_get_contents($_FILES['file']['tmp_name']);

$data = json_decode($jsondata, true);
//$stmt = $db->prepare("INSERT into itc(ctin, cfs, num, tx_cs, elg, tx_i, tx_c, tx_s, samt, csamt, rt, txval, camt, iamt, val, inv_typ, flag, updby, pos, idt, rchrg, cflag, inum, chksum) values(: ctin,: cfs,: num,: tx_cs,: elg,: tx_i,: tx_c,: tx_s,: samt,: csamt,: rt,: txval,: camt,: iamt,: val,: inv_typ,: flag,: updby,: pos,: idt,: rchrg,: cflag,: inum,: chksum)");

$gstin = $data['gstin'];
$fp = $data['fp'];
$stmt = "INSERT INTO gstin (gstin, fp) VALUES('$gstin', '$fp')";

mysqli_query($conn, $stmt);

foreach ($data['b2b'] as $row1) {
    $ctin = $row1['ctin'];
    $cfs = $row1['cfs'];

    $gst_id = '';

    $sql = "SELECT `auto_increment` as LastID FROM INFORMATION_SCHEMA.TABLES
    WHERE table_name = 'gstin'
    ";
    $result = mysqli_query($conn, $sql);

    // if (mysqli_num_rows($result) > 0) {

        //if ($row = mysqli_fetch_assoc($result)) {
            //$lclId = intval($row["LastID"]) - 1 + intval('1');
            //$gst_id = 'BU-'.$lclId  ;
            //echo $row["LastID"];
        //}
    //} else {
    // }

    $gst_id = intval($row["LastID"]) - 1;

    //echo $gst_id;
    //$lclDeptCode = 'DS-01';
    //$gst_id = $lclId  ;
    //echo $row["LastID"];
}

$stmt = "INSERT INTO b2b (ctin, cfs, gst_id) VALUES('$ctin', '$cfs', '$gst_id')";

mysqli_query($conn, $stmt);

foreach ($row1['inv'] as $row3) {
    $val = $row3['val'];
    $inv_typ = $row3['inv_typ'];
    $flag = $row3['flag'];
    $updby = $row3['updby'];
    $pos = $row3['pos'];
    $idt = $row3['idt'];
    $rchrg = $row3['rchrg'];
    $cflag = $row3['cflag'];
    $inum = $row3['inum'];
    $chksum = $row3['chksum'];

    $b_id = '';
    $sql = "SELECT `auto_increment` as LastID FROM INFORMATION_SCHEMA.TABLES
    WHERE table_name = 'b2b'";

    $result = mysqli_query($conn, $sql);

    if ($row = mysqli_fetch_assoc($result)) {
        $b_id = intval($row["LastID"]) - 1;
    }

    $stmt = "INSERT INTO inv (val, inv_typ, flag, updby, pos, idt, rchrg, cflag, inum, chksum, b_id)
    VALUES('$val', '$inv_typ', '$flag', '$updby', '$pos', '$idt', '$rchrg', '$cflag', '$inum', '$chksum', '$b_id')";

    $result = mysqli_query($conn, $stmt);

    foreach($row1['inv'][0]['itms'] as $row2) {
        // echo $row2;
        // print_r($row2);
        $tx_cs = $row2['itc']['tx_cs'];
        $elg = $row2['itc']['elg'];
        $tx_i = $row2['itc']['tx_i'];
        $tx_c = $row2['itc']['tx_c'];
        $tx_s = $row2['itc']['tx_s'];
        $samt = $row2['itm_det']['samt'];
        $csamt = $row2['itm_det']['csamt'];
        $rt = $row2['itm_det']['rt'];
        $txval = $row2['itm_det']['txval'];
        $camt = $row2['itm_det']['camt'];
        $iamt = $row2['itm_det']['iamt'];

        $inv_id = '';
        $sql = "SELECT `auto_increment` as LastID FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'inv'";
        $result = mysqli_query($conn, $sql);

        if ($row = mysqli_fetch_assoc($result)) {
        //}
        //if (mysqli_num_rows($result) > 0) {
            $inv_id = intval($row["LastID"]) - 1;
        }

        $stmt = "INSERT INTO itms (tx_cs, elg, tx_i, tx_c, tx_s, samt, csamt, rt, txval, camt, iamt, inv_id)
        VALUES('$tx_cs', '$elg', '$tx_i', '$tx_c', '$tx_s', '$samt', '$csamt', '$rt', '$txval', '$camt', '$iamt', '$inv_id')";

        $result = mysqli_query($conn, $stmt);
    }
}
}

I am getting duplicate values in columns tx_i, tx_c, tx_i.
Is there an alternative way to access values and I am getting undefined index tx_i in itms array even though the key is present.
Comment: Use json_encode and var_dump to understand the structure of the object.
Comment: I have done but getting duplicate values
Comment: my problem is only for itms array not for other arrays
Comment: What's the output of var_dump(json_decode($json)); ? (Please add it to your question and i'll do my best to help you)
Comment: Please show your php code.
Comment: php code end of the json
Comment: First decode JSON string using json_decode(), then access as key value.
Comment: I have Updated my php code
Answer: <?php

$jsondata = file_get_contents('file.json');

$data = json_decode($jsondata, true);

echo'
';

$tx_i=array();
$tx_c=array();
$tx_s=array();
foreach($data['b2b'] as $row){

    (isset($row['inv'][0]['itms'][0]['itc']['tx_i'])) ? $tx_i[]=$row['inv'][0]['itms'][0]['itc']['tx_i'] : null;
    (isset($row['inv'][0]['itms'][0]['itc']['tx_s'])) ? $tx_s[]=$row['inv'][0]['itms'][0]['itc']['tx_s'] : null;
    (isset($row['inv'][0]['itms'][0]['itc']['tx_c'])) ? $tx_c[]=$row['inv'][0]['itms'][0]['itc']['tx_c'] : null;
}

print_r($tx_i);
print_r($tx_s);
print_r($tx_c);

This code checks if the tx_i , tx_s , tx_c values exist and if they do it puts each of them in a new array.
The output is :
Array
(
    [0] => 112.5
)
Array
(
    [0] => 171.59
    [1] => 20
    [2] => 329
    [3] => 114.39
    [4] => 385.56
    [5] => 882.42
)
Array
(
    [0] => 171.59
    [1] => 20
    [2] => 329
    [3] => 114.39
    [4] => 385.56
    [5] => 882.42
)

The "main" issue was that in the same path you have the variables you want and sometimes they don't exist. So in one array you may have tx_i and in the next array have tx_c in it's position so you need to see first if they are set.
Comment: bro, getting Warning: Cannot use a scalar value as an array
Comment: Where do you get this error and what php version do you have?
Comment: here, (isset($row['inv'][0]['itms'][0]['itc']['tx_i'])) ? $tx_i[]=$row['inv'][0]['itms'][0]['itc']['tx_i'] : null; for all 3   and again getting duplicate values are inserted.
Comment: https://www.abeautifulsite.net/how-to-use-the-php-ternary-operator

Propably  you are having a php version older than 5.3. I provide you the manual to convert it to a normal if/else it's easy. Don't forget the isset that does the trick do get the output i provided.
Comment: If your php version is more than 5.3 make sure that in your code you include this :
`$tx_i=array();`
`$tx_c=array();`
`$tx_s=array();`

That is 99% the reason a scala error appears, that an array is not "defined" as an array. This will solve your error.
Comment: PHP Version 5.5.19 this is my php version
Comment: Did you define the arrays before you use them as i saw you in the above comment? like i define them in my code?
Comment: bro, if the inv contains more number of itms inside inv that time foreach looping only the first itc and itm_det that is not going deeply
Comment: My code will go to position 0 where the itc values are. Is there any chance that itc values exist also in other parts of your json? Basically my code follows a specific path that i saw that are the values you want.
Comment: Then what is the problem. can you saw me which part fails and where it fails?
Comment: i will share my database pic
Comment: can I use foreach loop bracket separately
Comment: you mean use $data instead of $data['b2b'] ?
Comment: same way but 1st foreach loop ends before the next foreach loop start
Comment: In my code i have 1 foreach loop to parse through your json. But you can try it. This part of my code works in order to get the values you want from your json so moving forward to your code you have to see how you insert those values in the db. For sure you will need a loop because we are talking about arrays.


Cross-lagged analysis. Interpretation of Coefficients and Covariates

Question: I am currently, for the first time, conducting cross-lagged panel analyses to test for temporal precendence in the relationship between two variables. I have two questions:
How do you interpret, in words, the respective cross-lagged coefficients. Is it similar to regression as in (given they are unstandardized): one unit increase in X from t1 to t2 leads to ß increase in Y from t1 to t2?
Secondly, do you typically include time-constant covariates/control variables in the model, if yes how would you do that? - simply running them as multiple regression on X1 and Y1 within the cross-lagged analysis?
Any help would be greatly appreciated.
Answer: The interpretation of the path coefficients is the same as the interpretation of partial regression coefficients in multiple regression. I would say something like: "A one-unit increase in X at Time 1 is associated with a  ß-unit increase in Y at Time 2, controlling for the autoregression of Y on itself over time."
One would typically use path analysis for autoregressive/cross-lagged models because path models allow you to consider multiple dependent and independent variables simultaneously. You can then simply add covariates at whichever time point is theoretically appropriate. You could, for example, include time-invariant covariates ("traits") as additional predictors at each time point.


Automatically hide LinqPad query

Question: I wrote a simple tool to decode JWT tokens and I'd like to use it in a similar way as the Interactive Regex Evaluator.
Is there a way to either automatically hide a query (e.g., via the Util class) or to even register it to something like Ctrl+Shift+F2?
Answer: Unfortunately that functionality doesn't exist.
You'll notice when using the Interactive Regex Evaluator it's opening the sample of the same name but doing extra work to hide the query panel. Looking at LinqPads code using it's own ILSpy, there's a method called LINQPad.UI.MainForm.miRegex_Click and it's calling the method LINQPad.UI.QueryControl.ToggleFullPaneResults which does that functionality but unfortunately the method is internal.
If you'd like to suggest the feature head over to the LinqPad forums over at http://forum.linqpad.net/ and make the suggestion. Joseph is good at getting back to people.
Comment: Thanks for investigating this. I created a feature suggestion.

Automatically hide LinqPad query


Intersection of two arrays in multiple arrays

Question: I'm searching for a way for extracting common values in at least two arrays in the list of arrays in JS.
e.g. [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]] to ["reddit", "telegram]
The point is 1. the arrays can be any length 2. common at least two (or any specified number) of arrays but not all of the arrays.
I looked a countless numbers of SO posts and also looked the lodash functions, they are all talking either "of two arrays" or "of all arrays from multiple arrays", none of them were takling "of two/arbitrary arrays from multiple arrays". So I'm here to ask.
Thanks.
Comment: `[...new Set(input.flat())].map(_=>[_,input.flat().filter($=>$===_).length]).filter(([,_])=>_>1).map(([_])=>_)`
Comment: @mplungjan BF does not include a-z, so no ... it was written to work as a one-liner (my favourite type of code), with minimal help for a 5 year veteran of SO who couldn't even bother writing any code :p
Comment: @mplungjan *this will find common values in the same sub array too* - it will also find values that are in ALL arrays (which it shouldn't if you read the OP) ... both *issues* are very easily remedied
Comment: @mplungjan - `[...new Set(input.map(_=>[...new Set(_)]).flat())].map(_=>[_,input.map(_=>[...new Set(_)]).flat().filter($=>$===_).length]).filter(([,_])=>_>1&&__)` :p
Comment: I have posted an answer - with meaningful easier on the eye code :p
Comment: @JaromandaX Is that written in [BrainFuck](https://en.wikipedia.org/wiki/Brainfuck) ? ;) - this will find common values in the same sub array too
Comment: I made an O(n) version which is not a one liner but more efficient and easier on the eye
Comment: @JaromandaX You should answer and give the reasons for the two versions
Answer: using various Array methods, and Set, it can be accomplished fairly easily

const input = [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]];

// remove duplicaates within a sub array
const uniqueInSub = input.map(_=>[...new Set(_)]);

// create a list of all values in a flat array
const uniqueInSubFlat = uniqueInSub.flat();

// list of unique values
const values = [...new Set(uniqueInSubFlat)];

// array of [value, count] pairs
const pre1 = values.map(value => [ value, uniqueInSubFlat.filter(subValue => subValue === value).length]);

// value,count pairs where the count > 1 and < the number of sub arrays
const pre2 = pre1.filter(([, count]) => count > 1 && count < input.length);

// array of values
const result = pre2.map(([value])=>value);

console.log(result);
Comment: @Yunnosch - what is a s**m question and wtf does it have to do with me?
Answer:

let arr = [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]]

const flatedArr =arr.flat(Infinity);

const repeatedItems = []
const nonRepeatedItems = []

flatedArr.forEach(val => {

  if(nonRepeatedItems.includes(val))
   return repeatedItems.push(val)

  return nonRepeatedItems.push(val)
})

console.log(repeatedItems);  // ["reddit","telegram"]
Answer: Here is an O(n) version using Map to not bother about the type of the values
Note this will also return dupes in one array

const extractCommonValues = arr => {
  const counts = arr.flat().reduce((acc, cur) => (acc.set(cur, (acc.get(cur) || 0) + 1), acc), new Map());
  return [...counts.keys()].filter(el => counts.get(el) > 1);
};

console.log(
extractCommonValues([["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]])
)

// will extract the dupe amazon in the first array
console.log(
extractCommonValues([["google", "amazon", "reddit", "amazon"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]])
)

To ignore dupes in the sub arrays we can set them first

const extractCommonValues = arr => {
  const counts = arr.map(subArr => [...new Set(subArr)]).flat().reduce((acc, cur) => (acc.set(cur, (acc.get(cur) || 0) + 1), acc), new Map());
  return [...counts.keys()].filter(el => counts.get(el) > 1);
};

console.log(
  extractCommonValues([["google", "amazon", "reddit", "amazon"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]])
)
Answer:

function findCommonValues(arrays, minCommon) {
  // Create an object to keep track of the count of each value
  const countMap = new Map();

  // Iterate over each array
  for (const array of arrays) {
    // Iterate over each value in the array
    for (const value of array) {
      // Increment the count for the current value
      countMap.set(value, (countMap.get(value) || 0) + 1);
    }
  }

  // Filter the values that have a count equal to or greater than the specified minimum
  const commonValues = [];
  for (const [value, count] of countMap.entries()) {
    if (count >= minCommon) {
      commonValues.push(value);
    }
  }

  return commonValues;
}

// Example usage
const arrays = [
  ["google", "amazon", "reddit"],
  ["telegram", "reddit", "discord"],
  ["firefox", "telegram", "chrome"]
];

const commonValues = findCommonValues(arrays, 2);
console.log(commonValues); // Output: ["reddit", "telegram"]
Comment: Hi, You may consider the time complexity here which is  O(n * m + k + u), where n represents the number of arrays, m represents the maximum number of values in any array, k represents the total number of values in all arrays, and u represents the number of unique values in all arrays.
Answer: You could use .flat() and .filter() methods as follows:

const
      data = [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]],

      common = [...new Set(data.flat().filter((v,i,a) => a.filter(val => val === v).length > 1))];

console.log( common );

Or More efficiently ....

const
      data = [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]],

      all = data.flat(),

      uniq = [...new Set(all)],

      common = uniq.filter(v => all.filter(val => val === v).length > 1);

console.log( common );


Proof: If a matrix is semi-definite and symmetric positive then it is a covariance matrix

Question: Anyone have the following proof? If a matrix is semi-definite positive and symmetric then it is a covariance matrix.
Comment: One proof is that (assuming it is symmetric) it is the covariance matrix of the (multivariate) Normal distribution it determines, *qed.*
Comment: it may not be symmetric
Comment: a covariance matrix is a matrix that is a positive semi definite matrix. (any) definiteness can be a property of any matrix. whether a covariance matrix obtains a specific type of definiteness depends on the nature of the data the covariances are being computed for
Answer: Let $\mathbf{\Sigma}$ be an arbitrary $n \times n$ real symmetric positive semi-definite matrix.  Consider the normal random vector $\mathbf{X} \sim \text{N}(\mathbf{0}, \mathbf{\Sigma})$ with density function:
$$p(\mathbf{x}) = (2 \pi)^{-n/2} \det(\mathbf{\Sigma})^{1/2} \exp \Big( -\frac{1}{2} \mathbf{x}^\text{T} \mathbf{\Sigma} \mathbf{x} \Big)
\quad \quad \quad
\text{for all } \mathbf{x} \in \mathbb{R}^n$$
The variance/covariance matrix for this random vector is:
$$\mathbb{V}(\mathbf{X}) = \mathbf{\Sigma}.$$
(Hat-tip to whuber in the comments for this answer.)


Essential things to memorize in music theory

Question: What are some of the essential music theory concepts to memorize?
I just started looking at music theory earlier this week, and I have to admit that it's pretty overwhelming especially since my only background involves playing the guitar--basic chords, playing songs by tabs, etc. Also, I realized how useful music sheet notation is. It abstracts away from the instrument and has an immediate focus on theory. But I'm not quite sure what's essential and what's not. Of course, this depends on the goals of the learner. My goal is to be able to compose with enough theoretical background. I don't plan to write sheet music, take music classes (although I'm taking a few online classes on coursera), or play the instrument proficiently by any means. What I want to do is analyze the songs that I like and ask myself why I like it in order to achieve my end goal, which again is to compose music.
This is my progress so far:

I'm confident in reading the treble clef, but is reading the bass clef necessary? Rhythm seems rather useless also.
I'm using a midi keyboard so I can apply what I learned (I don't have the fretboard memorized, so I decided to take this path). Someone mentioned that in order to get the intervals down on the piano, I should just learn the 5th interval from each key. I noticed a pattern and it stuck, and it's allowing me to find other intervals with ease. Any other tips?
The intervals of the various triads, 7 chords, and sus chords. Would you guys add something here?

And things I plan to do (or maybe not depending on your opinion):

Learn the 10 essential scales (7 modes and a few others like the altered). I don't think I really need to know them at the top of my head, but taking note of what notes they're comprised of should be enough to know which notes I can play when I see a certain chord. My goal doesn't involve improvising, and I can afford to make time to think.
Learn the different key signatures and their relative keys.
Learn the chord progressions for major and minor keys. The basic I-VII pattern.
Hopefully by now I can finally understand the use for borrowing/applying chords and learn their use cases.

Do you guys have any suggestions? Additions you'd like to make? I was actually inspired by the last todo item to ask this question, and the reason is because while I understand it, I can't see the bigger picture in terms of applying it to my own composition. I'm juggling a lot of concepts in my head (which is great for learning imo), but while I'm at it, I'd like to add more todos so I'm constantly overwhelmed.
Comment: It's not like music theory is just a checklist of items to memorize. How you use the ideas is much more important and most people approach how to use the theory in different ways.
Comment: Sounds like you should take classes. You have enough interest in music theory to begin with. So don't underestimate theory, there are no shortcuts to it.
Comment: I agree, but my focus at the moment is like learning the basics of a foreign language. I want to get up to speed just enough so I can understand specific concepts much easier. Hopefully by then I'll apply it in various ways as you have said. My concern is that I may be learning stuff that's useless for what I'm doing, or possibly missed something that's pretty important to music theory.
Comment: This question might be closed as too broad and or opinion based.  But I have many of the same goals as you do.  I am a singer songwriter and I play guitar & some keyboard.  I have always played by ear but as I become more advanced in my songwriting and composition, I have developed an interest in learning more theory.  I have actually found this site to be very helpful in that regard.  I look for questions that interest me or ones that I want to know the answer to b/c I feel it may help me with my goals.  Then reading the answers gives me information I can apply.
Comment: Popular music is rather eclectic nowadays: It borrows from all genres and cultures. You need to know *everything* to understand why you like it (and even then you will fail sometimes, it's art in the end). One particular song might be easily analyzable with some classical theory but you'll eventually run into jazz harmonies, polyrhythms, additive rhythms, Indian scales, microtones and what not in one of your favorite songs.
Comment: Don't forget inversions.  And voice leading.
Comment: @user18822 To give you some encouragement and reduce your feeling of being overwhelmed, what if you try playing simple songs using the chords you already know. Many songs like Twinkle twinkle little stars use 3-4 chords only. By playing you will reinforce your memory, and get encouraged because you can see the results of your hard work quickly. Then you can expand this to playing songs with 6 chords (I, IV, V, ii, iii, vi). Take one step at a time. **Good luck**☺
Comment: @user18822 and let me share this: before i learned to play the piano, i could only compose two proper songs in one year. After i managed to play 6 basic chords in the key of C (only C!), i was able to write ten times as much. Of course, they are simple songs, but listeners find them quite nice. ☺
Comment: @user18822: what do you mean "rhythm is rather useless"?
I, for one, wouldn't want to live in a world where each note is the same duration, like 13th century sacred vocal music.
Comment: Don't worry too much about music theory yet. Start off by learning music notation. If your goal doesn't include improvisation, why do you need to know what scales fit what chords?
Comment: OK, a different answer. Get a teacher who understands where you want to get to. But then, trust him. Don't be so full of what you DON'T want to learn, let him tell you what you DO. And accept that there's no easy fix.
Answer: but is reading the bass clef necessary? Rhythm seems rather useless also.
Cough, cough.  In baroque times, accompaniment was written down by writing down the bass line and rhythm and putting numbers for the type of chord/harmony to be played above the bass line.
While the numbers are gone these days and replaced by explicitly writing out the right hand, the bass line is still the foundation of the harmonies.  And "rhythm seems rather useless also" is also a bit audacious: the rhythm is the skeleton of music.  Even if you are not fond of looking at bones themselves, a collapsed heap of flesh has nothing to hang its features from.
When trying to read piano music and interpret the chords/harmonies, not looking at the bass part is making you miss essential stuff.
Answer: It is more essential to be able to hear (recognize exactly) and to sing everything you learn than to memorize it. Music theory is only a structured way of thinking about music. If you are not able to hear what you are thinking about then it is merely words and ideas, not music. Learn to hear and sing intervals, then 3 and 4 note chords, then chords with extensions, scales, chord progressions; these are the building blocks of composition or improvisation. Doing exercises on paper and then not hearing them on the piano is not absolutely pointless but it is not very smart.
As for the intellectual side of things,  first you probably should memorize the circle of fourths or fifths, and then if you practice ear training in the 12 keys eventually you will memorize scales, chords and whatever you need.
Comment: You certainly don't need to, however the way to achieve freedom and facility in composition is to hear things. You just mentioned sound. Isn't it contradictory to say hearing is not important when it comes to sound? If composition is about creating "pleasing sounds" as it's usually said, the best way to create these sounds is to be able to hear them, not to go around feeling in the dark for good melodies or progressions.
Comment: I disagree with this.  Not everyone learns or composes best with auditory methods; you don't have to hear a sound in order to produce it.
Comment: @mcpca i agree. People learn best by doing the actual thing, rather than a simulation.
Comment: I really like this answer as it simplifies many of the things that i need to keep track of. I never saw sheet music that useful other than as a means of communication, but that isnt my intentention in the slightest.
Comment: I have written melodies for two years now and only in the last two months been playing and listening to them. You have to be familiar with the tenants of good melody writing before you play anything.
Answer: First off, you need to understand what music theory actually is. Wikipedia defines it as:

Music theory considers the practices and possibilities of music. It is
  generally derived from observation of how musicians and composers
  actually make music, but includes hypothetical speculation. Most
  commonly, the term describes the academic study and analysis of
  fundamental elements of music such as pitch, rhythm, harmony, and
  form, but also refers to descriptions, concepts, or beliefs related to
  music.

I don't completely agree with this definition, but it highlights an important point that being able to read music is fundamental to being able to understand basic elements in music such as:

How to read notes based on the clef (treble, bass, alto , tenor).
A basic understanding rhythms and time signatures.
Intervals and scale patters.

These are very basic ideas covered at the beginning of any music theory book because understanding this is necessary to progress in topics such as:

Chord construction
Form
Harmonic Analysis
Counterpoint and Voice Leading
Modulation

If you are interested in this topic there are a ton of books that will help you understand the topic better and they should be laid out to put the fundamentals necessary to go deeper into the actual theory.
Answer:
What are some of the essential music theory concepts to memorize?

If the subject matter is taught in a intellectually engaging manner then it is rarely needed to make theory an issue of memory.

I'm confident in reading the treble clef, but is reading the bass clef
  necessary?

Yes. you will find it useful to be able to read bass sheet music.

Learn the 10 essential scales (7 modes and a few others like the
  altered). I don't think I really need to know them at the top of my
  head, but taking note of what notes they're comprised of should be
  enough to know which notes I can play when I see a certain chord. My
  goal doesn't involve improvising, and I can afford to make time to
  think.

If you can get your head around semi tones and whole tones you can learn any scale starting on any note. That is all a scale is in essence a bunch of notes a set amount of semitones and whole tones apart.
Answer: In my experience, here are the essentials:

Progressions. Know your I, IV and V chords for all major keys cold. If not for all keys, in all the common keys you play: E, A, D, G, C or whatever else you do. Relative minors (minor vi chords) are probably just as important.
Scales. There are dozens of kinds of scales, but majors and minors are essential and first. The way to learn about them is not to worry so much about sharps and flats, but where half steps occur and where whole steps occur in every scale. It is same for them all. For major scales, half steps between three and four and seven and eight. For minor scales, between two and three and five and six, no matter where you start.
If you are playing anything with a blues base - jazzy stuff, rock and roll included - learn your blue notes for every key you play in: minor third, flat fifth or augmented fourth, and flat seventh.

If you know all this stuff already, you should find a nice self-teaching tool. I used a Harvard Press book on music theory with some great exercises in the back. I was taking the A Train in those days, (I HAD to take the A Train) and got a lot of work in between Inwood and midtown Manhattan.
As for reading, if you are working with keyboards, you want to master the bass clef. It may feel like heavy going, but in the end will be worth it to you. Just drill, drill, drill. Be patient AND persistent, and you can't go wrong.
Answer: The bad news is that at first there is going to be drill drill and then some more drill; the good news is that you will be able to able to finish this drill [of chords} in less than two months if you practice daily for not more than 5 minutes. [Yes 5 minutes ....it is not a misprint].
I believe you have a good Ear Training app;  learn the chords [major and minor] by heart and from there you can progress. This is the key.  Take the time. You will be reworded for it.


Laço de Repetição no Tmemo

Question: Estou utilizando um Tmemo que recebe dados de um edit,porem esse dado vai ser inserido x vezes, a questão é a seguinte:
Ao apertar o botão o Tmemo recebera os dados da seguinte maneira:
Memo1.Lines[10] := ('linha adicionada');

Gostaria que ao clicar no botão os edits fossem limpos, e ao a pessoa digitar os novos dados e ao apertar o mesmo botão, os dados fossem inseridos na linha abaixo no caso Memo1.Lines[11]. e assim repetidamente..
Answer: Em vem de inserir na posição [10], [11] por exemplo, use:
Memo1.lines.add('linha adicionada');

Assim sempre vai adicionar na próxima linha.
E para limpar seus Edits use:
edit1.clear;

Comment: Porem abaixo da linha [10] existem informações
e seu colocar o `Memo1.lines.add ('linha adicionada');`
e a pessoa não digitar nada, ficara o espaço em branco
Comment: No caso para esclarecermos sua duvida, você quer sempre adicionar uma linha nova acima da linha 10 ?
Comment: Embaixo da linha 10. clicando no mesmo botão na que a 10 foi criada.
Comment: @GuilhermeLima, poste seu código para esclarecer melhor sua pergunta. Obrigado.
Comment: `Memo1.Lines.Add('    dose = ' + funcao);
Memo1.Lines.Add('    '+'if'+' '+ cond1+':');
Memo1.Lines.Add('        '+ enta1); `
Ao apertar o botão 1 vez, o Tmemo recebe esses dados
Gostaria que quando apertasse o mesmo botão, ele adicionasse informações na linha de baixo.
Comment: se você usar `Memo1.Lines.Add` ele irá adicionar na próxima linha.
Comment: Concordo totalmente, o problema é como faço para que quando eu apertar o botão X vezes, ele vá adicionado?
Comment: Usando `Memo1.Lines.Add` pois ele irá adicionar sempre no fim do `Memo1`. Independente de quantas vezes você clicar no botão.
Comment: Certo,  pense nesse cenário. Variável X recebe os dados de um edit, e essa variável é escrita no Tmemo. Após isso clicasse no botão o edit e a Variável X receberá novos valores. E deverá ser escrita embaixo da anterior.
Comment: x := edit1.text;
memo1.lines.add(x);

Pode clicar quantas vezes quiser ele sempre adicionará uma linha nova certinho.
Comment: Acho que não estou me explicando bem
Vou adicionar um exemplo real:
edit vai receber a seguinte string: k1 > 90
após dar ok e escrever no memo a pessoa irá digitar
edit vai receber a seguinte string k1 = 100
essa string deve ser escrita abaixo de k1 > 90
Comment: Então, não sei onde você esta errando, pois com `memo1.lines.add();` terá um resultado igual ao que você espera.

Laço de Repetição no Tmemo


Share common templates across groups in GitLab

Question: Using a self-hosted GitLab instance where we need to use common templates across several groups.
Currently we copy and paste templates into a "project-templates" projects within each group. This becomes a maintenance issue when templates are updated.
Is there a better method for managing common templates across multiple groups?
Answer: I am unsure if this is still a concern for you but while digging around for a solution I found this article that is what I am using to guide my way through the problem.
TL;DR

Create a project for storing your template
Add your template yaml
Reference it in your project .gitlab-ci.yaml files with an include stanza

include:
  - project: 'full/path/to/project'
    ref: 'master'
    file: '<file_name>.yml'

The project path is as you would find it in your URL when look at the project in GitLab.


How to negate in Prolog

Question: I'm new to PROLOG and am at the very beginning of the exercises on this page. Given the rules parent(X, Y) and male(X), I'm trying to define a rule mother(X, Y) as
mother(X, Y) :-
    not(male(X)),
    parent(X, Y).

However, in GNU Prolog I get the following error:
| ?- mother(lina, julia).
uncaught exception: error(existence_error(procedure,not/1),mother/2)
| ?-

Answer: \+/1 is the ISO Prolog predicate to "negate". Note that "negate" means here not provable at that point.
You can refer to this excellent answer by @false for more on the subject
Answer: The solution is actually in the exercise file on that page:
female(X) :- \+ male(X).

As @Mog said, negation is the unary \+ operator.

How to negate in Prolog


Routing multiple params / paths to single method

Question: I'm attempting to create the following routing :
<code>/app/{type}
/app/{type}.{format}
/app/{type}/{limit}
/app/{type}/{limit}.{format}
</code>
I would like all of these routes to route to a single method. Do I need to declare a route for each of the paths and params ? Does the ranking of the routes also matter ? e.g do I have to place

/app/{type}.{format}

first before

/app/{type}

?
Comment: You can try [Dynamic routes](https://www.drupal.org/node/2122201) too.
Answer: Yes, you need to define a route for each path.
The order should not matter, it will put them all in the router table and then "order" them by the best match first.


Manipulate Array of pointer to 2D int Array

Question: I have this code :
int (*pieces) [10][10];

I want to dynamically allocate it into a function.
createPieces(int* (**pieces)){

*pieces = malloc(sizeof(int[10][10])*12); //12 = for example but it's a variable

}

And I try to initialize it like :
for (int i = 0; i < 12; ++i) {
        for (int x = 0; x < 10; ++x) {
            for (int y = 0; y < 10; ++y) {
                (pieces+i)[x][y] = 1;
            }
        }
    }

unfortunately that doesn't work. I get EXC_BAD_ACCESS (code=EXC_I386_GPFLT).
Any idea ?
Thank you !
Comment: An `int[][]` can  ***NOT*** be interpreted as an `int **`.
Comment: So how can I handle it ?
Comment: In your last question when you had a pointer to 2D array and passed the address so you could allocated storage for the pointer-to-pointer-to 2D array made sense. It seems you have gotten lost between then and now. If you have `int (*pieces) [10][10];` and pass the address to your `createPieces()` function would be `createPieces(int (**pieces)[10][10]){` where `int (**pieces)[10][10]` is a pointer-to-pointer-to `int[10][10]`. You can then allocate with `*pieces = malloc (sizeof **pieces * 12)` to allocate storage for 12 10x10 arrays accessible through `pieces` back in the caller.
Answer: I'm still not 100% clear on your intent, but I think I understand you want to start with your pointer-to-pointer-to int[10][10] array, pass the address to a function to allocate and then initialize the values for the storage of all twelve of the 10x10 blocks allocated. If that isn't correct, drop a comment below.
As mentioned in my comment to an earlier of your questions, any time you receive an EXC_BAD_ACCESS error, it is likely due to abusing a pointer and attempting to access a memory address that isn't a valid memory address for your program (like attempting to access an address way down in the system-reserved memory range). This usually occurs when you use a stored value as an address due to improperly dereferencing one-to-many times, etc..
Presuming that int (*pieces) [10][10]; isn't a global variable (which is should not be to begin with), you can declare your array and then pass to createpieces() for allocation as follows:
int main (void) {

    int (*pieces) [10][10];
    size_t n = 12;

    createpieces (&pieces, n);

    if (!pieces)        /* validate EVERY allocation, before using the block */
        return 1;

While I would recommend having createpieces() return a pointer to int (*)[10][10] so you need only pass the number of 10x10 arrays to allocate and assign the return to your pointer -- there isn't anything wrong with passing the address and allocating (which is the only way possible when the function is a callback, etc..)
Your createpieces() function could be written as:
void createpieces (int (**pieces)[10][10], size_t narrays)
{
    *pieces = malloc (sizeof **pieces * narrays);

    if (!*pieces)   /* validate the allocation */
        perror ("malloc-*pieces");
}

Now after your allocation, since it was a single-allocation, you have a contiguous block of memory, so if you want to initialize all values to 1, simply include string.h and then following your call to createpieces():
memset (pieces, 1, sizeof *pieces * n);

Much easier than nested loops (and more efficient), but by way of example, you can use nested loops if you like. The following initializes the elements of each 10x19 array to 1...100:
    for (size_t i = 0; i < n; i++)
        for (int j = 0; j < 10; j++)
            for (int k = 0; k < 10; k++)
                pieces[i][j][k] = j * 10 + k + 1;

(note: the type consistency in the loop variables)
Adding a short prnpieces() function to output all twelve arrays, you could do:
void prnpieces (int (*pieces)[10][10], size_t narrays)
{
    for (size_t i = 0; i < narrays; i++) {
        printf ("\narray: %2zu\n", i);
        for (int j = 0; j < 10; j++) {
            for (int k = 0; k < 10; k++)
                printf (" %3d", pieces[i][j][k]);
            putchar ('\n');
        }
    }
}

Putting it altogether, you would have:
#include <stdio.h>
#include <stdlib.h>

void createpieces (int (**pieces)[10][10], size_t narrays)
{
    *pieces = malloc (sizeof **pieces * narrays);

    if (!*pieces)   /* validate the allocation */
        perror ("malloc-*pieces");
}

void prnpieces (int (*pieces)[10][10], size_t narrays)
{
    for (size_t i = 0; i < narrays; i++) {
        printf ("\narray: %2zu\n", i);
        for (int j = 0; j < 10; j++) {
            for (int k = 0; k < 10; k++)
                printf (" %3d", pieces[i][j][k]);
            putchar ('\n');
        }
    }
}

int main (void) {

    int (*pieces) [10][10];
    size_t n = 12;

    createpieces (&pieces, n);

    if (!pieces)        /* validate EVERY allocation, before using the block */
        return 1;

    for (size_t i = 0; i < n; i++)
        for (int j = 0; j < 10; j++)
            for (int k = 0; k < 10; k++)
                pieces[i][j][k] = j * 10 + k + 1;

    prnpieces (pieces, n);
    free (pieces);
}

Example Use/Output
$ ./bin/ptr22d

array:  0
   1   2   3   4   5   6   7   8   9  10
  11  12  13  14  15  16  17  18  19  20
  21  22  23  24  25  26  27  28  29  30
  31  32  33  34  35  36  37  38  39  40
  41  42  43  44  45  46  47  48  49  50
  51  52  53  54  55  56  57  58  59  60
  61  62  63  64  65  66  67  68  69  70
  71  72  73  74  75  76  77  78  79  80
  81  82  83  84  85  86  87  88  89  90
  91  92  93  94  95  96  97  98  99 100

<snip>

array: 11
   1   2   3   4   5   6   7   8   9  10
  11  12  13  14  15  16  17  18  19  20
  21  22  23  24  25  26  27  28  29  30
  31  32  33  34  35  36  37  38  39  40
  41  42  43  44  45  46  47  48  49  50
  51  52  53  54  55  56  57  58  59  60
  61  62  63  64  65  66  67  68  69  70
  71  72  73  74  75  76  77  78  79  80
  81  82  83  84  85  86  87  88  89  90
  91  92  93  94  95  96  97  98  99 100

Memory Use/Error Check
In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.
It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.
For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.
$ valgrind ./bin/ptr22d
==12640== Memcheck, a memory error detector
==12640== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==12640== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==12640== Command: ./bin/ptr22d
==12640==

array:  0
   1   2   3   4   5   6   7   8   9  10
  11  12  13  14  15  16  17  18  19  20
  21  22  23  24  25  26  27  28  29  30
  31  32  33  34  35  36  37  38  39  40
  41  42  43  44  45  46  47  48  49  50
  51  52  53  54  55  56  57  58  59  60
  61  62  63  64  65  66  67  68  69  70
  71  72  73  74  75  76  77  78  79  80
  81  82  83  84  85  86  87  88  89  90
  91  92  93  94  95  96  97  98  99 100

<snip>
==12640==
==12640== HEAP SUMMARY:
==12640==     in use at exit: 0 bytes in 0 blocks
==12640==   total heap usage: 2 allocs, 2 frees, 5,824 bytes allocated
==12640==
==12640== All heap blocks were freed -- no leaks are possible
==12640==
==12640== For counts of detected and suppressed errors, rerun with: -v
==12640== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.
Look things over and let me know if you have further questions.
Answer: regarding:
int (*pieces) [10][10];

This is declaring a 10x10 array of pointers to integer
suggest:
in the caller:
...
int (*array[12])[10][10] = NULL;
array = createArray( 12 );
...

int * createArray( size_t instances )
{
    // get a pointer for 12 instances, each pointer initialized to NULL
    int *pieces = calloc( sizeof (int *), instances );
    // check for malloc failure here

    for( size_t i=0; i < instances; i++ )
    {
        // fill in a pointer to point to an array (10x10) of integers
        pieces[i] = malloc( sizeof( int ) *100 );
        // check for malloc failure here
    }

    // add code to initialize each 10x10 array instance here.

The above will result in an array of 12 pointers to integer.  Where each of those pointers will point to a 10x10 array of integers.
Note: used calloc() so if there is a memory allocation failure, makes it easy to 'clean up'.
    return pieces;
}


How can one implement PCA using gradient descent?

Question: I have to implement PCA using gradient descent and stop at convergence. I am not able to find the objective function. I know that

the aim of PCA is to reduce the $n$-dimensional matrix to $k$ dimensions (where $k < n$).
I need to find $k$ such that the ratio of the average squared projection error to total variance is $\leq 0.01$ (as we need to minimise average squared projection error and maximise the spread of data).

I am confused. Do we need to find $k$ or do we need to find the dimensionally reduced matrix as an output to gradient descent algorithm? Also, I need help with the objective function.
I am stuck since yesterday and am not able to move.
Comment: Why can't you just calculate the covariance matrix and then find its eigenvalues and eigenvectors? Who asked you to do this with an objective function?
Comment: Yes, it is possible. If anything it is also widely used when doing some more specialised PCA variant. E.g. the standard Sparse PCA by Zou et al. reformulates SPCA as a ridge/elastic-net regression problem. In fairness most solution follow an alternating minimization approach  because it is easy to ensure orthgonality that way but aside that, yeah, doable. Fun problem, +1!
Comment: This is an unusual way to look at PCA. Please give more context to the question.
Comment: PCA and "throwing away dimensions" are only closely related but not the same, i.e. k=n for now. What PCA seeks is the "principal components" or -just phrased differently- a linear transformation given in form of a matrix A such that $A^t C A$ becomes diagonal (where C is the covariance matrix), i.e. one obvious loss function would be to use the sum of square deviations of the off-diagonal terms of $A^t C A$ (because we want to make them zero!).
Comment: I have already implemented this with the standard method of finding Eigen values and Eigen vectors in my previous homework. This is a part of my new homework.
Comment: so i think more context is required, but I suspect you should be looking at reconstruction error as a cost function...this would project onto suspace spanned by k principal components. issue is the orthogonality.
Comment: Are you still interested in this question?
Answer: We can pose PCA as a variance maximization problem. These are some of the hints:
The objective is to find the directions in which the variance, $\Bbb E(\vec X \vec X^T)$, is maximum.
Let $\vec w$ denote the unit vector direction along which the variance is maximum. The variance along this direction is given by:
\begin{aligned} \sigma_{\vec{\omega}^{2}}^{2} &=\frac{1}{n} \sum_{i}(\overrightarrow{x_{i}} \cdot \vec{w})^{2} \\ &=\frac{1}{n}(\mathbf{x} \mathbf{w})^{T}(\mathbf{x} \mathbf{w}) \\ &=\frac{1}{n} \mathbf{w}^{T} \mathbf{x}^{T} \mathbf{x} \mathbf{w} \\ &=\mathbf{w}^{T} \frac{\mathbf{x}^{T} \mathbf{x}}{n} \mathbf{w} \\ &=\mathbf{w}^{T} \mathbf{v} \mathbf{w} \end{aligned}
We can take gradients wrt to $\vec w$ and set it zero to find the optimum values.
$$
\begin{aligned} \mathscr{L}(\mathbf{w}, \lambda) & \equiv \sigma_{\mathrm{w}}^{2}-\lambda\left(\mathbf{w}^{T} \mathbf{w}-1\right) \\ \frac{\partial L}{\partial \lambda} &=\mathbf{w}^{T} \mathbf{w}-1 \\ \frac{\partial L}{\partial \mathbf{w}} &=2 \mathbf{v} \mathbf{w}-2 \lambda \mathbf{w} \end{aligned}
$$
Here $\mathscr{L}$ is the modified objective with Lagrange multipliers (they are required to ensure $\vec w$ is a unit vector)
Setting the derivatives to zero, gives you an eigenvalue problem!
If one wants to solve it using Gradient Descent, because we have obtained the gradients here, we can solve minimizing $\mathscr{L}$ using gradient descent as well.
Update:
The above problem is concave:
Hessian is
$$ \begin{bmatrix}
0 & -2 \bf{w}^T \\
-2 \bf{w} & 2 \bf{v} - 2 \lambda \Bbb I
\end{bmatrix} $$
The determinant of this Hessian can be computed as $$
{\rm det}\left|\begin{matrix} A & B \\ C & D \end{matrix}\right| =
  {\rm det}|D|\,{\rm det} \left|A - BD^{-1} C\right| $$
The determinant is -ve as the expression $$- {\rm det}(2 \bf{v} - 2 \lambda \Bbb I) {\rm det} (2 \bf{w}^T (2 \bf{v} - 2 \lambda \Bbb I)^{-1} 2 \bf{w} ) $$ is always negative. Therefore, it will converge to a maxima.
Comment: @RodrigodeAzevedo The function is concave (updated the calculations). Therefore, our approach will converge to maxima.
Comment: What about convexity?
Comment: @RodrigodeAzevedo The $L_2$ norm is convex - therefore, $ \bf{w}^T \bf{w}$ is convex in $\bf{w}$. Using similar logic, it can be shown that $\bf{w}^T \bf{v} \bf{w}$ is convex. Let me know if I am missing something.
Comment: @honeybadger 's answer is wrong. Because a positive determinant doesn't guarantee semi positive definite.


Is the kernel of a direct sum of linear maps the direct sum of kernels?

Question: If we have two linear maps $\phi,\psi$ between finite dimensional vectors spaces, is it true that the kernel of
$$
\phi \oplus \psi = \begin{bmatrix} \phi & 0 \\ 0 & \psi \end{bmatrix}
$$
is equal to $\ker \phi \oplus \ker \psi$? If this is not true in general, is it at least true that if $\phi,\psi$ are injective (have trivial kernel) then $\phi \oplus \psi$ is injective?
Comment: Yes, it is $ ker(\phi) \oplus \ker (\psi)$
Answer: $(\phi \oplus \psi)(x,y)=(0,0)  \iff \phi(x)=0$ and $ \psi(y)=0 \iff (x,y) \in ker(\phi) \oplus \ker (\psi)  $.


Are all questions that are only primarily expat-related off topic?

Question: There were many concepts for the topic of the site, but it seems that people who see that site primarily for legal questions (visa, work permit etc.) have won and now everything that could possibly affect locals is likely to be closed as off topic.
The problem is, that many issues apply to both locals and expats, but almost only expats would ask them. Why?
Because those are things that are obvious to locals, because they learn it from childhood. They know where to buy X, they have opened bank account, registered for social security immediately after reaching adolthood, they know all strange legal regulations, for example that drinking beer in the park may be illegal.
But for expatriates, it's all black magic.
The reason I've supported that site on Area51 was, I was primarily interested in understanding that black magic.
So my question is, is the decision about such narrowing of the scope final and absolute? Is any question that possibly could apply to local automatically off-topic? Or there are some more common sense rules, for example the topics that apply to locals as well, but are primarily asked by expats, are allowed?
Please consider, that if 'anti-boat programming meme' was applied to Travel, you couldn't ask there about city tickets, or musea etc., because they apply as well?
Or you want to keep the scope as narrow as possible, and all 'settling down' questions should be redirected to another (new) site?
Comment: Presumably you are aware of: http://meta.expatriates.stackexchange.com/questions/42/can-questions-that-would-apply-equally-to-locals-be-on-topic. Do you think something has changed?
Comment: Can you give examples as well?
Answer: I don't really see any problems with closing too many questions. I'm usually doing two checks to determine whether something seems on or off topic:

The issue does affect most expats
The issue does not affect most locals

The hard thing is the second point: there are things that seem to only affect expats, but will actually also affect a lot of locals, especially ones who try to move around, or ones who just got into a new state of their lifes (like turning 18/21/finishing school, moving away from their parents, new job, etc.), or have issues that usually don't affect locals (like having a very bad credit rating)
I ususally try to keep questions open when I think that the problem affects expats even a tiny bit more than locals who get into a new life situation. But if the topic would also greatly affect locals (especially those type of locals who I mentioned before), then it's probably off topic. If not, I keep it open.
But, as I've said I don't really find issues with recent questions, so I've checked some recent closures:

https://expatriates.stackexchange.com/questions/5660/how-often-do-people-in-paris-get-billed-for-water-electricity Anyone trying to first pay for it's first flat's bills would be affected by this question. A slightly better, but still borderline question would be how to set up your first service provider. An on-topic question (at least from my perspective) would be: "How to set up an account with the water provider, if I don't have 3 years history of previous addresses in the UK". Now this question is a bit more fine (at least for my standards): locals will most likely have at least 3 years of residence records, even if they just moved to the other end of the country, or are bankrupt. Expats however usually don't have this, which might cause real problems, if the provider requires this data.
https://expatriates.stackexchange.com/questions/5649/cost-of-living-in-munich-and-heidelberg Someone moving from, for example from Hamburg to Bavaria would also ask this question, so it doesn't fit with the "more like for expats" part. But even if it would fit, it's an opinionated question, that wouldn't really get quality answers.
https://expatriates.stackexchange.com/questions/5625/how-can-my-9mth-baby-and-i-stay-with-uk-citizen-husband-i-uk The question is expat related, but it's badly worded, that's why it was closed as unclear, and not as off-topic
https://expatriates.stackexchange.com/questions/5620/how-to-search-a-persons-contact-number-in-india I don't think only expats want to find contact information of people.
https://expatriates.stackexchange.com/questions/5627/job-offer-in-abu-dhabi opinion based, but it actually has a duplicate as well.

I would also include this question which I reopened because it did fit the criteria: Where I can cash a paycheck in London without a bank account (you can find my reasonings in acomment). On the other hand the question was very badly worded (it still is), if it would be something like "I got my first paycheck in the UK, and I would like to cash it in. What's the cheapest way to do it" would be better, indicating why exactly you don't have a bank account.


Normalize output scores for binary classification

Question: I am handling a binary classification problem on an imbalanced dataset.
The goal is to create a system able to insert the returned score (probability to be in the positive class) in a bins between 1 and 10, where 1 means low probability to be in the positive class and 10 high prob.
The main problem is that I only have the training dataset, so I don't know any values in the test set. Moreover, the predictions will be done one by one, so I cannot analyze the whole test scores.
I tried many models, but in particular I use tree-based models (such as XG-Boost, RF). In these cases, considering also the imbalanced dataset, the output scores are in a very small range, much smaller than [0, 1]. The scores are necessary since I don't want to classify the instances directly into the 0-1 class, but I want to analyze the scores.
How should I build a method able to find the different thresholds in order to create the 10 classes?
Comment: It sounds like your targets are ordinal. You can use an ordinal loss function. For example: https://en.wikipedia.org/wiki/Ordered_logit Although one must wonder why the targets have been pre-processed into this 1-10 scale instead of working with the class labels directly.
Comment: the target is always binary (0 or 1). I don't want to just put a label for each record, but I want to analyze the returned scores, in order to deeper understand the confidence of the prediction. I want to create the 10 classes in order to divide the output scores into these 10 classes to easily analyze
Comment: In your question, you write "How should I build a method able to find the different thresholds in order to create the 10 classes?" But there's no single, correct answer to this question. One method would divide $[0,1]$ into ten equal-sized bins. Another would examine the model predictions and then choose bins based on the deciles of the predictions. Another might be uniform on the logarithmic scale. In other words, how will you know that you've chosen a good way to make bins?
Comment: You are right, there are many possible solutions. To be more precise, I want a method able to equally distribute the test observation into the 10 bins. A vanilla solution should obviously be to create the 10 bins like 0->[0, 0.1], 1->[0.1, 0.2] and so on. Anyway in this case, it is possible that all the test observations will be categorized into one single bin according to their score. So, I am looking for a method able to build the 10 bins in such a way that the test scores will fall into all the bins, not just one.
Comment: It sounds like you can use the deciles of some test set as the bins. Another set of data drawn from the same distribution will be more-or-less uniformly allocated to the bins (it won't be exact because of sampling variance).
Comment: Yes, that's a good idea. The problem is that by this way I have to put aside a percentage of my training data and it could be a problem. I would try to train the model on the whole training set, and then predict the training set itself. Obviously it is not a good practice in general, due to overfitting. However, in my case I am not interested on who is predicted as 1 and who as 0, but just in the score distribution. What do you think about it?
Comment: I think you'll have to put aside a percentage of your training data.
Comment: What about $(0,0.1)$, $(0.1,0.2)$, etc?
Comment: no, it is not possible, since the scores are in a range between 0 and 1, but in most of the case the range is much smaller (eg. 0 - 0.05) and so if I use some a-priori partition I will probably fall in a case where all the records are in the same folder.
Answer: First, the fact that your outputs are in only the very low end of $[0,1]$ strikes me as a feature, not a bug, of the outputs of a probability predictor in an imbalanced setting. It might typically be the case that a minority-class event is unlikely, even if the probability is higher than the prior probability (class ratio), as I discuss here. If that is the case, then, yes, the predicted probabilities should be at the low end of $[0,1]$.
You want to then scale $[0,1]$ to $[1,10]$. That sounds like a job for $y=9x+1$: first multiply the value in $[0,1]$ by $9$, and then add $1$. If you are determined to have only the integers, you could consider rounding (though I do not see any statistical advantage to doing so). Yes, this approach will have a lot of values down towards one, but think about what it means if you manage to get a seven or a ten!
Answer: Well, if your models outputs probabilities for the positive class and your decision boundary is 0.5, i.e. p < 0.5 -> class 0 and p >= 0.5 -> class 1 then you can discretize the probability interval from $[0.5, 1.)$ into 10 bins and assign a class for each interval, e.g. $[0.5,0.55)$ => class 1, $[0.55,0.6)$ => class 2, ...
Now each class represents some confidence about the positive prediction.
Comment: This is not well conceptualized.  Keep probabilities as probabilities.  And use proper nomenclature.  This is not a classification problem.  This is a probability modeling problem.
Comment: Well, my decision boundary is not 0.5. Since I am working in an imbalanced scenario, the output probabilities for the positive class are usually much smaller than 0.5 (in particular for the tree-based classifiers), since they move around the *conversion rate* of the target column. Analyzing the problem from another point of view, it's as I have to set my threshold.


What is the best way to update object array value in React

Question: My React state:
//...
this.state = {
    mylist: [
        {
            "id": 0,
            "trueorfalse": false
        },
        {
            "id": 1,
            "trueorfalse": false
        }
    ]
}
//...

I am trying to update the trueorfalse value based on the id
Here is what I did so far but didn't work:
var idnum = e.target.id.toString().split("_")[1] //getting the id via an element id (0 or 1 in this case)
var TorF = true
if (type === 1) {
    this.setState({
        mylist: this.state.mylist.map(el => (el.id === idnum ? Object.assign({}, el, { TorF }) : el))
    })
}

I really want to make it dynamic so the trueorfase will be opposite of what it is now:
var idnum = e.target.id.toString().split("_")[1] //getting the id via an element id (0 or 1 in this case)
if (type === 1) {
    this.setState({
        mylist: this.state.mylist.map(el => (el.id === idnum ? Object.assign({}, el, { /* if already true set to false or vice versa */ }) : el))
    })
}

How can I update my code to have the dynamicity shown in the second example (if possible), otherwise the first example would do just fine
Comment: You could negate the existing property like `!el.trueorfalse`
Comment: `{ !el.trueorfalse }` didn't work, it instead gave an error
Comment: Possible duplicate of [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react)
Answer: Another solution using map:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mylist: [
        {
          id: 0,
          trueorfalse: false
        },
        {
          id: 1,
          trueorfalse: true
        }
      ]
    };
  }
  toggleBoolean = () => {
    const ID = Number(this.state.selectedID);
    this.setState(prevState => ({
      mylist: prevState.mylist.map(item => {
        if (item.id === ID) {
          return { ...item, trueorfalse: !item.trueorfalse };
        } else {
          return item;
        }
      })
    }));
  };
  render() {
    return (

{`State values: ${JSON.stringify(this.state.mylist)}`}

        <button onClick={this.toggleBoolean}>Change true/false values</button>
        Insert ID:
        <input
          type="number"
          onChange={event => this.setState({ selectedID: event.target.value })}
        />

    );
  }
}

Comment: @Si8 I think the performance would be pretty similar because both copy/create a new array and iterate over every element of the existing array. Either way though I think choosing based on efficiency at this point would be micro-optimizing; just pick which way makes more sense in your head.
Comment: Oh this also works. Which would be more efficient to use, or it doesn't matter.
Comment: Thanks @Michael for the clarification.
Answer: I think the following code would accomplish your second question.
var idnum = e.target.id.toString().split("_")[1]
let newList = Array.from(this.state.mylist) //create new array so we don't modify state directly
if (type === 1) {
    let objToUpdate = newList.find((el) =>  el.id === idnum) // grab first element with matching id
    objToUpdate.trueorfalse = !objToUpdate.trueorfalse
    this.setState( { mylist: newList } )
}

Comment: @JossClassey Because I changed `objToUpdate`, `newList` is also changed. It's like the following code: `a = ls[3]; a.x = 5` <- You just changed the third element of `ls`.
Comment: Should the last list be `mylist: objToUpdate`?
Comment: @Si8 no, `objToUpdate` is just a single element from `updatedList`
Comment: You beat me to fixing the `setState` method.
Comment: Btw this fixed my issue, so much simpler than I imagined! Thanks.
Comment: @Michael You didn't update `newList` with the updated object.
Comment: Ahh, I thought `find()` would return a new object, but no it returns a reference to the original array. Very interesting.
Comment: I was a little confused too but then realized that it's not s new object but a reference to the existing one.


How to add backspace in a Linux terminal command?

Question: I need to execute the following command to ssh into a device on a network whose credentials have been saved.
ans = subprocess.check_output(['sudo','sshpass','-p',iplist[index][3],'ssh',iplist[index][2],'@',iplist[index][2]])

This is executed on Ubuntu in a Python environment.
I want to actually execute-
sudo sshpass -p password username@hostname

It is quite possible that there is a space before and afer '@'.
How do I eliminate that?
Comment: It's not so much that there's a space, but that they're explicitly passed as two separate arguments: The argument list on UNIX (and so across all programming languages on that OS) is really a list of separate C strings; when you pass one string with spaces to the shell, the shell splits it up into individual strings before starting the program being called. Passing an array to `subprocess.Popen()`, you're forming that list yourself rather than generating a string and letting it be split elsewhere -- giving you more control.
Answer: Concatenate them to one argument
ans = subprocess.check_output(['sudo', 'sshpass', '-p', iplist[index][3], 'ssh', iplist[index][2] + '@' + iplist[index][2]])

Answer: You need to merge iplist[index][2],'@',iplist[index][2] into a single item in the list:
ans = subprocess.check_output(['sudo','sshpass','-p', iplist[index][3],'ssh','{}@{}'.format(iplist[index][2], iplist[index][2])])


Struggling to remove server from Rack

Question: currently racking my brain at this one, i'm struggling to remove the below server out of the rack, I haven't come across this type of rail before, usually I can pull a server out and there will be clips which once pressed I can lift it up.
Can anyone spot the obvious thing i'm missing?
Comment: It looks like you push the spring clip on the inner rail and then pull the server out.
Answer: Push in the red circled area. This will move the tab in the blue circled area clear of the stop, and you can then pull the server out.
Comment: Not to the OP, specifically: If not experienced with these kinds of rail systems, it is best not to work alone at first - dropping a 2U server on yourself, or losing your balance, or making a sparsely populated rack topple are all experiences best enjoyed in company.
Comment: @rackandboneman you're right - its a two person job.  Or ask your DC for their platform lift.  Most datacenters have something that looks like this : https://www.northerntool.com/images/product/2000x2000/445/44502_2000x2000.jpg  or the flash ones might have  http://alum-a-lift.com/sitefiles/wp-content/uploads/2014/05/21742-Side-to-Side-Roller-Deck-Lift-for-Servers.jpg   It only takes dropping one server to make these things worth the cost, plus avoiding the back strain.  Comment cos not an answer.
Comment: This is the right answer. And it's pretty common amongst server brands.
Comment: You might clarify that by "pulling the server out" you mean "keep pulling the server horizontally away from the rack until it completely slides out of the rails." The asker is expecting to lift the server up off the rails, as is common with Dell 2U Rapid Rails.
Comment: Hi all, apologies for the delay in responding to this - attempted the above with my manager and we couldn't get it to pull out even though the tabs were released on both sides, - we believe now something is causing it to Jam which is why i was so stumped, thanks for all the help!
Comment: It's designed this way at least partly because your hands are then near the center of mass for the server as you unlock it, giving you a more stable grip and applying less torque to your hands and wrists.
Comment: @ToddWilcox based on my experience with them I absolutely detest those "drop it on" rails.  Last thing I want to be doing when handling a big heavy server is trying to line up two flimsy pieces of metal with 4 mating pegs.
Comment: also @rackandboneman i was close to kicking it out - it's a dead server which will be destroyed, it's a nice enclosure though so we plan on keeping it haha

Struggling to remove server from Rack


Proving that a matrix transformation maps the zero vector in $\mathbb{R}^n$ into the zero vector in $\mathbb{R}^m$

Question: Suppose $T: \mathbb{R}^n \rightarrow \mathbb{R}^m$ is a matrix transformation. I want to show that
$$T(\vec{0}) = \vec{0}$$
I was told as a hint that we need to use the linearity conditions to make such a deduction, but I think that might be unnecessary, or I may be misunderstanding the concept of matrix transformations altogether.
Since $T$ is a matrix transformation, then for every $\vec{x} \in \mathbb{R}^n$ there exists a unique $m \times n$ matrix $A$ such that
$$T(\vec{x}) = A \cdot \vec{x}$$
If we let $\vec{x} = \vec{0}$, where this zero vector has dimensions $n \times 1$, then
$$T(\vec{0}) = A \cdot \vec{0} = \vec{0}$$
where the $\vec{0}$ on the right hand side of the equation is an $m \times 1$ vector.
Hence, every transformation maps the zero vector in $\mathbb{R}^n$ to the zero vector in $\mathbb{R}^m$.
Are there any problems with the proof?
Answer: It seems that you've simply restated the question. You are asked to show that $T(0)=0$ where $T$ is given by $T(x)=Ax$. To do so you must justify why $A0=0$.
You have several options, but the best by far is to use the linearity of $T$.
Note that
$$
T(0)=T(0-0)=T(0)-T(0)=0
$$
and you're done!
This is a great example of why abstraction is useful.
Comment: @BenedictVoltaire This question is asking you to verify that $A0=0$. Simply saying that this is a "well established truth" is circular. Note that AlexWertheim's comment gives direct justification why $A0=0$.
Comment: @BenedictVoltaire Later you'll learn about a more general concept called *linear transformations*. Every linear transformation $T$ satisfies $T(0)=0$ but is not necessarily of the form $T(x)=Ax$ for a matrix $A$. The only way to prove $T(0)=0$ is using the linearity conditions. So, not only is the proof I offer much simpler than writing the details your book provides, but it is also more general.
Comment: Heh, was in the process of writing an answer that was very nearly the same as this, but you were faster :). The OP can also prove their claim by noting that the entries of $A \cdot \vec{0}$ are given by the dot product of each of the rows of $A$ with $\vec{0}$, and hence are all $0$, but I agree that the abstract way is better.
Comment: @Brian_Fitzpatrix I guess I'm a little confused as to why it must be justified that $A \vec{0} = \vec{0}$ since this is a well established truth concerning matrix multiplication. I'm new to the concept of matrix transformations, but bear with me. To me, a given matrix transformation on $\vec{x}$ is synonymous with the matrix multiplication $A \vec{x}$ where $A$ is the standard matrix. Why is it that, in this case, the linearity conditions are what are needed for this proof? Also, in your proof, how do you know that $T(\vec{0}) = \vec{0}$?
Comment: Alright, but in the same section of the problem, there is a theorem which says, "For every matrix $A$, the matrix transformation $T_A:\mathbb{R}^n \rightarrow \mathbb{R}^m$ has the property $T_A(\vec{0}) = \vec{0}$," and the proof refers to a previous theorem regarding matrix multiplication that $A \vec{0} = \vec{0}$. It seems that this problem is asking for another proof using the linearity conditions, but I don't see why such a proof is necessary.


Heatmap using ggplot2 in r

Question: My Data looks like this:
data1 <- read.table(text = "District    Block   IE       FE     AOE     CLE      CS
A             A1    4.87    17.54   13.85   9.01    45.27
                 B             B1    8.19    20.83   14.59   7.04    50.65
                 C             C1    8.71    19.16   16.54   8.24    52.65
                 D             D1    2.43    11.77   11.51   6.96    32.67
                 E             E1    6.85    13.54   14.54   5.7     40.63
                 F             F1    7.02    19.96   13.96   3.82    44.76
                 G             G1    2.55    11.64   8.74    5.06    27.99
                 H             H1    9.81    20.2    12.62   5.95    48.58
                 I             I1    6.56    15.49   12.32   8.08    42.45
                 J             J1    9.47    22.86   25      22.73   80.06
                 K             K1    10.2    20.18   20.14   20.06   70.58
                 L             L1    9.52    14.86   16.95   18.23   59.56", header = TRUE)

I have created data matrix from the dataframe.My initial code looks like this
row.names(data1)<-data1$Column1

data1<-select(data1,-c(1))
data1<-data.matrix()
data1_heatmap<-heatmap(data1,Rowv = NA,Colv = NA,col=heat.colors(256),scale = "none",margins = c(12,3))

Whenever I am using the above code,it plots for the whole sheet.
I have 2 issues:

I need to show the cell values which are present in the data matrix.
Also i need to specify a color range in each column from IE to CS.For example,in IE column less the 4.87 is red,6.56 to 6.85 is orange and green for greater than 8.17.So basically user defined range for each column.
Comment: What does this have to do with `ggplot2`?
Answer: Try this with ggplot2 (starting with the original data1):
library(ggplot2)
library(reshape2)
row.names(data1)<-data1$Column1
data1<-select(data1,-c(1))
data1 <- melt(data1, id='Block')
data1$value <- cut(data1$value,breaks = c(-Inf,4.87, 6.56, 6.58, 8.17, 14, 19, 21, Inf),right = FALSE) # bin IE variable
ggplot(data =  data1, aes(x = Block, y = variable)) +
  geom_tile(aes(fill = value), colour = "white") +
  scale_fill_brewer(palette = "PRGn")

Heatmap using ggplot2 in r


void function not returning

Question: I am having an issue returning out of  a void function.
I can see the output printed when the name (input) is found, which returns true. The void function should return if the lambda (or name_checker) function returns true, but it still implementing remaining part of the function.
Comment: If the node is a `ControlNode`, the function will not return until it has iterated over, and recursed into, all the children. It is common to return a value that indicates success so you can avoid pointless recursions.
Comment: How do you know it's still implementing the rest of the function? Because, clearly, you are mistaken about that. Maybe you are confusing the rest of the function, with remaining recursive calls to your function?
Answer: Change your function to return a bool, use that return value to quit immediately that you find something. Something like this
bool findTreeNodeRecursively(unsigned indent, const TreeNode* node, const std::function<bool(const TreeNode*)>& name_checker){

    for (unsigned i = 0; i < indent; i++)
    {
        std::cout << "   ";
    }
    if (!node)
    {
        std::cout << "!nullptr!" << std::endl;
        return false;
    }

    indent++;

    if(name_checker(node) == true){
        return true;
    }

    if (auto control = dynamic_cast<const ControlNode*>(node))
    {
        for (const auto& child : control->children())
        {
            if (findTreeNodeRecursively(indent, child, name_checker))
                return true;
        }
    }
    else if (auto decorator = dynamic_cast<const DecoratorNode*>(node))
    {
        if (findTreeNodeRecursively(indent, decorator->child(), name_checker))
            return true;
    }
    return false;
}

In a recursive function return only returns from one recursive call, it doesn't return all the way back to the top. If that's what you want you have to program it.
Comment: that works! thank you very much for your explanation and help!

void function not returning