text:
Q: What is a difference between table distribution and table partition in sql? I am still struggling with identifying how the concept of table distribution in azure sql data warehouse differs from concept of table partition in Sql server?
Definition of both seems to be achieving same results.

A: Azure DW has up to 60 computing nodes as part of it's MPP architecture. When you store a table on Azure DW you are storing it amongst those nodes. Your tables data is distributed across these nodes (using Hash distribution or Round Robin distribution depending on your needs). You can also choose to have your table (preferably a very small table) replicated across these nodes.

That is distribution. Each node has its own distinct records that only that node worries about when interacting with the data. It's a shared-nothing architecture.

Partitioning is completely divorced from this concept of distribution. When we partition a table we decide which rows belong into which partitions based on some scheme (like partitioning an order table by the order.create_date for instance). A chunk of records for each create_date then gets stored in its own table separate from any other create_date set of records (invisibly behind the scenes).
Partitioning is nice because you may find that you only want to select 10 days worth of orders from your table, so you only need to read against 10 smaller tables, instead of having to scan across years of order data to find the 10 days you are after.
Here's an example from the Microsoft website where horizontal partitioning is done on the name column with two "shards" based on the names alphabetical order:

Table distribution is a concept that is only available on MPP type RDBMSs like Azure DW or Teradata. It's easiest to think of it as a hardware concept that is somewhat divorced (to a degree) from the data. Azure gives you a lot of control here where other MPP databases base distribution on primary keys. Partitioning is available on nearly every RDBMS (MPP or not) and it's easiest to think of it as a storage/software concept that is defined by and dependent on the data in the table.
In the end, they do both work to solve the same problem. But... nearly every RDBMS concept (indexing, disk storage, optimization, partition, distribution, etc) are there to solve the same problem. Namely: "How do I get the exact data I need out as quickly as possible?" When you combine these concepts together to match your data retrieval needs you make your SQL requests CRAZY fast even against monstrously huge data.

A: Just for fun, allow me to explain it with an analogy.
Suppose there exists one massive book about all history of the world. It has the size of a 42 story building.
Now what if the librarian splits that book into 1 book per year.  That makes it much easier to find all information you need for some specific years. Because you can just keep the other books on the shelves.
A small book is easier to carry too.
That's what table partitioning is about.  (Reference: Data Partitioning in Azure)
Keeping chunks of data together, based on a key (or set of columns) that is usefull for the majority of the queries and has a nice average distribution.
This can reduce IO because only the relevant chunks need to be accessed.
Now what if the chief librarian unbinds that book. And sends sets of pages to many different libraries.
When we then need certain information, we ask each library to send us copies of the pages we need.
Even better, those librarians could already summarize the information of their pages and then just send only their summaries to one  library that collects them for you.
That's what the table distribution is about.  (Reference: Table Distribution Guidance in Azure)
To spread out the data over the different nodes.

A: Conceptually they are the same. The basic idea is that the data will be split across multiple stores. However, the implementation is radically different. Under the covers, Azure SQL Data Warehouse manages and maintains the 70 databases that each table you define is created within. You do nothing beyond define the keys. The distribution is taken care of. For partitioning, you have to define and maintain pretty much everything to get it to work. There's even more to it, but you get the core idea. These are different processes and mechanisms that are, at the macro level, arriving at a similar end point. However, the processes these things support are very different. The distribution assists in increased performance while partitioning is primarily a means of improved data management (rolling windows, etc.). These are very different things with different intents even as they are similar.


text:
Q: IntelliJ adding additional jvm parameters but where? So this is a web application the jvm running the applications encoding must be Cp1252 to make the web - app work fine.
In .bash_profile when I add:
export MAVEN_OPTS="-Dfile.encoding=Cp1252"

and open up terminal and start jetty with:
mvn org.mortbay.jetty:maven-jetty-plugin:6.1.22:run

everything will be fine. How do I know? There is a page which checks the encoding in the web app itself and it shows:
Encoding JVM: windows-1252 / Encoding Application: Cp1252

Now when I have the same jvm parameters in IntelliJ, I see this is added to my parameters:
-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 12.app/bin" -Dfile.encoding=UTF-8

and this breaks everything.
How can I edit the parameters IntelliJ adds to maven runner?

A: You can simply create maven configuration with custom parameters. Check http://www.jetbrains.com/idea/webhelp/creating-maven-run-debug-configuration.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aplicar responsividade
Como podemos ver na primeira imagem com a telá estendida está certo porem quando eu redimensiono a tela as tabelas saem da organização, podem me ajudar a manter as tabelas redimensionando de acordo com o tamanho da tela?

{
html {
    margin: 0;
    height: 100px;
}

body {
    font-family: "Verdana",Times,serif;
    background: #f8f8f8;
    height: 55em;
    margin: 0.5em;
    font-size: 15px;
}

textarea {
    width: 90%;
    height: 100%;
    margin-left: 20%;
    font-family: "Verdana", Times, serif;
    font-size: 100px;
}

img {
    border-radius: 10px;
    padding: 7px;
    max-width: 100px;
    max-height: 70px;
    width: auto;
    height: auto;
    margin-left: 3.8%;
}

.header {
    width: 100%;
    background: #ffffff;
    height: 4.5em;
    box-shadow: 1px 1px 1px rgba(100, 100, 100, 0.49);
    margin: auto;
}

.menu {
    border-radius: 5px;
    width: 100%;
    background: rgb(00, 87, 147);
    height: 2.5em;
    margin-bottom: 1em;
    box-shadow: 1px 3px 5px 1px rgba(0,0,0,0.37);
    color: #d5d1d1;
}

#usuario {
    line-height: 3.5em;
    margin-right: 7em;
    font-size: 0.8em;
    width: 10%;
    height: 100%;
    float: right;
    display: inline-flex;
}

.menu ul {
    padding: 2px;
    margin-bottom: 0px;
    margin-left: 6.3%;
    margin-top: 0px;
    float: left;
}

    .menu ul li {
        display: inline-flex;
        color: white;
    }

        .menu ul li a {
            padding: 8px 20px;
            color: #d5d1d1;
            text-decoration: none;
        }

            .menu ul li a:hover {
                color: #fff;
                background: #4698ca;
                border-top-color: #5db1e0 !important;
                border-left-color: #5db1e0;
            }

.content {
    background: #ffffff;
    width: 100%;
    height: 46em;
    margin: 0.5em;
    box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.5);
}

.content2 {
    background: #ffffff;
    width: 100%;
    height: 1em;
    margin: 1em auto;
    box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.5);
}

.footer {
    width: 98%;
    background: #ffffff;
    height: 13%;
    margin-left: 1em;
    margin-bottom: 0em;
    box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.5);
    color: #333333;
}

.button {
    background-color: rgb(00, 87, 147);
    border-radius: 4px;
    color: white;
    padding: 5px 24px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    width: 173px;
}

.button2 {
    background-color: rgb(00, 87, 147);
    border-radius: 4px;
    color: white;
    padding: 5px 24px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    width: 237px;
}

#buttonConsulta {
    background-color: rgb(00, 87, 147);
    border-radius: 4px;
    color: white;
    padding: 5px 24px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    width: 237px;
    margin-left: 5%;
}

    #buttonConsulta:hover {
        color: #fff;
        background: #4698ca;
        border-top-color: #5db1e0 !important;
        border-left-color: #5db1e0;
    }

.button:hover {
    color: #fff;
    background: #4698ca;
    border-top-color: #5db1e0 !important;
    border-left-color: #5db1e0;
}

.button2:hover {
    color: #fff;
    background: #4698ca;
    border-top-color: #5db1e0 !important;
    border-left-color: #5db1e0;
}

.campos-texto {
    border: 1px solid rgba(100, 100, 100, 0.49);
    width: 165px;
    color: #333333;
    padding: 3px;
    margin-right: 4px;
    margin-bottom: 8px;
    font-family: tahoma, arial, sans-serif;
    margin-top: 5px;
}

.campos-texto2 {
    border: 1px solid rgba(100, 100, 100, 0.49);
    width: 230px;
    color: #333333;
    padding: 3px;
    margin-right: 4px;
    margin-bottom: 8px;
    font-family: tahoma, arial, sans-serif;
    margin-top: 5px;
}

.editor-label {
    margin-top: 10px;
}

.form {
    position: relative;
    display: inline-block;
    margin-top: 60px;
    margin-left: 80px;
    float: left;
}

.form2 {
    margin-top: 30px;
    margin-left: 80px;
}

p {
    font-family: "Verdana", Times, serif;
    font-size: 20px;
}

.conteudo {
    height: 47%;
    width: 75%;
    margin-left: 9%;
    background: red;
}

.configuracoes {
    margin-left: 70px;
    font-size: small;
}

textarea {
    resize: none;
}

.form fieldset {
    float: left;
    border: none;
}

}
me descupem a ignorância, peço ajuda e desde já agradeço.
aqui o restante do codigo:
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPageHome.cshtml";

var grid1 = new WebGrid(Model.inciAnalista, canPage: true, rowsPerPage: 7, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent2");
var grid2 = new WebGrid(Model.gmudAnalista, canPage: true, rowsPerPage: 7, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent2");
var grid3 = new WebGrid(Model.demandaAnalista, canPage: true, rowsPerPage: 7, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent2");
var grid4 = new WebGrid(Model.problemaAnalista, canPage: true, rowsPerPage: 7, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent2");
var grid5 = new WebGrid(Model.totalAnalista, canPage: true, rowsPerPage: 7, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent2");
var grid6 = new WebGrid(Model.totalAnalista, canPage: true, rowsPerPage: 7, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent2");
var grid7 = new WebGrid(Model.totalAnalista, canPage: true, rowsPerPage: 7, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent2");

int r1, r2, r3, r4, r5, e1, e2, e3, e4, e5, a1, a2, a3, a4, a5, h1, h2, h3, h4, h5, f1, f2, f3, f4, f5, l1, l2, l3, l4, l5, c1, c2, c3, c4, c5;
r1 = Model.totalAnalista[0].umMes;
r2 = Model.totalAnalista[0].duasSemanas;
r3 = Model.totalAnalista[0].noPrazo;
r4 = Model.totalAnalista[0].planejada;
r5 = Model.totalAnalista[0].incidente;

e1 = Model.totalAnalista[1].umMes;
e2 = Model.totalAnalista[1].duasSemanas;
e3 = Model.totalAnalista[1].noPrazo;
e4 = Model.totalAnalista[1].planejada;
e5 = Model.totalAnalista[1].incidente;

a1 = Model.totalAnalista[2].umMes;
a2 = Model.totalAnalista[2].duasSemanas;
a3 = Model.totalAnalista[2].noPrazo;
a4 = Model.totalAnalista[2].planejada;
a5 = Model.totalAnalista[2].incidente;

h1 = Model.totalAnalista[3].umMes;
h2 = Model.totalAnalista[3].duasSemanas;
h3 = Model.totalAnalista[3].noPrazo;
h4 = Model.totalAnalista[3].planejada;
h5 = Model.totalAnalista[3].incidente;

f1 = Model.totalAnalista[4].umMes;
f2 = Model.totalAnalista[4].duasSemanas;
f3 = Model.totalAnalista[4].noPrazo;
f4 = Model.totalAnalista[4].planejada;
f5 = Model.totalAnalista[4].incidente;

l1 = Model.totalAnalista[5].umMes;
l2 = Model.totalAnalista[5].duasSemanas;
l3 = Model.totalAnalista[5].noPrazo;
l4 = Model.totalAnalista[5].planejada;
l5 = Model.totalAnalista[5].incidente;

c1 = Model.totalAnalista[6].umMes;
c2 = Model.totalAnalista[6].duasSemanas;
c3 = Model.totalAnalista[6].noPrazo;
c4 = Model.totalAnalista[6].planejada;
c5 = Model.totalAnalista[6].incidente;
}

o restante:
{
(document).ready(function () { $("#gridContent tbody tr").each(function (i, row) { var $actualRow = $(row); if ($actualRow.find('td').eq(3).text() > 0 && $actualRow.find('td').eq(4).text() 0 && $actualRow.find('td').eq(3).text()

    .webGrid {
        margin: 20px;
        margin-left: 110px;
        border-collapse: collapse;
        width: 40%;
        background-color: #ffffff;
        text-align: left;
        font-size: 13px;
        float: left;
    }

    .webGrid2 {
        margin: 10px;
        margin-left: 990px;
        border-collapse: collapse;
        width: 30%;
        background-color: #ffffff;
        text-align: left;
        font-size: 13px;
    }

    .headerGrid a {
        color: rgb(00, 87, 147);
        text-decoration: none;
    }

    .comentario {
        max-width: 200px;
        white-space: nowrap;
        overflow: hidden;
    }

    .grafico {
        float: right;
    }

    #chartContainer,
    #chartContainer2 {
        display: inline-block;
        margin: 0px;
        float: left;
        margin-left: 10%;
    }

    #chartContainer3,
    #chartContainer4 {
        display: inline-block;
        margin: 0px;
        float: left;
        margin-left: 10%;
    }

    #chartContainer5 {
        display: inline-block;
        margin: 0px;
        float: left;
        margin-left: 10%;
    }

    #chartContainer6,
    #chartContainer7 {
        display: inline-block;
        margin: 0px;
        float: left;
        margin-left: 10%;
    }

    @*@foreach (var item in Model.totalAnalista) {}

    *@ @grid1.GetHtml(tableStyle: "webGrid", headerStyle: "headerGrid", alternatingRowStyle: "alt", selectedRowStyle: "select", columns: grid1.Columns( grid1.Column("analista", " Analista"), grid1.Column("incidente", "Incidentes"), grid1.Column("noPrazo", "No Prazo"), grid1.Column("duasSemanas", "Mais De 2 Semanas"), grid1.Column("umMes", "Mais De 1 Mês"), grid1.Column("planejada", "Planejada"))) @grid2.GetHtml(tableStyle: "webGrid", headerStyle: "headerGrid", alternatingRowStyle: "alt", selectedRowStyle: "select", columns: grid2.Columns( grid2.Column("analista", " Analista"), grid2.Column("incidente", "G.M.U.Ds."), grid2.Column("noPrazo", "No Prazo"), grid2.Column("duasSemanas", "Mais De 2 Semanas"), grid2.Column("umMes", "Mais De 1 Mês"), grid2.Column("Planejada"))) @grid3.GetHtml(tableStyle: "webGrid", headerStyle: "headerGrid", alternatingRowStyle: "alt", selectedRowStyle: "select", columns: grid3.Columns( grid3.Column("analista", " Analista"), grid3.Column("incidente", "Demandas"), grid3.Column("noPrazo", "No Prazo"), grid3.Column("duasSemanas", "Mais De 2 Semanas"), grid3.Column("umMes", "Mais De 1 Mês"), grid3.Column("planejada", "Planejada"))) @grid4.GetHtml(tableStyle: "webGrid", headerStyle: "headerGrid", alternatingRowStyle: "alt", selectedRowStyle: "select", columns: grid4.Columns( grid4.Column("analista", " Analista"), grid4.Column("incidente", "Problemas"), grid4.Column("noPrazo", "No Prazo"), grid4.Column("duasSemanas", "Mais De 2 Semanas"), grid4.Column("umMes", "Mais De 1 Mês"), grid4.Column("planejada", "Planejada"))) @grid5.GetHtml(tableStyle: "webGrid2", headerStyle: "headerGrid", alternatingRowStyle: "alt", selectedRowStyle: "select", columns: grid5.Columns( grid5.Column("analista", " Analista"), grid5.Column("incidente", "Totalidade"), grid5.Column("noPrazo", "No Prazo"), grid5.Column("duasSemanas", "Mais De 2 Semanas"), grid5.Column("umMes", "Mais De 1 Mês"), grid5.Column("planejada", "Planejada"))) var randomScalingFactor=function () {
        return Math.round(Math.random() * 100);
    }

    ;
    var config= {
        type: 'pie',
        data: {
            datasets: [ {
                data: [ @r1, @r2, @r3, @r4 ], backgroundColor: [ "#de4e3a", window.chartColors.yellow, window.chartColors.blue, window.chartColors.green, ], label: "Romulo Cano"
            }
            ],
            labels: [ "1 Mês +",
            "2 Semanas +",
            "No Prazo",
            "Planejada"],
        }
        ,
        options: {
            title: {
                display: true, text: 'Romulo Cano Total: '+@r5
            }
        }
    }

    ;
    var config2= {
        type: 'pie',
        data: {
            datasets: [ {
                data: [ @e1, @e2, @e3, @e4 ], backgroundColor: [ "#de4e3a", window.chartColors.yellow, window.chartColors.blue, window.chartColors.green, ], label: 'Dataset 1'
            }
            ],
            labels: [ "1 Mês +",
            "2 Semanas +",
            "No Prazo",
            "Planejada"]
        }
        ,
        options: {
            responsive: true
        }
        ,
        options: {
            title: {
                display: true, text: 'Ericles Silva Total: '+@e5
            }
        }
    }

    ;
    var config3= {
        type: 'pie',
        data: {
            datasets: [ {
                data: [ @a1, @a2, @a3, @a4 ], backgroundColor: [ "#de4e3a", window.chartColors.yellow, window.chartColors.blue, window.chartColors.green, ], label: 'Dataset 1'
            }
            ],
            labels: [ "1 Mês +",
            "2 Semanas +",
            "No Prazo",
            "Planejada",
            ]
        }
        ,
        options: {
            responsive: true
        }
        ,
        options: {
            title: {
                display: true, text: 'Anderson Litri Total: '+@a5
            }
        }
    }

    ;
    var config4= {
        type: 'pie',
        data: {
            datasets: [ {
                data: [ @h1, @h2, @h3, @h4 ], backgroundColor: [ "#de4e3a", window.chartColors.yellow, window.chartColors.blue, window.chartColors.green, ], label: 'Dataset 1'
            }
            ],
            labels: [ "1 Mês +",
            "2 Semanas +",
            "No Prazo",
            "Planejada"]
        }
        ,
        options: {
            responsive: true
        }
        ,
        options: {
            title: {
                display: true, text: 'Henrique Giopato Total: '+@h5
            }
        }
    }

    ;
    var config5= {
        type: 'pie',
        data: {
            datasets: [ {
                data: [ @f1, @f2, @f3, @f4 ], backgroundColor: [ "#e13f3a", window.chartColors.yellow, window.chartColors.blue, window.chartColors.green, ], label: 'Dataset 1'
            }
            ],
            labels: [ "1 Mês +",
            "2 Semanas +",
            "No Prazo",
            "Planejada"]
        }
        ,
        options: {
            responsive: true
        }
        ,
        options: {
            title: {
                display: true, text: 'Francisco Melo Total: '+@f5
            }
        }
    }

    ;
    var config6= {
        type: 'pie',
        data: {
            datasets: [ {
                data: [ @l1, @l2, @l3, @l4 ], backgroundColor: [ "#e13f3a", window.chartColors.yellow, window.chartColors.blue, window.chartColors.green, ], label: 'Dataset 1'
            }
            ],
            labels: [ "1 Mês +",
            "2 Semanas +",
            "No Prazo",
            "Planejada"]
        }
        ,
        options: {
            responsive: true
        }
        ,
        options: {
            title: {
                display: true, text: 'Lucas Silva Total: ' +@l5
            }
        }
    }

    ;
    var config7= {
        type: 'pie',
        data: {
            datasets: [ {
                data: [ @c1, @c2, @c3, @c4 ], backgroundColor: [ "#e13f3a", window.chartColors.yellow, window.chartColors.blue, window.chartColors.green, ], label: 'Dataset 1'
            }
            ],
            labels: [ "1 Mês +",
            "2 Semanas +",
            "No Prazo",
            "Planejada"]
        }
        ,
        options: {
            responsive: true
        }
        ,
        options: {
            title: {
                display: true, text: 'Caroline Muniz Total: '+@c5
            }
        }
    }

    ;
    window.onload=function () {
        var ctx=document.getElementById("chart-area").getContext("2d");
        window.myPie=new Chart(ctx, config);
        var ctx2=document.getElementById("chart-area2").getContext("2d");
        window.myPie=new Chart(ctx2, config2);
        var ctx3=document.getElementById("chart-area3").getContext("2d");
        window.myPie=new Chart(ctx3, config3);
        var ctx4=document.getElementById("chart-area4").getContext("2d");
        window.myPie=new Chart(ctx4, config4);
        var ctx5=document.getElementById("chart-area5").getContext("2d");
        window.myPie=new Chart(ctx5, config5);
        var ctx6=document.getElementById("chart-area6").getContext("2d");
        window.myPie=new Chart(ctx6, config6);
        var ctx7=document.getElementById("chart-area7").getContext("2d");
        window.myPie=new Chart(ctx7, config7);
    }

    ;

    }

}

A: Tenta usar:
@media (min-width: 1200px)
.container {
    max-width: 1200px;
    background: #ffffff;
    margin: 0.5em;
    box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.5);
}

Você pode dá uma olhada mais aprofundada aqui: https://pt.stackoverflow.com/a/383840/79242


text:
Q: How is autotools configured to build optional components only when dependencies are installed? I have a C++ project using autotools as the build system.
My program involves an abstract interface, of which there are several implementations, with each implementation in a separate source file. These implementations depend on libraries which may or may not be installed, depending on user preference and platform.
I would like to configure autotools to skip building the implementations that are lacking the underlying dependencies. I'd like to do so in whatever way will be conventionally expected by users and package maintainers.
As an example, let's say my program outputs audio, and it can do so with OSS, ALSA, or JACK. These are implemented in oss_output.cc, alsa_output.cc, and jack_output.cc, respectively.
Currently my Makefile.am contains (among a few other things):
myprog_SOURCES = \
    src/oss_output.cc \
    src/alsa_output.cc \
    src/jack_output.cc

myprog_LDFLAGS = [...some other stuff...] -ljack

Unfortunately attempting to build this program on a system without JACK installed fails because the linker can't find libjack and/or the compiler fails because JACK's header files are missing. In the case JACK isn't installed, I'd instead like to drop src/jack_output.cc from myprog_SOURCES, and remove -ljack from myprog_LDFLAGS. And similar, for ALSA and OSS.
Of these dependencies (OSS, ALSA, and JACK), some of these libraries use pkg-config. Some do not, but I can still detect their presence by the existence of a header file and a library.
How is this accomplished with autotools, taking care to follow best practice and convention?

A:
How is this accomplished with autotools, taking care to follow best practice and convention?

There are two pieces:

*

*Detecting which subsystems are wanted / supported, and

*Limiting the build to only the selected subsystems.

Identifying the subsystems to support
The first piece is Autoconf's bread & butter.  Typically, one would check for the presence of each subsytem's library(-ies) via AC_CHECK_LIB() or AC_SEARCH_LIBS() to identify whether it is available, and also check for the main header file(s) via AC_CHECK_HEADER() or AC_CHECK_HEADERS().
It would be a convenience to also set up a mechanism for opting out of building support for some of the subsystems that are available.  That would take the form of setting up --without or --disable arguments (which of those to choose is often ambiguous).  This is not obligatory, but I would consider it good form.  Note, however, that it does require some care and attention to avoid including all found libraries in the link.
The Cadillac version would furthermore provide support for the user specifying where to find the wanted libraries and headers, in case they are not in the default search path.  I often do see this sort of thing in well-maintained projects, but it takes the complexity up a level, and I would not consider it in any way obligatory.
The implementation details could vary quite widely, but typically, the end result would be, for each subsystem,

*

*a shell variable indicating whether to include the subsystem in the build (maybe build_oss, for example), and

*(optionally) output variables (created via AC_SUBST()) conveying preprocessor / compiler / and or linker flags to be used to build against the the appropriate back-end library.  For instance, some or all of OSS_CPPFLAGS, OSS_CXXFLAGS, OSS_LIBS for the OSS piece.

Limiting the build to selected subsystems
Automake and Autoconf work together on this.  The key tool is the Automake conditional.  Automake provides an Autoconf macro, AM_CONDITIONAL, for defining these and assigning their values, and it supports an if / then / else construct in Makefile.am files based on them.  (Note well that these are entirely separate from GNU make conditionals, though they have similar syntax.)
The section of the Automake manual I have linked refers to several others that discuss how conditionals should be used in various scenarios, and it's not entirely clear which of those apply to you.  My best guess, however, is that all you really need is conditional sources, so that's what I'll focus on.
The Autoconf part would follow on from the bits I already discussed.  It might be as simple as
AM_CONDITIONAL([oss], [test "$build_oss" = "1"])
AM_CONDITIONAL([alsa], [test "$build_alsa" = "1"])
AM_CONDITIONAL([jack], [test "$build_jack" = "1"])

The Automake manual gives other examples.
On the Makefile.am side, that might match up with something like this:
myprog_SOURCES = \
  src/main.cc \
  src/another.cc \
  ...

if oss
  myprog_SOURCES += src/oss_output.cc
endif
if alsa
  myprog_SOURCES += src/alsa_output.cc
endif
if jack
  myprog_SOURCES += src/jack_output.cc
endif

You would need to take care of applying the per-subsystem flags and libraries, too.  You can take the same approach (and even use the same if blocks) as for the sources, and that would be just fine, or you could let configure take control through how (whether) it defines any flags for each subsystem in the first place.
You will have noticed that I glossed over many of the details.  This is a fairly high-level answer to what I have to take as a high-level question.  If I take the question any other way then it is too broad for this venue.

A: The way to have selective compilations with autotools is to detect in configure.ac and define in Makefile.am. Using this method, detection of available libraries is done when the initial configure command executes and this conditionally creates a Makefile which only compiles source code if its dependencies are installed.
For example from the gtkIOStream software's configure.ac detects the presence of jack. It then defines the variabel HAVE_JACK if it is present, like so :
# jack
PKG_CHECK_MODULES([JACK], [jack], HAVE_JACK="yes", HAVE_JACK="no")
AC_SUBST(JACK_CFLAGS)
AC_SUBST(JACK_LIBS)
AM_CONDITIONAL(HAVE_JACK, test x$HAVE_JACK = xyes)
if test "x$HAVE_JACK" == xyes ; then
    AC_DEFINE(HAVE_JACK, [], [whether to build in Jack support])
fi

The Makefile.am checks for the HAVE_JACK variable and if it exists, it alters compilation. In your case this should work :
if HAVE_JACK
    myprog_SOURCES += src/jack_output.cc
endif

Now if configure detects jack, then your Makefile adds it to the sources to build.
If you want to limit ammplications from being built, then you will want to ammed a different variable (as for the previously mentioned gtkIOStream example) which looks like this :
if HAVE_JACK
bin_PROGRAMS += I2SEndianTest CrossoverTester
endif

gtkIOStream also detects ALSA like so :
# alsa
PKG_CHECK_MODULES(ALSA, alsa, HAVE_ALSA="yes", HAVE_ALSA="no")
AC_SUBST(ALSA_CFLAGS)
AC_SUBST(ALSA_LIBS)
AM_CONDITIONAL(HAVE_ALSA, test x$HAVE_ALSA = xyes)
if test "x$HAVE_ALSA" == xyes ; then
    AC_DEFINE(HAVE_ALSA, [], [whether to build in Alsa support])
fi


text:
Q: ECONNRESET nodejs kubernetes I am getting a lot ECONNRESET
Error: socket hang up
    at connResetException (internal/errors.js:570:14)
    at Socket.socketOnEnd (_http_client.js:440:23)
    at Socket.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1183:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

In one of my application sending request to my microservice.
Both are running into my kubernetes and calling via the internal endpoint, for example my-service.production:3026
It happens when we are sending a lot of requests from the app to the service which is performing request into mongodb.
The problem is that on the app side I only have the ECONNRESET error and nothing on the service.
Can the issue comes from the kubernetes network ? And how can I debug it ?

A: With the looks of it, you are getting ECONNRESET because TCP/IP connection limit is breaching.
By default each server/machine allow 1000 TCP/IP connections. Maximum limit of connections is 65,535. You can increase these connections by following answer on this thread
mongodb : Increasing max connections in mongodb
You need to increase connections limit on every server involved.


text:
Q: Counterexample of polynomials in infinite dimensional Banach spaces I'm trying to prove exercise I.3.B in Mujica's "Complex analysis in Banach spaces".
DEFINITIONS:

A map $P$ is an m-homogeneous polynomial from $E$ to $F$ if there is a m-linear map $A$ from $E^m$ to $F$ such that $P(x)=A(x, \dots, x)$.
$P$ is a polynomial of degree at most $m$ if $P = P_0 + \dots + P_m$ where each $P_j$ is an j-homogeneous polynomial.

I have to find a function $f: E \to \mathbb{K}$ (where $E$ is infinite dimensional) such that $f(a + \lambda b)$ is a polynomial in $\lambda$ for all $a,b \in E$ but $f$ is not a polynomial.
$f$ clearly has to be discontinuous because there is a theorem implying that $f$ would be a polynomial in the continuous case.
I thought about considering something like (where $\theta$ stands for the step function):
$$f(a+\lambda b) = \theta (\| b\| -1) (a_1 + \lambda b_1)$$
But I don't know how to prove that $f$ wouldn't be a polynomial or even how to apply it to an arbitrary $x \in E$.
I also know that the restriction of $f$ to any finite dimensional subspace of $E$ is indeed a polynomial and that there is a sequence of homogeneous polynomials $P_k$ such that $f(x)=\sum_{k=0}^{\infty} P_k(x)$ where for each $x \in E$ $P_k(x)=0$ for all but finitely many indices.
What function could act as a good example for this situation?
I can provide any definition if you're not familiar with the terminology. Please ask for clarification in a comment if that is the case.

A: Let $\{x_i;i\in I\}$ be a Hamel basis for $E.$ If $E$ is infinite dimensional then without loss of generality we can have $I$ include the natural numbers as a subset.
Define
$$f:E\to\mathbb K:\sum_{i\in I}\alpha_ix_i\mapsto\sum_{n\in\mathbb N}\alpha_n^n.$$
Then $f$ cannot be a polynomial of degree at most $m$ for any $m,$ because for all $\lambda\in\mathbb K$ we have
$$f(\lambda x_{m+1})=\lambda^{m+1}$$
On the other hand for fixed $a$ and $b$ in $E$ the function $\lambda\mapsto f(a +\lambda b)$ is a polynomial in $\lambda$ because $a$ and $b$ are linear combinations of a finite number of elements from the Hamel basis.


text:
Q: Cosmos DB Result Missing in Larger Search I wonder if I may be hitting a limit of some kind that is causing this behvaviour. I have run a query that proves a record exists in the Cosmos DB document collection when filtered by three fields PLUS the unique id, but when I remove the unique id I get back 124 results, none of which is the original record.
If I run the following live query in the Azure portal, I get a single result, which is the item I expect:
-- 1 result, item 'ABCD-EFGH-IJKL-MNOP' present and correct
SELECT
    *
FROM a
WHERE a.width = 205
AND a.height = 55
AND a.depth = 16
AND a.uniqueId = 'ABCD-EFGH-IJKL-MNOP'

When I remove the final line, I get 124 results, but not the item with unique id 'ABCD-EFGH-IJKL-MNOP'.
-- 124 results, item 'ABCD-EFGH-IJKL-MNOP' missing
SELECT
    *
FROM a
WHERE a.width = 205
AND a.height = 55
AND a.depth = 16

Each record is actually pretty big, because the document contains quite a large array of information. If I change the query again to:
-- 150 results, item 'ABCD-EFGH-IJKL-MNOP' present and correct
SELECT
    a.width,
    a.height,
    a.depth,
    a.uniqueId
FROM a
WHERE a.width = 205
AND a.height = 55
AND a.depth = 16

I get 150 results and the result magically pops back into the results...
Is there some limit that could cause by result to be left out?
Additional notes:

*

*I'm testing this in query explorer

*I have changed "Settings -> Items per page" to "Unlimited"

A: Even though you run a query "unlimited" (with FeedOptions.MaxItemCount set to -1), the results can still be paged based on the amount of data that comes back.
You can detect this because the flag Has More Results comes back true:
if (queryable.HasMoreResults)
{
    //... there are more results
}

You may not be expecting this when running an unlimited query.
If you are using the REST API, there is a header for this:
x-ms-continuation=randomlookingstring

You can pass this header back in a subsequent request and the query will resume.
I am currently looking for the documentation on limits and will update when I find it.


text:
Q: Using group with Inner Join in Sequelize giving error I am trying to write this raw query
SELECT users.status,count(`users`.`id`) AS `count`
FROM `users` AS `users`
   INNER JOIN `organization_entries` AS `organizationEntries` ON `users`.`id` = `organizationEntries`.`user_id`
       AND `organizationEntries`.`organization_id` = '1'
       AND `organizationEntries`.`type` = '001'
group by users.status;

in Sequelize .
I have written this query in Sequelize like this
db.users
    .findAll({
      attributes: [
        'status',
        [db.sequelize.fn('COUNT', 'users.id'), 'entries']
      ],
      include: {
        model: db.organizationEntries,
        where: {

          organization_id: req.params.org_id,
          type: '001',

        },
      },
      group: ['users.status']
    }).then(c => {
      console.log(c);

      let active_users = {
        active_users: c,
      }
      return res.send(active_users);

    })
    .catch(next);

but when I am running this query I am getting this error

code  "ER_WRONG_FIELD_WITH_GROUP" errno   1055 sqlState   "42000"
sqlMessage    "Expression #1 of SELECT list is not in GROUP BY clause and
  contains nonaggregated column 'ontro.users.id' which is not
  functionally dependent on columns in GROUP BY clause; this is
  incompatible with sql_mode=only_full_group_by"

I am not able to understand what I am doing wrong.

A:
If the ONLY_FULL_GROUP_BY SQL mode is enabled, MySQL rejects queries for which the select list, HAVING
  condition, or ORDER BY list refer to nonaggregated columns that are
  neither named in the GROUP BY clause nor are functionally dependent on
  them.

Please read on MySQL Handling of GROUP BY.


text:
Q: What is a word to describe these two separate but related items in a software application? Some background: I am working on the menu for an online homework assignment generator.  In this program, the user will click through a series of pages and fill in necessary information (assigned & due dates, questions included, order & number of questions, etc).  At the top of each page is a group of tabs to allow the user to switch between the pages.
The current tabs have the labels:

*

*Details

*Questions

*Edit

*Print

*Done

All pretty self-explanatory.
Now, a page is being added to the application in which the user can make the assignment only be assigned to certain students in the class, or give certain students different assigned or due dates.
The question is: what would be a good tab label for this page?  I'm looking for a single word that would describe to the user what they can do on this page.  Two words could possibly fit in the tab, but no more than that.

A: If it is an assignment for just certain students, I suggest a name "Special Assignment" or "Personal Assignment" (or plural, if more than one), and show it ONLY if current student does have such assignment (hide button if no such assignments). If you have to show it always, show the number (which would be 0 if none are assigned), like: "Personal Assignment (0)".
Number is to improve usability: if such bonus assignments are rare, it is frustrating to open something just to see nothing it there, and after a while you will train your users never open it - which is exactly the opposite you want.
If you need to save the space, just "Personal (0)" is OK too.
If your font does not distinguish between uppercase O and 0 (zero), "None" is better than confusing 0.
If such assignment is for extra points, you can use "Bonus (2)".
If all students have same assignment, but due on different dates (why would you even consider that? What would be a business reason to do that), just show due date with the assignment, no need of special page.

A: Permissions, Roles, Groups, Advanced (where you can house all additional functionalities in the future as well)


text:
Q: Invariant ring of $\mathrm{SO}_3(\mathbb{Z})$ By classical results in invariant theory, we know the invariant ring $\mathbb{C}[X_1, X_2, X_3]^{\mathrm{SO}_3(\mathbb{C})}$ is equal to $\mathbb{C}[X_1^2 + X_2^2 + X_3^2]$. Here
$\mathbb{C}X_1 \oplus \mathbb{C}X_2 \oplus \mathbb{C}X_3$ is the fundamental representation of $\mathrm{SO}_3(\mathbb{C})$.
My question is, what about $\mathbb{Z}[X_1, X_2, X_3]^{\mathrm{SO}_3(\mathbb{Z})}$?
More generally, view $\mathrm{SO}_3$ as an affine group scheme, can we describe the functor
$$R\longmapsto R[X_1, X_2, X_3]^{\mathrm{SO}_3(R)}$$
from the category of commutative rings to itself?

A: $SO_3(\mathbb{Z})$ is generated by
$\left[ \begin{array}{rrr} -1 & 0 & 0 \\ 0 & -1 & 0 \\ 0 & 0 & 1 \end{array} \right],\left[ \begin{array}{rrr} 0 & 1 & 0 \\ -1 & 0 & 0 \\ 0 & 0 & 1 \end{array} \right],\left[ \begin{array}{rrr} 0 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{array} \right]$.
You can conclude that the invariant ring is $\mathbb{Z}[\,x_1^2 x_2^2 x_3^2\,,\, x_1^2+x_2^2+x_3^2\,,\,x_1^2 x_2^2+x_2^2 x_3^2+x_3^2 x_1^2\,,\,x_1x_2x_3(x_1^2-x_2^2)(x_2^2-x_3^2)(x_3^2-x_1^2)\,]$.
$\\$
How about an arbitrary ring $R$ in general? A fascinating question! If you're interested, maybe consider finite fields? I haven't thought much about this, but good luck!


text:
Q: Questions about existence of injections between infinite sets and the sets of all infinite topologies on them 1) If $X$ is an infinite set and $T_X$ the set of all infinite topologies on $X$ is it in general true that there is no injection $f_T:T_X \to X$?
2) What conditions on $X$ assure an injection (if that´s ever possible)?
By infinite topologies, I mean topologies with an infinite number of sets (subsets of $X$) as its elements.

A: Similar to Keith Kearnes' answer, but made slightly more concrete:

*

*there's an injection from "partial orders on $X$" to "infinite topologies on $X$", sending any partial order to its Alexandrov topology, whose open sets are just the down-closed sets of the order.  This is always infinite if $X$ is, since the sets $\mathord{\downarrow} \{x \}$ are distinct for each $x \in X$; and it's an injection since any partial order can be recovered from its Alexandrov topology as the specialisation order.

*there's an injection from "proper subsets of $X$" to "partial orders on $X$" sending $S \subseteq X$ to the order where $x <_S y$ just if $x \in S$ and $y \notin S$.  (I.e. all of $X \setminus S$ is above all of $S$, and the order is otherwise discrete.)  This is an injection since $S$ can be recovered as $\{ x \mathrel{|} \exists y,\ x <_S y \}$.

*composing these gives an injection from "proper subsets of $X$" to "infinite topologies on $X$"

*so any injection "infinite topologies on $X$" to $X$ would give an injection from "proper subsets of $X$" to $X$, which is impossible.
I'm assuming throughout that you work in ZFC.  Without choice, the earlier parts all work, but the final step breaks, because we don't know that there's no injection $\mathcal{P}(X) \to X$.
In a comment, you mention restricting further, to topologies whose (nonempty) open sets are all infinite.  That doesn't essentially change anything, as can be shown by a slight modification of the above construction.  Fix a countable and co-infinite set $K \subseteq X$.  Now take the injection from "proper subsets of $X \setminus K$" to preorders on $X$, where $\leq_S$ puts $K$ codiscretely at the bottom, $S$ discretely in the middle, and $X \setminus (S \sup K)$ discretely on top.  Now send this to its specialisation order.  This gives an injection from "proper subsets of $X \setminus K$" to "infinite topologies on $X$ with all nonempty opens infinite".  But since $K$ was countable and co-infinite, $|X \setminus K| = |X|$, so we are done as before.

A: Let
$$ \forall_{A\subseteq X}\quad \mathcal B_A
\ :=\ \{\{a\} :\ a\in A\}\cup X $$
Then each $\ \mathcal B_A\ $ is a topological base in $\ X\ $
while every two of them generate different topologies in $\ X.\ $ When $\ X\ $ is infinite then
$$ |\,\{\mathcal B_A :
    \, A\subset X\ \ \text{and}\ \ |A|=\infty \}\,|
      \,\ =\,\ 2^{|X|} $$
We see that an injection of the set of all topologies
in $\ X\ $ into $\ X\ $ is impossible when $\ X\ $ infinite.
Remark 1    There is no such injection also when $\ X\ $ is finite but $\ |X|\ne 1.\ $
Indeed, let
$$ \forall_{A\subseteq X}\quad T_A
           \ :=\ \{\emptyset\,\ A\,\ X\} $$
These are topologies, and
$$ |\,\{T_A:\,A\subseteq X\}\,|\ =\ 2^{|X|}-1 $$
for every non-empty finite $\, X.\, $ In the empty case we get $\, 0\, $ points and $\, 1\, $ topology, $\ 0<1.$
Remark 2   The situation, cardinality wise, is even more dramatic.

A: For an infinite set $X$, there are $2^{2^{|X|}}$ topologies with infinitely many elements on $X$.
The upper bound is obvious, the lower bound is given by my comment (and the slight correction in YCor's): for any ultrafilter $U$ on $X$, define $T_U$ to have as opens the empty set and the elements of $U$. It is clear that this forms a topology, and that you can recover $U$ from it.
Moreover, clearly $T_U$ has infinitely many open sets.
So $U\mapsto T_U$ defines an injection $\beta X\to T_X$, and it's well known that $|\beta X| = 2^{2^{|X|}}$.
So there can be no injection $T_X\to X$ (in fact, no injection $T_X\to P(X)$)
YCor's comment below mine elaborates a bit on what one can ask of these topologies and how many we get (Hausdorff, metrizable)

A: If $X$ is an infinite set, then there are $2^{|X|}$-many ways to well-order $X$. Each such order determines an Alexandroff topology on $X$, which will have infinitely many open sets. The order is recoverable from the topology, so there are too many different infinite topologies on $X$ for there to be an injection $f_T: T_X\to X$.


text:
Q: Corrupted excel file when emailing it in Android from a Uri using the Gmail API I'm trying to share from Microsoft's Excel Android app to my custom Android app that will take the shared excel workbook and send it in an email through Gmail's API.
After my app sends the email and I try to open the excel file on my computer, I get there error, "We found a problem with some content in 'May 25.xlsx'."
It does, however, open in the desktop Chrome browser using Google Sheets.
Here's the Uri of the workbook: content://com.microsoft.office.excel.excelApplication.provider/docsui_temp_share_files/fea009cf-65c3-46f4-8dda-50758298b9fc/May%2025.xlsx
Here's the code that turns it into a file.
Context ctx; //defined by Android
Uri uri; //comes in populated with the value above
String filename; //generated from the Uri in a separate method

InputStream is = ctx.getContentResolver().openInputStream(uri);
File directory = ctx.getCacheDir();
FileOutputStream fos = null;
File fileToReturn = null;
try {
    final File tempFile = File.createTempFile(filename.split("\\.")[0], "." + filename.split("\\.")[1], directory);
    tempFile.deleteOnExit();

    fos = new FileOutputStream(tempFile);

    byte[] bytes = new byte[1024 * 16];
    int read = -1;
    while ((read = is.read(bytes)) != -1) {
        fos.write(bytes);
    }

    fileToReturn = tempFile;

}
finally {
    if (fos != null) {
        fos.close();
    }
}

Here's the code that creates the MimeMessage to send. The attachments parameter has the File created from above.
private MimeMessage createEmail(List<String> toAddresses,
                                String from,
                                String subject,
                                String bodyText, ArrayList<File> attachments) throws MessagingException {
    if(attachments == null){
        attachments = new ArrayList<>();
    }
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress fAddress = new InternetAddress(from);

    for(String toAddress : toAddresses) {
        InternetAddress toInternetAddress = new InternetAddress(toAddress);
        email.addRecipient(javax.mail.Message.RecipientType.TO, toInternetAddress );
    }

    email.setFrom(fAddress);
    email.setSubject(subject);

    Multipart multipart = new MimeMultipart();

    BodyPart textBody = new MimeBodyPart();
    textBody.setText(bodyText);
    multipart.addBodyPart(textBody);

    for (File attachment : attachments){
            MimeBodyPart attachmentBody = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment.getAbsolutePath());
            attachmentBody.setDataHandler(new DataHandler(source));
            attachmentBody.setFileName(attachment.getName());
            multipart.addBodyPart(attachmentBody);
    }

    email.setContent(multipart);
    return email;
}

And the code to send the email.
private String sendMessage(Gmail service,
                           String userId,
                           MimeMessage email)
        throws MessagingException, IOException {

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    email.writeTo(bytes);

    ByteArrayContent messageByteArrayContent = new ByteArrayContent("message/rfc822", bytes.toByteArray());

    Message message;
    message = service.users().messages().send(userId, null, messageByteArrayContent).execute();
}

Here's what comes through as the email.
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_0_262386509.1596398610889"
Date: Sun, 2 Aug 2020 13:03:34 -0700

------=_Part_0_262386509.1596398610889
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

May 252265647717182285060.xlsx
------=_Part_0_262386509.1596398610889
Content-Type: application/octet-stream; name="May 25.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="May 25.xlsx"

------=_Part_0_262386509.1596398610889--

Note that the Content-Type is application/octect-stream.
I've made this application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, by manually adding a Content-Type header, but to no avail.
This code works to send almost anything else. And if I save the excel file first and share it from my file manager app, it opens just fine.
And it seems specific to an excel file. If I share it as a pdf from the Excel app (that's an option), the pdf opens fine.
I also encounter the same error if I try to share from the Google Sheets app, and share it as an .xlsx file. But again, if I try to share it as anything else, like a .csv or .pdf, it opens fine on the other side.
Here's the email if it's shared as a .pdf file from the Google Sheets app. Again, the content type is application/octet-stream, but it opens fine here.
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_4_203349844.1596399067869"
Date: Sun, 2 Aug 2020 13:11:10 -0700

------=_Part_4_203349844.1596399067869
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Untitled spreadsheet8410545067288443069.pdf
------=_Part_4_203349844.1596399067869
Content-Type: application/octet-stream; name="Untitled spreadsheet8410545067288443069.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Untitled spreadsheet8410545067288443069.pdf"

------=_Part_4_203349844.1596399067869--

A: In the code, where you are writing the xlsx file, you are always reading a specified buffer size (1024 * 16), and writing to file. I think on last read, if the bytes you read are less than the buffer size of your bytes array, you would be writing extra unnecessary bytes. This could be your file corruption reason.


text:
Q: What's a word like "disregard" or "bypass" that means "hides"? Imagine that someone skips a step, with the hope that the audience will never know that it existed.  I was thinking extends or circumvents.  I'm not sure if these words are on the nose; I am looking for a word that really shows intent to conceal.
Here's a sample sentence:

Any plan of action that ______ preservation of human life is, at its core, flawed.

A: I think eschew would fit well in these circumstances.

A: I feel like there is a perfect term lurking at the edge of my memory, but all I'm coming up with immediately is "Ignore" in the sense of pretending that something does not exist.
"Gloss Over" is a bit better, and plain old "Overlook" is another possibility.

A: While it doesn't quite work (gracefully) in your sample sentence, elide is a word that describes the kind of action you mention in your opening sentence.
From my Merriam-Webster thesaurus:

Entry Word: elide Function: verb Text: Synonyms NEGLECT, discount,
  disregard, fail, forget, ignore, omit, overlook, pass, slight

A: To obscure is to conceal, to make unclear or indistinct. The act of obscuring is an intention to hide or make less visible. However, in the context of your sentence the word disregards is perhaps more appropriate although it doesn't retain the intent of concealing.

A: Dismiss.  In your case, dismisses.


text:
Q: how to get nearest point to a given point in points of polygon? Here is image ,

I want to know how to get nearest point to a given point [can be anywhere] [green one] , for array of points. By seeing we can get, but how to do same in code ?

A: The distance between between two points can be found by using the distance formula. By implementing this formula, you can iterate through your collection of points and find the closest one to your starting point.

A: Calculate the distance to each point:
distance = sqrt((x2-x1)^2 + (y2-y1)^2)

Then take the min of that. There are probably more efficient ways of doing it (e.g. octtrees) for very large # of points.


text:
Q: Join array of strings in d In python I can do this:
In [1]: x = ["a", "b", "c"]

In [2]: "--".join(x)
Out[2]: 'a--b--c'

Is there an equivalent trick in d?

A: Yes, use std.array.join:
import std.array, std.stdio;

void main()
{
    auto x = ["a", "b", "c"];
    writeln(x.join("--"));
}

Note that D's argument order is reversed when compared to Python's.


text:
Q: How To Add New Line on Metadata by C# I have file .XML by Exporting on Gridview But The Metadata showed Like
and i want the metadata like
Here is My Code
    private void ExporttoExcel( DataTable table)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ContentType = "application/xml";
        HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename= Att " + txtPeriodeAwal.Text + " to " + txtPeriodeAkhir.Text + ".xml");

        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

        HttpContext.Current.Response.Write("<?xml version=\"1.0\"?>");
        HttpContext.Current.Response.Write("<?mso-application progid=\"Excel.Sheet\"?>");
        HttpContext.Current.Response.Write(" <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        HttpContext.Current.Response.Write("xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
        HttpContext.Current.Response.Write("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
        HttpContext.Current.Response.Write("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
        HttpContext.Current.Response.Write("xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
}

Can I get New Line Indent on My metadata base on My Code??


text:
Q: Keycloak Access-Control-Allow-Origin I have integrated keycloak with my angularJS app.While I running the app after login page, The browser console showing.
XMLHttpRequest cannot load http://192.168.1.7:8080/auth/realms/app1/protocol/openid-connect/token. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://192.168.1.7:8000', but only one is allowed. Origin 'http://192.168.1.7:8000' is therefore not allowed access.

A: You need to set the Web Origins property for your client in the KC Web Console.


text:
Q: Avoid unwanted path in Zip file in makefile I want to create an archive for a given folder but without the folders name in the path...
In fact I want to do the same thing that this post : Avoid unwanted path in Zip file
BUT I'm in a makefile and the following code doesn't work :
cd $(PROJECT_FOLDER)
zip -r dist/$(ARCHIVE) $(PROJECT_FOLDER)

It is like cd is not done and finaly the archive is well created but with the $(PROJECT_FOLDER) folder at the beginning.
Do you know how to do this ?

A: Each command line in a Makefile is launched into a separate shell process.  To get a cd to work, do
cd $(PROJECT_FOLDER); zip -r dist/$(ARCHIVE) $(PROJECT_FOLDER)

i.e., all on one line.
Optionally, for clarity, you could say
cd $(PROJECT_FOLDER); \
zip -r dist/$(ARCHIVE) $(PROJECT_FOLDER)

i.e., make it one logical line, but break the pieces into separate physical lines.


text:
Q: Merge multiple PDfs using pypdf2 and Email I am using PyPDF2 to merge multiple pdf files and then use python shutil method to copy the output to the final destination and use smtplib to email a copy(as an attachment) to a user.
The merged files in the final destination is appearing correctly but the emailed copy(attachment) is not.  Only fist item in an array is appearing but rest page is blank with correct total number of pages.
Here is my workflow

*

*Merge Files and save merged to local folder  --- Working as expected

*Copy merged file to final destination --- Working as expected -

*Email a copy of merged file to user email address  -- First file in an array, empty pages after that. The total number of pages matches with the total count.

I am using following code to merge files
pdf_list=['pdf_source.pdf','second_file.pdf','third_file.pdf']
for pdf in pdf_list:
            merger.append(PdfFileReader(pdf),'rb')
with open(merge_file_name, 'wb') as new_file:
            merger.write(new_file)

Please suggest

A: After researching, I found the issue was not pypdf2 but the way file was being attached to an email.
Following stackoverflow solution fixed the issue.
How to attach a pdf file to a MIME email in Python?


text:
Q: Не могу обработать массив PHP Есть функция
    function getFile($file_id) {
  $file_path_array = json_decode(file_get_contents($GLOBALS['api'] . '/getFile?file_id=' . $file_id), TRUE);
    $file_path = $file_path_array['result']['file_path'];
    $file_path_url = 'https://api.telegram.org/file/bot00037100:XXXkXU9L8DXXXXXUSY0R36XXCQ9d3XXXX/'.$file_path;
    return $file_path_url;
}

Обрабатывает она массив формата
{"ok":true,"result":{"file_id":"XXXXqcxGwyaYxXXXXXVvITMmrQ4ABOlO5XXX1KQBAXXX","file_size":47984,"file_path":"photos/file_0.jpg"}}

Почему то она может переварить значения file_id и file_size но вот нужное file_path выводить категорически отказывается


text:
Q: programa em c duvida - busca dentro do for Olá! Sou estudante de ciências da computação e estou desenvolvendo um programa de uma livraria com menu. O programa funciona todo que é uma beleza por excessão de uma coisa...
Quando faço uma busca por autor não consigo colocar quando o autor não foi encontrado
quando adiciono o else ele encontra o autor e depois aparece não encontrado para cada livro cadastrado.
poderiam me ajudar?
segue meu codigo de busca
case 'a':

    fflush(stdin);
    printf("\ndigite o AUTOR do livro que procura\n");

    gets(autor_pesquisa);

    for(i=0; i<=cadlivrosmax; i++){
        retorno = strcmp(autor_pesquisa,quantidades[i].autor);
        if(retorno == 0){
            printf("Codigo: %d\n",i+1);
            printf("Titulo: %s\n",quantidades[i].titulo);
            printf("Autor: %s\n",quantidades[i].autor);
            printf("Estilo: %s\n",quantidades[i].estilo);
            printf("Preco: %f\n\n\n",quantidades[i].preco);
        }

        else{
            printf("\n autor não encontrado\n");
        }
    }

break;

A: Poderia fazer assim:
case 'a':

fflush(stdin);
printf("\ndigite o AUTOR do livro que procura\n");

gets(autor_pesquisa);

for(i = 0; i <= cadlivrosmax; i++){

    retorno = strcmp(autor_pesquisa,quantidades[i].autor);

    if(retorno == 0){
        break;
    }

}

if(retorno == 0){

    printf("Codigo: %d\n",i+1);
    printf("Titulo: %s\n",quantidades[i].titulo);
    printf("Autor: %s\n",quantidades[i].autor);
    printf("Estilo: %s\n",quantidades[i].estilo);
    printf("Preco: %f\n\n\n",quantidades[i].preco);

} else {

    printf("\n autor não encontrado\n");

}

break;


text:
Q: Return int as boolean I am a beginner so please bear with me. I decompiled the source code of a professional application. When I copied the source code into eclipse, an error came up with the following code( the error is with the return type):
public boolean method(){
...
...
   for(int i = 0; ; i = 1){
       return i;
}

How can I change the code to keep it correct but keep the functionality?

A: You can cast i as a boolean, or change return i; to return i != 0;, which will be true for all non-zero values of i, and false if i == 0.
As a side note, I really see no reason to wrap a return in a for loop. In this case, you might as well just replace both of those lines with return 0; (or return false;, to match the method signature).

A: Change the return type from boolean to int.
As you can see, your method is returning i which is declared as an int in the for loop, so the return type of your method has to be the same as the type of the variable it returns.


text:
Q: how to get key value of array with curl (php) I want to make use of an API but it print alot of info and i don't know how i can get a few key values of the array.
<?php
$query = "SELECT * FROM kvk WHERE adres='Wit-geellaan 158'";
$host  = "http://api.openkvk.nl/php/";
$url   = $host ."/". rawurlencode($query);

$curl = curl_init();
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);

curl_exec($curl);

curl_close($curl);
?>

Is my php script and it shows
array(array("RESULT"=>array("TYPES"=>array("int","bigint","varchar","varchar","varchar","varchar","varchar","int","int","smallint","smallint","int"),"HEADER"=>array("id","kvk","bedrijfsnaam","adres","postcode","plaats","type","kvks","sub","bedrijfsnaam_size","adres_size","verhuisd"),"ROWS"=>array(array("1303095","271242250000","Schoonmaakbedrijf Regio","Wit-geellaan 158","2718CK","Zoetermeer","Hoofdvestiging","27124225","0","23","16","0")))))

Thanks in advance
Greetings,
Vierri

A: //Use the cURL setting to put the result into a variable rather than printing it
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

//store the result rather than print (as we set CURLOPT_RETURNTRANSFER)
$result = curl_exec($curl);
if ( $result === false ){
    //something went wrong, handle the error
}

//evaluate the array result and store it. (Please don't use this line in production code)
//as the $result string is from a untrusted source
eval('$array = '.$result.';');

//then you can, for example, get a list of the types
$types = $array[0]['RESULT']['TYPES'];

//or some keys
$keys = array_keys($array[0]['RESULT']);

The above code is dangerous and probably shouldn't be used as it is. They could put anything nasty in the response and you would evaluate it (the eval line) which could do bad things to your server. I would check if they have a better API that doesn't send responses in that format. (json or XML would be better)
If not you may want to considerer manually parsing the response array rather than using eval

A: To get all keys and values:
$server_output = curl_exec($curl);
var_dump($server_output);

To just get a list of keys:
$server_output = curl_exec($curl);
ksort($server_output);
foreach ( $server_output AS $key => $val ) {
  echo "$key\n";
}


text: Q: phonegap desktop app connect to my laptop's server Hi I am using the phonegap desktop app to make hybrid iphone apps. I had my app download on my iphone device but it can't connect to my localhost on my laptop becausue they are two different machines. I want to know how to connect to my laptop's local server from my actual iphone device. Don't give me answers if you don't actually know if it works.


text:
Q: How to retrieve checkboxes values in jQuery How to use jQuery to get the checked checkboxes values, and put it into a textarea immediately?
Just like this code:

      <input type="checkbox" value="one_name" checked>
      <input type="checkbox" value="one_name1">
      <input type="checkbox" value="one_name2">

    <textarea id="t"></textarea>

If the id="c_d" is updated by Ajax, the below of altCognito's code doesn't work. Is there any good solution?

A: Thanks altCognito, your solution helped. We can also do this by using name of the checkboxes:
function updateTextArea() {
   var allVals = [];
   $('[name=chkbox]:checked').each(function() {
      allVals.push($(this).val());
   });
   $('#t').val(allVals)
}
$(function() {
    $('#c_b input').click(updateTextArea);
    updateTextArea();
});

A: Your question is quite vague but I think this is what you need:
$(function() {
    $('input[type="checkbox"]').bind('click',function() {
        if($(this).is(':checked')) {
            $('#some_textarea').html($(this).val());
         }
   });
});

Edit: Oh, okay.. there you go... You didn't have the HTML up before. Anyways, yeah, I thought you meant to put the value in a textarea when it gets clicked. If you want the checked checkboxes' values to be put into the textarea (maybe with a nice comma-seperation) on page load it would be as simple as:
$(function() {
    $('#c_b input[type="checkbox"]:checked').each(function() {
        $('#t').append(', '+$(this).val());
    });
});

Edit 2 As people have done, you can also do this to shortcut the lengthy selector I wrote:
$('#c_b :checkbox:checked').each(function() {
    $('#t').append(', '+$(this).val());
});

... I totally forgot about that shortcut. ;)

A: The following may be useful since I got here looking for a slightly different solution. My script needed to automatically loop through input elements and had to return their values (for jQuery.post() function), the problem was with checkboxes returning their values regardless of checked status. This was my solution:
jQuery.fn.input_val = function(){

    if(jQuery(this).is("input[type=checkbox]")) {
        if(jQuery(this).is(":checked")) {
            return jQuery(this).val();
        } else {
            return false;
        }
    } else {
        return jQuery(this).val();
    }
};

Usage:
jQuery(".element").input_val();

If the given input field is a checkbox, the input_val function only returns a value if its checked.  For all other elements, the value is returned regardless of checked status.

A: Here's an alternative in case you need to save the value to a variable:
var _t = $('#c_b :checkbox:checked').map(function() {
    return $(this).val();
});
$('#t').append(_t.join(','));

(map() returns an array, which I find handier than the text in textarea).

A: Here's one that works (see the example):
 function updateTextArea() {
     var allVals = [];
     $('#c_b :checked').each(function() {
       allVals.push($(this).val());
     });
     $('#t').val(allVals);
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });

Update
Some number of months later another question was asked in regards to how to keep the above working if the ID changes. Well, the solution boils down to mapping the updateTextArea function into something generic that uses CSS classes, and to use the live function to monitor the DOM for those changes.

A: $(document).ready(function() {
  $(':checkbox').click(function() {
    var cObj = $(this);
    var cVal = cObj.val();
    var tObj = $('#t');
    var tVal = tObj.val();
    if (cObj.attr("checked")) {
      tVal = tVal + "," + cVal;
      $('#t').attr("value", tVal);
    } else {
      //TODO remove unchecked value.
    }
  });
});

A:  function updateTextArea() {
     var allVals = $('#c_b :checked').map(function() {
       return $(this).val();
     }).get();
     $('#t').val(allVals)
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });

A: $("#t").text($("#cb").find(":checked").val())

A: Anyway, you probably need something like this:
 var val = $('#c_b :checkbox').is(':checked').val();
 $('#t').val( val );

This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'.
Note that in your example code you should put the checkboxes in a form.

A: A much easier and shorted way which I am using to accomplish the same, using answer from another post, is like this:
var checkedCities = $('input[name=city]:checked').map(function() {
    return this.value;
}).get();

Originally the cities are retrieved from a MySQL database, and looped in PHP while loop:
while ($data = mysql_fetch_assoc($all_cities)) {
<input class="city" name="city" id="<?php echo $data['city_name']; ?>" type="checkbox" value="<?php echo $data['city_id']; ?>" /><?php echo $data['city_name']; ?>

<?php } ?>

Now, using the above jQuery code, I get all the city_id values, and submit back to the database using $.get(...)
This has made my life so easy since now the code is fully dynamic. In order to add more cities, all I need to do is to add more cities in my database, and no worries on PHP or jQuery end.

A: You can also return all selected checkboxes value in comma separated string.
This will also make it easier for you when you send it as a parameter to SQL
Here is a sample that return all selected checkboxes values that have the name "chkboxName" in comma separate string
And here is the javascript
function showSelectedValues()
{
  alert($("input[name=chkboxName]:checked").map(function () {
    return this.value;
  }).get().join(","));
}

Here is the HTML sample

   <input name="chkboxName" type="checkbox" value="one_name" checked>
   <input name="chkboxName" type="checkbox" value="one_name1">
   <input name="chkboxName" type="checkbox" value="one_name2">

A: If you want to insert the value of any checkbox immediately as it is being checked then this should work for you:
$(":checkbox").click(function(){
  $("#id").text(this.value)
})

A: I have had a similar problem and this is how i solved it using the examples above:
 $(".ms-drop").click(function () {
        $(function showSelectedValues() {
            alert($(".ms-drop input[type=checkbox]:checked").map(
               function () { return this.value; }).get().join(","));
        });
    });

A: Try this one..
var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);


text:
Q: How to echo a MSSQL datetime field $row into PHP I'm trying to create a simple table displaying data from June 2019, however i'm having trouble getting the MSSQL datetime row to eacho out properly. Initially it broke my code and was blank, then i tried using the date() strtotime php function, which now just shows 31 01 1970 for all columns which is incorrect.
Here's a example of the input 2016-07-04 00:00:00.000
Below is my code.
    <?php
$serverName = "SQL,1433";
$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo );

$sql = "SELECT TOP 1 * FROM [all sales data]";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
?>

                    <?php echo $row['Order Point Account'];?>
                    <?php echo $row['Analysis Category'];?>
                    <?php echo $row['Branch Code'];?>
                    <?php echo date("d m Y", strtotime($row->date));?>
                    <?php echo $row['Product Discount Group'];?>
                    <?php echo $row['End Product Cost of Sale'];?>
                    <?php echo $row['End Product Other Value'];?>
                    <?php echo $row['End Product Sales Value'];?>
                    <?php echo $row['End Product Analysis Quantity'];?>
                    <?php echo $row['Invoice Account'];?>
                    <?php echo $row['Magic Number'];?>
                    <?php echo $row['Order Number'];?>
                    <?php echo $row['PAC Level 1'];?>
                    <?php echo $row['PAC Level 2'];?>
                    <?php echo $row['PAC Level 3'];?>
                    <?php echo $row['PAC Level 4'];?>
                    <?php echo $row['Product Code'];?>
                    <?php echo $row['Salesman 1'];?>
                    <?php echo $row['Statement Account'];?>
                    <?php echo $row['Supplier Account'];?>
                    <?php echo $row['Contact']?>
                    <?php echo $row['Order Source'];?>
                    <?php echo $row['User'];?>
                    <?php echo $row['Customer Order No'];?>

            <?php
            }
            ?>

below is the vardump

object(DateTime)#1 (3) { ["date"]=> string(26) "2016-07-04 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/London" }

Here's the result of print_r($row);

Array ( [Order Point Account] =>  [Analysis Category] => AD [Branch Code] => 100 [Transaction Date] => DateTime Object ( [date] => 2016-07-04 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/London ) [Product Discount Group] =>  [End Product Cost of Sale] => 165.19999694824 [End Product Other Value] => 165.2 [End Product Sales Value] => 369.60000610352 [End Product Analysis Quantity] => 1 [Invoice Account] =>  [Magic Number] => 800713 [Sales Order Line Number] => [Order Number] => 319651 [PAC Level 1] => d [PAC Level 2] => dLB [PAC Level 3] => dLB01 [PAC Level 4] => dLB0106 [Product Code] =>  [Salesman 1] => 9500 [Statement Account] =>  [Supplier Account] =>  [Contact] => fax [Order Source] => FAX [User] =>  [Customer Order No] =>  )

Any ideas what i'm doing wrong to get this data to display correctly?
Many thanks!

A: There are 4 issues in your code:
Issue 1:
You have typo here $row,[Transaction Date].
Issue 2:
Your column name is date not Transaction Date
Issue 3:
Your response in object form not in array format.
Issue 4:
You are using t in date format, which return Number of days in the given month
<?php echo date("t m Y", strtotime($row,['Transaction Date']));?>

Should be:
<?php echo date("d m Y", strtotime($row->date));?>

PHP Manual


text:
Q: Javascript key event prohibits click event temporarily I am having a weird little issue which seems to be restricted to Windows(Edge, IE, Firefox, Chrome & Opera). I have tested it under Windows 10 x64. After a key{up,down,press} event, the click event seems to be temporarily disabled. Anyone knows how I can fix this?
JSFiddle: https://jsfiddle.net/b4s1pqe7/1/
// add event listener to table
function callEvent(e) {
    console.log(Date.now() + " " + e.type);
}

document.addEventListener("click", callEvent);
document.addEventListener("keyup", callEvent);

How To:

*

*Open your console log in your browser

*Press a key on your keyboard

*Start clicking furiously in the HTML part of the Fiddle.

*Note that click events temporarily do not show up

When I open it in a browser under Linux (tested with Firefox) the event is not temporarily disabled. @itsgoingdown tested it under Windows 7 SP 1 with Chrome and it also does not have this issue.
Thanks in advance!


text:
Q: invisible columns in oracle 12c view One of the topics on the Oracle 1Z0-047 sql expert exam is "Create simple and complex views with visible/invisible columns". I can create tables with invisible columns, I can create a view containing those invisible columns, but I cannot find the syntax to make those columns invisible in the resulting view. Oracle documentation mentions visible/invisible in the Database SQL language reference "Create View" page but gives no specific example and my attempt at following their squiggly diagram failed:
create or replace view jl_book_author as
    select title, b.isbn isbn invisible, lname, fname
        from jl_books b
            join jl_bookauthor a on b.isbn = a.isbn
            join jl_author r on a.authorid = r.authorid
         order by title, lname, fname;
ERROR at line 3:
ORA-00923: FROM keyword not found where expected

Any idea how to do make a column of a view invisible and why I would want to do this other than to pass the exam?

A: This works. The only way to specify "INVISIBLE" is if you're using column aliases in the view. The aliases, constraints and INVISIBLE/VISIBLE modifiers need to be in parenthesis between the view name and keyword "AS".
create or replace view jl_book_author (tl, bn INVISIBLE, al, af) as
    select title, b.isbn, lname, fname
        from jl_books b
            join jl_bookauthor a on b.isbn = a.isbn
            join jl_author r on a.authorid = r.authorid
         order by title, lname, fname;

A:
"why I would want to do this other than to pass the exam?"

You use the INVISIBLE clause, as stated in the Oracle SQL Reference CREATE TABLE, to add columns to any table, without having code that includes wildcard SELECT * statements add to it haphazardly.
Therefore very useful for adding columns to tables that you wouldnt want legacy code to casually manipulate.
For a fuller explanation and examples see the article ASK TOM: technology from the  MAY/JUNE 2014 edition of Oracle Magazine.


text:
Q: jQuery trigger click mobile Safari (iPad) I have stumbled upon a bug in Safari on iPad.
$('#next_proj a').trigger('click');

.. does not seems to click on the actual link.
Any clues?

A: I got this to work by doing this...
var el = $('#next_proj a').get(0);
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
el.dispatchEvent(evt);

Hope it helps...

A: It may not be a bug. My guess is that they did not want to allow javascript emulated user clicks.

A: Have you tried triggering a touch event instead of a click event?  Not sure how you would implement in jquery - but it isn't too complicated in plain js
function simulateEvent() {
  var e = document.createEvent('HTMLEvents');
  e.initEvent('touchstart',true, true);
  document.dispatchEvent(e);
}


text:
Q: Putting balls into boxes where balls and/or boxes are distinguishable Part (a) How many ways are there to put $4$ balls into $3$ boxes, given that the balls are not distinguished and neither are the boxes?
Part (b) How many ways are there to put $2$ white balls and $2$ black balls into $3$ boxes, given that balls of the same color are indistinguishable, but the boxes are distinguishable?
I am not sure how distinguished and indistinguishable makes a difference in the question and I have no clue how to do this. Any help is appreciated.

A: For part (a), these are (unordered) partitions of $4$ into $3$ parts where parts can be $0.$ To ensure that you hit all possibilities, tackle three cases: exactly $2,1,$ or $0$ parts with nothing. There cannot be three parts with nothing. If exactly $2$ parts have nothing, the only possibility is $4+0+0.$ If exactly $1$ part has nothing, the possibilities are $3+1+0$ and $2+2+0.$ If exactly $0$ parts have nothing, then each part has at least $1.$ This means the remaining one gets assigned somewhere and the only possibility is $2+1+1.$ So the answer is $4.$
For the second part, treat white balls and black balls separately. Doing either one will let you square it to get the answer thanks to the multiplication principle. For white balls, there are $$\binom{2+3-1}{3-1}=\binom{4}{2}=6$$ possibilities, so the answer is $6^2=36.$ This is using sticks and stones.


text:
Q: How to call Socket Send and Receive multiple times without closing the socket? I'm using the .NET Socket class.
Basically my program is to send XML commands via TCP to my server (running some 3rd party services), and it will send back an XML response.
What I wanted to do is to send and receive multiple times without closing the socket, because the server seems to slow down if I open and close the socket too many times in a short period of time.
Stripped down version of my code:
//Connects to server
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint("123.123.123.123", 8199);
socket.Connect(ipe);

//Send my message
int sent = sock.Send(buffer, buffer.Length, SocketFlags.None); //buffer contains my XML data

//Receives respond from server
byte[] buf = new byte[65536];
int ret = socket.Receive(buffer, 0, 65536, SocketFlags.None);

//Send my message again without closing the socket
sent = sock.Send(buffer, buffer.Length, SocketFlags.None); //buffer contains my XML data

//Receives respond from server failed..
ret = socket.Receive(buffer, 0, 65536, SocketFlags.None);

It send/receive works the first time, but not the second time. The second time it throws an exception "An existing connection was forcibly closed by the remote host". What do I need to do before I can issue another send/receive?
Thank you so much for reading.

A: The problem might be these

*

*other endpoint might have closed the connection

*your Receive method is blocking since no data is sent by the other client

The server might have closed the connection since you might have a send an invalid packet. check whether the data you are sending is valid. Debug or have a tcp/ip packet montior in the server side and examine the packet you receive.


text:
Q: Rewrite request in subdirectory after rewriting into that subdirectory I have following file structure in my server:
/
    source/             # source PHP files (not accessible)
    public/             # publicly accessible files (media)
        .htaccess       # second level htaccess to rewrite path into variable
        index.php       # request collector
    .htaccess           # first level htaccess to redirect flow into public dir

In first level htaccess I have rewrite rule moves flow into "public" directory.
RewriteRule ^(?!public/).*$ public/$0 [L,NC]

"public/.htaccess" contains following code:
RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{QUERY_STRING} !index.php
RewriteRule ^(.*)$ index.php/$1 [QSA,L]

So if requesting existing file it is served. Otherwise request is rewrited like "example.com/namespace/controller/action?var=blah" to "example.com/index.php/namespace/controller/action?var=blah"
And that request should be handled by "public/index.php". However it seems that multiple rewriting is not allowed. Am I right? Or maybe I am making something wrong. I have to admit I can not understand mod_rewrite.


text:
Q: one-to-many relation with mongodb? I have two schemas called HotelSchema and PricelineSchema:
// schemas.js
const mongoose = require("mongoose")

module.exports.HotelSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    index: true
  },
  accommodation_type: {
    type: String,
    enum: ["هتل", "هتل آپارتمان", "مهمانسرا"],
    index: true
  },
  pricelines: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Priceline' }]
})

module.exports.PricelineSchema = mongoose.Schema({
  source: {
    type: String,
    required: true,
    index: true
  },
  price: {
    type: String,
    required: true,
    index: true
  },
  hotel: { type: mongoose.Schema.Types.ObjectId, ref: "Hotel" }
})

and accordingly two models called Hotel and Priceline:
// models.js
const mongoose = require("mongoose")
const {HotelSchema, PricelineSchema} = require("./schemas")

module.exports.Priceline = mongoose.model("Priceline", PricelineSchema)
module.exports.Hotel = mongoose.model("Hotel", HotelSchema)

story short I have an endpoint that in which async.waterfall used:
const async = require("async")
const bodyParser = require("body-parser")
const app = express()
app.use(bodyParser.json())

const { Hotel, Priceline } = require("./models")

function buildPricelineMany (arr, hotel) {
  const pricelines = []
  for (let priceline of arr) {
    pricelines.push(
      new Priceline({
        source: priceline.source,
        price: priceline.price,
        hotel: hotel._id
      })
    )
  }
  return pricelines
}

app.put("/hotels", (req, res) => {
  async.waterfall(
    [
      function (callback) {
        Hotel.findOne({ name: req.body.name })
          .populate("pricelines")
          .exec(function (err, hotel) {
            if (err) return callback(hotel)
            return callback(null, hotel)
          })
      },
      function (hotel, callback) {
        const pricelines = buildPricelineMany(req.body.pricelines, hotel)
        Priceline.insertMany(pricelines)
          .then(docs => callback(null, hotel, docs))
          .catch(err => {
            return callback(err)
          })
      }
    ],
    function (error, hotel, pricelines) {
      if (error) {
        res.status(500).jsonp({ errors: [error] })
        return
      }

      res.status(200).jsonp(hotel)
    }
  )
})

app.listen(8080, "localhost")

when I call populate('pricelines') the result is an empty array and I don't know why?!
{
    "pricelines": [],
    "_id": "5b0569dc1b99f37385c4d975",
    "name": "baz",
    "accommodation_type": "هتل",
    "__v": 0
}

The way that I created one-to-many relation is exactly as documented http://mongoosejs.com/docs/populate.html.
Here's my collection:
> db.pricelines.find({})
{ "_id" : ObjectId("5b058bf9e87a0e7ae7f6bd47"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfae87a0e7ae7f6bd48"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfae87a0e7ae7f6bd49"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfae87a0e7ae7f6bd4a"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfbe87a0e7ae7f6bd4b"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfbe87a0e7ae7f6bd4c"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfbe87a0e7ae7f6bd4d"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfbe87a0e7ae7f6bd4e"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfbe87a0e7ae7f6bd4f"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfbe87a0e7ae7f6bd50"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
{ "_id" : ObjectId("5b058bfbe87a0e7ae7f6bd51"), "source" : "jabama", "price" : "1231231", "hotel" : ObjectId("5b058beee87a0e7ae7f6bd42"), "__v" : 0 }
>
> db.hotels.find({})
{ "_id" : ObjectId("5b058beee87a0e7ae7f6bd42"), "name" : "baz", "accommodation_type" : "هتل", "pricelines" : [ ], "__v" : 0 }
{ "_id" : ObjectId("5b058bf6e87a0e7ae7f6bd46"), "name" : "استقلال", "accommodation_type" : "هتل", "pricelines" : [ ], "__v" : 0 }

A: Well populate is now history... You should use $lookup to populate the _id of the hotel in the hotel field of pricelines
Here is the example to do (mongodb version 3.6)
db.collection.aggregate([
  { "$match": {  "name": req.body.name } },
  { "$lookup": {
    "from": Priceline.collection.name,
    "let": { "hotel_id": "$_id" },
    "pipeline": [
       { "$match": { "$expr": { "$eq": [ "$hotel", "$$hotel_id" ] } } }
     ],
     "as": "pricelines"
  }},
 ])

and if you have mongodb version below then 3.6 then you can use this
 db.collection.aggregate([
  { "$match": {  "name": req.body.name } },
  { "$lookup": {
    "from": Priceline.collection.name,
    "localField": "_id",
    "foreignField": "hotel",
    "as": "pricelines"
  }},
 ])

One of the best use of $lookup is you don't need to put array of _id into the collections (for populate) which reduces the collection size

A: Have you tried to Populate after you receive the object? Like this I mean:
...
.exec(function (err, hotel) {
   Priceline.populate(hotel, {path:'pricelines'}, function (err, populatedHotels){
        //do your things here
    })
});
...

I recently stumbled upon this and I think it might help.
Let me know


text:
Q: Specify citation style in footnotes (point at the end of the citation) I'm trying to modify the style of citations in footnotes, specifically adding a point at the end of the citation.
I use the biblatex-chicago package for my bibliography and here is a MWE of my document setup:
\documentclass{scrbook}

\usepackage[utf8]{inputenc}

\usepackage[main=british, ngerman]{babel}
\usepackage[babel]{csquotes}

\usepackage[backend=biber,
            bibencoding=inputenc,
            notes,
            isbn=false,
            noibid=true,
            doi=only,
            ]{biblatex-chicago}

\begin{filecontents}{bibliography.bib}
@article{url,
  url = {http://www.example.de},
  author = {Surname, Prename},
  title = {An article which has a URL},
  journaltitle = {Bibliography Styles in LaTeX},
  date = {2017}
}

@article{no_url_1,
  author = {Surname, Prename},
  title = {An article which has no URL},
  journaltitle = {Bibliography Styles in LaTeX},
  date = {2017}
}

@article{no_url_2,
  author = {Surname, Prename},
  title = {An article which has no URL},
  journaltitle = {Bibliography Styles in LaTeX},
  date = {2017}
}
\end{filecontents}

\addbibresource{bibliography.bib}

\begin{document}
Entry with url.\footnote{\cite{url}}
Entry without url.\footnote{\cite{no_url_1}}
Entry without url but page reference.\footnote{\cite[5]{no_url_2}}
\end{document}

The result looks like this:

I made the distinction between to entries with and without url because you can see the trailing comma in the second entry. Also I created two bib entries with no url because after I reference an entry the first time, there will be a short version in the footnote.
My goal would be to have a point at the end of each footnote citation and therefore replace the trailing comma as well.
Is there a way to change the style and do this programatically (without having to write the style by myself) or do I have to insert the point manually on each entry like this:
\footnote{\cite{id}.}

Thanks for any help in advance.
[Edit]
The given document is in a fairly final stage and I'm trying to consult with the author to fix some problems. There are quite a few long footnotes with many cites in it mixed up with text. So, changing the command like @gusbrs suggested would be very hard (although possible).
I'm still hoping there is another way.

A: Of course the best solution would be to use \footcite.
But we can also let \cite end with a full stop if it is called in a footnote.
\DeclareCiteCommand{\cite}
  {\usebibmacro{prenote}}
  {\usebibmacro{citeindex}%
   \usebibmacro{cite}}
  {\multicitedelim}
  {\usebibmacro{cite:postnote}\iffootnote{\addperiod}{}}

The problematic comma in the second footnote is caused by commas in cjournal+issue+year+pages that don't use \setunit.
\makeatletter
\renewbibmacro*{cjournal+issue+year+pages}{%
  \usebibmacro{cjournal+ser+vol+num}%
  \ifboolexpr{% 16th ed.
    test {\iffieldundef{issue}}%
    and
    test {\iffieldundef{year}}%
    and
    not togl {cms@switchdates}%
  }%
  {\iffieldundef{number}%
    {\ifthenelse{\iffieldundef{pagination}\AND%
        \iffieldundef{bookpagination}}%
      {\setunit{\postvolpunct}}%
      {\setunit{\addcolon\addspace}}}%
    {\setunit{\addcomma\addspace}}}%<--- HERE
  {\ifthenelse{\iffieldundef{volume}\AND\iffieldundef{number}}% 16th ed.
    {\newcunit%
      \iffieldundef{issue}%
      {\usebibmacro{number+or+month}}%
      {\printfield{issue}%
        \setunit{\addspace}%
        \usebibmacro{cmsyear}}%
      \setunit{\addcomma\addspace}}%<--- HERE
    {\setunit{\addspace}%
    \printtext[parens]{% parens is the default here
      \iffieldundef{issue}%
      {\usebibmacro{number+or+month}}%
      {\printfield{issue}%
        \setunit{\addspace}%
        \usebibmacro{cmsyear}}}}}}
\makeatother

The two changes are marked with HERE.


text:
Q: Syntax highlighting in VS 2010 For some reason my syntax error highlighting has disappeared from Visual Studio 2010. For example, this shows no error until I try to build this...
String userName = Request.ServerVariables("LOGON_USER");
fW4YQHKRHAENKR!!!;

A: http://msdn.microsoft.com/en-us/library/ms247075.aspx
Edit
As per comment, I've added the text from the link:
How to: Reset Your Settings
Visual Studio 2010 Other Versions 19 out of 25 rated this helpful - Rate this topic
You can reset the integrated development environment (IDE) to a previous state using the Import and Export Settings wizard. All settings and categories are applied by default; if you want to specify which settings to change, use the option Import selected environment settings. For more information, see How to: Share Settings Between Computers or Visual Studio Versions.
To reset your settings
On the Tools menu, click Import and Export Settings.
On the Welcome to the Import and Export Settings Wizard page, click Reset all settings and then click Next.
If you want to save your current settings combination, click Yes, save my current settings, specify a file name, and then click Next.
—or—
If you want to delete your current settings combination, choose No, just reset settings, overwriting my current settings, and then click Next. This option does not delete default settings, which will still be available the next time you use the wizard.
In Which collection of settings do you want to reset to, select a settings collection from the list.
Click Finish.
The Reset Complete page alerts you to any problems encountered during the reset.

A: did you install any plugin/addin to the visual studio recently? A malfunctioning plugin or addon could be the cause  of this problem.


text:
Q: android tv -Reloading adapter data I want to re-load some of the rows data in a browse fragment.
Basically I want to reset the adapter data without causing a flash like effect in the browse fragment. Any idea how it can be done?
Something like notifyDataSetChanged() in list view.
Thanx

A: This will refresh data without losing current position:
for (int i = 0; i < mAdapter.size(); i++) {
    ListRow listRow = ((ListRow) mAdapter.get(i));
    ArrayObjectAdapter listRowAdapter = ((ArrayObjectAdapter) listRow.getAdapter());
    if (listRowAdapter.size() > 0) {
        listRowAdapter.notifyArrayItemRangeChanged(0, listRowAdapter.size());
    }
}

A: I answered something similar in this question:
Dynamically add more cards in a list Row android TV leanback
I'll copy my answer from there. Hopefully this helps.
To add items to a presenter;
CardPresenter channelCardPresenter = new CardPresenter();
ArrayObjectAdapter channelRowAdapter = new ArrayObjectAdapter(channelCardPresenter);
channelRowAdapter.add(new Movie("Movie Title"));
HeaderItem header = new HeaderItem(0, "My Channels");
mRowsAdapter.add(new ListRow(header, channelRowAdapter));

Of course this may only work for the first time you're creating the UI. Future times may not do this. In my app, CumulusTV, I create a method that will be called each time I want to do a full redraw of the app:
public void refreshUI() {
    prepareBackgroundManager();
    setupUIElements();
    loadRows(); //Generate and populate all the rows
    setupEventListeners();
}

A: You can create your own adapter and add a new replaceAll() method.
public void replaceAll(Collection items){
 int itemsCount = items.size();
 if (itemsCount == 0){
    return;
 }
 mItems.clear();
 mItems.addAll(index, items);
 notifyItemRangeChanged(0, itemsCount);
}

complete source:link

A: Here's my kotlin version of @ewilly's answer, implementing only replaceAll which I use to both initially populate and incrementally update the list.
class RefreshableArrayObjectAdapter(presenter: Presenter): ObjectAdapter(presenter) {
    var items: ArrayList<Any> = arrayListOf()

    override fun isImmediateNotifySupported(): Boolean = true

    override fun size(): Int = items.size

    override fun get(position: Int): Any = items[position]

    fun replaceAll(list: Collection<Any>) {
        items.clear()
        items.addAll(0, list)
        notifyChanged()
    }
}

A:   /**
 * Notify that the content of a range of items changed. Note that this is
 * not same as items being added or removed.
 *
 * @param positionStart The position of first item that has changed.
 * @param itemCount The count of how many items have changed.
 */
public void notifyArrayItemRangeChanged(int positionStart, int itemCount) {
    notifyItemRangeChanged(positionStart, itemCount);
}

Notify that the content of a range of items changed. Note that this is
 * not same as items being added or removed.
if you want add or remove item,please try this:
1.mRowsAdapter.clear();
2.mRowsApdapter.addAll();


text:
Q: cannot execute elastix binary file I am trying to run a binary file (./elastix) in the terminal but I am getting the following error
/Users/tony/Desktop/elastix-4.9/bin/elastix: cannot execute binary file

When I type the command file elastix I get
elastix: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), dynamically linked, interpreter /lib64/l, for GNU/Linux 2.6.32, BuildID[sha1]=d13c10b0fe409ac66c2733ea6efb1cfb175b4070, not stripped

and when I type uname -m I get:
x86_64

So it seems like my system and the file are compatible which is why I'm confused. Perhaps it has to do with not striped?

A: From your /Users/tony path, I'm guessing you're trying to do this on a Mac. The binary you have is a Linux binary and won't work on your macOS system.
You need to either find a macOS binary, or run your Linux binary in a Linux VM, or build your own macOS binary.


text:
Q: discord.js Cannot read property 'guild' of undefined I've already looked through a few tutorials and pages, but couldn't find a working version to check whether the author has the appropriate role.
My last tryed code:
const fs = require('fs');
const Discord = require('discord.js');
const {
  token
} = require('./config.json');

const client = new Discord.Client();

//functions
function loadServer() {
  server = getJ('./server.json');
}

function abnahme(message){
let charRole = message.guild.roles.find("name", "Character-Abnehmer");

if (message.content == 'accepted' && message.member.roles.has(charRole)) {
//code....
}else {
        return;
      }
}

//run

client.once('ready', () => {
  console.log('Ready!');
});

//events
loadServer();
client.on('message', message => {
if (message.content.startsWith(server.prefix)) {

const args = message.content.slice(server.prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
    message.channel.send(`\`command: ${command} args: ${args}\``);

      if(command == 'abnahme'){
        abnahme(message);
      }
  }

});

client.login(token);

Can someone give me an example of how I can just query the role?

A: The easiest way to see if a member has a role is with GuildMember.roles.cache.has().
Use this code
client.on('message', async msg => {
let memberHasRole = msg.member.roles.cache.has('role-id');
//true if member has the role, false if they don't
})


text:
Q: How to include rgb and grayscale images in CNN using tf.data? I am trying to use rgb images as input and grayscale images as label image based on this post. How can I modify the following code to define that the label images contain one channel?
# step 1
filenames = tf.constant(input_list)
labels = tf.constant(label_list)

# step 2: create a dataset returning slices of `filenames`
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))

# step 3: parse every image in the dataset using `map`
def _parse_function(filename, label):
    image_string = tf.io.read_file(filename)
    image_decoded = tf.image.decode_jpeg(image_string, channels=3)
    image = tf.cast(image_decoded, tf.float32)
    return image, label

dataset = dataset.map(_parse_function)
dataset = dataset.batch(2)

# step 4: create iterator and final input tensor
iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)
images, labels = iterator.get_next()

A: Use this function to load an image with a varying number of channels:
def _parse_function(filename, channels):
    image_string = tf.io.read_file(filename)
    image = tf.image.decode_jpeg(image_string, channels=channels)
    image = tf.image.convert_image_dtype(image, tf.float32)
    return image

Then:
dataset = dataset.map(lambda x, y:
    (
        _parse_function(x, channels=3),
        _parse_function(y, channels=1)
    )
)