Domain Name Routing Across Multiple Varying Servers

Question: How can you use one public IP address to host multiple domain names that span across multiple servers in your LAN?
Let's say I have 5 web servers, serving 5 different domain names, using 5 different server-side technologies, and I currently have 5 public IP addresses.
DNS is setup so that each of the 5 domain names are mapped to each of the respective public IPs, and the firewall has port-forwarders so all requests get forwarded to the respective internal ip-addresses of the correct server within the LAN.
How would I consolidate to using one IP instead of 5? I understand how  dynamic-dns works and if there was just one web-server I'd have no problems. However, since there are multiple web-server, using varying technologies, I'm not sure how to accomplish using only one public IP.
Is there a server (preferably Linux based) that I can send all requests to, that is capable of transparently routing each request to a specific internal IP+port based strictly on domain name within the request?
Comment: I know you prefer Linux, but if you have an IIS server in the mix you could use **URL Rewrite** and **Application Request Routing** to set it up as a flexible reverse proxy. I do this for several scenarios that include Apache web servers on Linux.
Answer: An Apache or Nginx reverse proxy would do.
Below is a simple example with nginx reverse proxy, including load balancing.
<code>http {
  upstream backend_server_2 {     # load balanced server block
     ip_hash;
     server 10.1.1.2:8080 weight=2;
     server 10.1.1.3:8080 weight=1;
  }

  server {
     listen public_ip:80;
     server_name example1.com;
     location / {
         proxy_pass http://10.1.1.1/;
     }
  }

  server {
     listen public_ip:80;
     server_name example2.com;
     location / {
         proxy_pass http://backend_server_2/;
     }
   }
}
</code>
Comment: How transparent is this solution? Will the webserver see only the original source address or will it see the Nginx address as the source address of the request? I'd like to handle this at a low enough networking layer, so the webserver is fooled into thinking it has received a request that has not passed through a proxy server. For example, I can imagine a firewall extension that analyzes the domain name in the packet before routing the packet to one of the web servers within the LAN.
Comment: Given solution is not a transparent proxy, so the client requests get modified at reverse proxy server (in Layer 3, Layer 4 & Layer 7 headers) before sending to back-end servers.

Next option for you is to use XFF header in reverse proxy, where original client IP is preserved as a layer 7 header information. However, L3 & L4 details will get changed while proxy-ing.
Comment: If you need to preserve original client's L3, L4 & L7 information, you can try something like HAProxy's proxy protocol (http://www.haproxy.org/download/1.8/doc/proxy-protocol.txt) or transparent mode. But this might offer limited proxy functionality, and requires changes in network architecture.
Answer: You could try setting up a Load Balancer with a Reverse Proxy.
It's basically a server where all the requests goes to, but it does not process the requests; rather, it only sends the request to be processed by one of the servers behind it.
There are different algorithms to send requests to the right servers in order not to workload one of the servers more than others, but for basic setups, even making it random or sending requests to one server at one time could work. Since who's going to make the request to the actual server is Nginx, you'll lose the original user's IP address. To make it available again, you'll have to set up Nginx and your servers to pass the original IP address as a HTTP header (such as X-Forwarded-For).
Comment: The source IP changing is an issue. Each of the webservers log source IPs for stat purposes, which would be meaningless if each request's source IP is that of the internal "load balancer / reverse proxy server". Are you aware of anything that operates at a lower networking layer. For example, theoretically I can image a firewall module that route IP traffic by extracting the domain name out of the packet. Such a strategy would be transparent to the web server; the original source IP would be preserved and the web server could just respond to the request like normal.
Comment: Use `proxy_set_header X-Forwarded-For $http_x_forwarded_for` in your Nginx config and the servers behind your reverse proxy will be able to get the source IP address on the X-Forwarded-For header.
Answer: Sure you could handle it with a load balancer. But the appropriate way is to use Server Name Indication (SNI). Don't  reinvent the wheel, especially in network/internet questions...


How do I compute the following probability?

Question: I have the following problem:

Let $X,Y$ be two random variables which are indipendent and uniformly distributed on $[0,1]$. I need to compute $\Bbb{P}\left(Y\leq \frac{X}{2}\right)$

Since they are uniformly distributed I know that their density maps are $\Bbb{1}_{[0,1]}$. Then I thought that $$\Bbb{P}\left(Y\leq \frac{X}{2}\right)=\Bbb{P}(2Y-X\leq 0)=F_{2Y-X}(0)$$. But I'm not sure if this works.
Could maybe someone help me?
Comment: If $X$ and $Y$ are independent, $\mathbb P\{(X,Y)\in A\}=\iint_A f_X(x)f_Y(y)\,\mathrm d x\,\mathrm d y$
Comment: @Surb Ah so you mean that I first need to find $A$ geometrically?
Answer: I think your approach is correct, just compute the area of $\{(x,y)\in\mathbb{R}^2:2y-x\leq0\}\cap[0,1]^2$.
If you want to use integration, you would have to compute $\int_0^1\int_0^{\frac{x}{2}}dydx$.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Sure so I know this possibility but I wanted to compute it with integrals
Comment: I recently added the corresponding integrals.


Is this diminished II7 or VII in harmonic minor?

Question: 1: []
Hi,
I have some problems to analyze 2nd and 4th bar chords in this example in A minor (harmonic). For my understanding, 2nd bar chord can be either diminished chord in ii or vii. What about the first chord in 4th bar (before v chord), is it ii or vii chord? Which diminished chords are used here in this simple chord progression? Thanks
Comment: Hi everyone, This is not homework just my analysis of a song. Treble clef on top, bass clef on bottom. No accidentals so it's in A Minor. Chord labels should be in smaller lowercase as it's minor - sorry about that.
Comment: @Dekkadeci, My example is a song from the soundtrack of Nier Automata (Grandma - Destruction).
Comment: Hi Janta. Is this homework for a class?
Comment: What are the clefs for these staves?
Comment: @ToddWilcox - I would hazard a guess that it's treble clef on top and bass clef underneath based on the existing chord analysis, but there are definitely still inconsistencies in the less disputed chord labels in that case (especially the 2nd chord of Bar 4, claimed to be V).
Comment: Also, what key signature is the example in? (I'd hazard a guess that it has no accidentals and your example is in A minor, but that doesn't quite explain how all your tonic chords are labelled I instead of i.)
Comment: What song is this from? It looks like it has a deceptively fast harmonic rhythm right now - i.e. I'd hazard a guess that Bar 4 might even change chords every *8th note* for more than half of it.
Comment: An answer might be more helpful to you if you added what you feel is the _harmonic reduction_ of the passage. Bar 2 has `B D G#` on all strong downbeats which is reasonable for  a `viio6`. The only `B` or `D` in the bass in bar 4 is the `B` on up beat of beat 3 which does not make a strong case for a `iio` chord.
Comment: @MichaelCurtis - A previous edit had Bars 2 and 4 split into 2 chords each, one per every 2 beats. Note my earlier comments doubting that this interpretation was correct.
Comment: @Dekkadeci, OK, but I just want to see how the OP reduces whatever version they are working with. Essentially, their reduction is their analysis. How they perceive that is really the heart of the matter.
Comment: @Michael Curtis, What does harmonic reduction means? I'm just a beginner and still learning the basics of harmony and voice leading. I tend to over-analyze every possible chord within a bar so maybe harmonic reduction is opposite of that?
Comment: @Janta, look at the Bach C major prelude and E minor prelude illustrations on this page https://en.wikipedia.org/wiki/Voice_leading, the staves under the original scores are harmonic reductions.
Comment: @Janta your comment "I tend to over-analyze every possible chord within a bar so maybe harmonic reduction is opposite of that?" more or less, yes, that is the idea. In your example, if you look to every beat or every eighth note moment for chords, it mixes up the harmonic level, you might say harmonic rhythm level, with the figuration details.
Answer: I would analyze the entire second measure as a V7 chord. Since the first and third measures are both I chords, analyzing m. 2 as V7 gives a clear accounting of the harmonic motion. The first two beats of that measure comprise a vii dim chord in second inversion, but calling it such doesn't significantly change the overall analysis of Tonic – Dominant – Tonic.
I would call m. 4 V7 for the same reason — the micro-details don't change the overall analysis.

For the purpose of attempting to label each chord, then the downbeat of m. 2 is vii dim in first inversion, and the downbeat of m. 4 is ii halfdim7 in third inversion and with the chordal fifth omitted, which is standard.
Comment: Thank you for your answer. So if the harmonic progression is clear like I - V7 here, then you don't have to label each possible chord within a measure?
Comment: @Janta That's right.
Answer: The bars are basically i (bar1) V (bar2) i (bar3) and V (bar4). There's nothing particular that changes the basic harmony in each of the four bars. Beats 1 and 3 (the strongest) all allude to those chords, except 3 in bar 4, which waits till beat 4.
A minor is a key; A harmonic minor is a scale.
Comment: Thanks, this makes sense. Now if I only knew when not to over-analyze every possible chord within a bar!
Answer: This isn't really an answer, the other answers give the basic analysis of the chords in your example. But I think you need to look into harmonic analysis and harmonic reduction. You may be trying to identify chords on too small a time scale - like every beat of even every eight note - but that is not always appropriate. Some related terms to read up on are harmonic rhythm, figuration, diminution, non-chord tones.
A harmonic analysis could look like the following where a simplified version of the music is given below the original score...

That is from https://en.wikipedia.org/wiki/Voice_leading
The arrows in that reduction may seem confusing, but they are trying to show something called a voice exchange. You can ignore them if it isn't clear.
Also, you can think of levels of harmonic action which distinguishes between top level, melodic particulars versus deeper, more abstracted harmonic design, like in this example from the textbook Kostka, Tonal Harmony...

From comments...

f a chord in A minor has tones B-D-F-G#, then can it be both iio7 (G# as 7th) and viio chord?

No. You want to read chords in thirds, identify chord roots, then identify inversions.
B-D-F-G# if you read that in thirds it will be G# B D F, so G# is the root and the chord is in first inversion from the B in bass. In Roman numeral analysis (RNA) that is Am: viio6/5.
For the diminished chord iio in minor, the basic triad is B D F. It is often in first inversion D F B, D in bass, RNA iio6.
When you get to that chord as a seventh chord things get a little tricky. The ii chord in major and the iio chord in minor are both subdominant function chords, they are not dominant chords. That has bearing on the seventh chord in minor.
The seventh chord spelling in A minor is B D F A. Notice the seventh above root B is an A. It's a base diminished triad plus a minor seventh. That chord is called a half diminished chord. The RNA symbol uses a slashed circle: iiø7. This is the seventh chord on root ii in minor. It often is in first inversion D F A B, iiø6/5.
You can lower the top tone of B D F A by a half step to B D F G#, but notice that in the key of A minor that change from A to G# is a move from tonic to leading tone scale degrees. That leading tone is what creates the dominant function viio6/5.
One half step may seem like a tiny change, but it's an important change. It's the difference between a subdominant function iiø7 chord and a dominant function viio7 chord!
If all this stuff about roots, inversions, function, etc. is not familiar, you probably need to get a good harmony textbook to learn the fundamentals of harmony.
Comment: Michael, thanks once again for your help. Your explanation provided the answer to my question!
Comment: Thank you Michael for providing a lot of helpful information.
Comment: You wrote earlier: "Bar 2 has B D G# on all strong downbeats which is reasonable for a viio6. The only B or D in the bass in bar 4 is the B on up beat of beat 3 which does not make a strong case for a iio chord." This makes sense although I'm still a bit confused with diminished chords in harmonic minor. If a chord in A minor has tones B-D-F-G#, then can it be both iio7 (G# as 7th) and viio chord? I guess there are no hard and fast rules and it all depends on context.
Comment: @Janta, I think I see where you may be having trouble. I added some more to my answer, because it's a long explanation.
Answer: Bar 1 is basically an Am chord.  So is bar 3.  Bar 2 includes a G♯ and all the on-the-beat notes are included in an E7 chord.  Accept the simple analysis!   Bar 4 is a little more complex, but it's still basically E7.
If the environment is A minor, and you find yourself playing E, G♯ and D notes, it's 99% sure there's no point in calling the chord anything but E7.    If the E is specifically omitted, it MIGHT be useful to call it G♯dim.   But, functionally, it's just another flavour of E7, the dominant of Am.
Comment: Thank you Laurence, I'm slowly but surely begin to believe the dominance of V chord!


Como criar novo elemento a partir de formulário input?

Question: Consegui criar um javascript que cria um novo elemento a partir do id do input de nome, porém quero também adicionar os elementos do input de valor e data, como eu faço?
Tentei copiar igual fiz com o nome:
var textoValor = document.getElementById('novoValor')
tr.textContent = textoValor.value;
Também gostaria de saber como fazer para resetar a tabela

var novoNome = document.getElementById('novoNome');
var novoValor = document.getElementById('novoValor');
var novaData = document.getElementById('novaData');

btnNovoCliente = document.getElementById('btnNovoCliente');

var tbody = document.getElementsByTagName("tbody")[0];

function adc() {
    document.getElementById("btnNovoCliente").addEventListener("click", function(){
        var cliente = document.getElementById('tbody');
        var textoNome = document.getElementById('novoNome');
        var tr = document.createElement('tr');

        tr.textContent = textoNome.value;

        cliente.appendChild(tr);

    });

}

window.addEventListener("load", adc);
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html {
    font-family: monospace;
    font-size: 16px;
    background-color: rgba(10, 5, 9, 0.233);
}

body {
    width: 90%;
    height: 90%;
    display: flex;
    flex-direction: column;
    font-family: monospace;
}

.left {
    background-color: gray;
    width: 350px;
    height: 270px;
    padding: 15px 30px;
    margin: 30px 30px;
}

.left form .formulario input {
    width: 275px;
    height: 30px;
    margin: 6px;
    padding: 10px;
}

.left form .btn {
    margin-top: 15px;
    display: flex;
    flex-direction: row;
    margin-left: -5px;
}

.left form .btn input {
    margin: 10px;
    width: 80px;
    height: 30px;
}

#btnResetar {
    background-color: rgb(187, 111, 111);
    font-weight: bolder;
    color: white;
}

.right {
    display: flex;
    flex-direction: column;
    width: 1440px;
    height: 900px;
}

.right table {
    border: 1px solid white;
    margin-left: 60px;
}
.right table thead tr th {
    border: 1px solid white;
    outline: solid white;
}
.right table thead tr th {
    margin-right: 100px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MyClients</title>
    <link rel="stylesheet" href="style.css">

            <form action="#">

                        Nome:

                        <input type="text" id="novoNome">

                        Valor:

                        <input type="text" id="novoValor">

                        Data:

                        <input type="text" id="novaData">

                    <input type="button" id=btnNovoCliente value="Criar">
                    <input type="button" id=btnNovoCancelar value="Cancelar">
                    <input type="button" id=btnResetar value="Resetar">

            </form>

                        Nome
                        Valor
                        Data

Answer: Fiz o uso do HTMLTableRowElement.insertCell() para inserir novas células á sua tabela..
aliás, vale a pena dar uma olhada na documentação HTMLTableRowElement. Necessariamente precisei fazer algumas alterações no seu código javascript e algumas correções no seu html para funcionar de acordo. Contudo pelo que entendi é que deseja:

Adicionar os respectivos valores na

Limpar os valores pré adicionados no formulário
Resetar os respectivos valores da

Portanto, sugiro que não deixe de ver Como criar um exemplo Mínimo, Completo e Verificável para poder elaborar uma pergunta boa e clara!

Segue o código abaixo:

var nome = document.querySelector("#novoNome");
var valor = document.querySelector("#novoValor");
var data = document.querySelector("#novaData");

document.querySelector("#btnNovoCliente").addEventListener("click", function() {
  addRow(nome, valor, data); // adiciona o valor na tabela
});

document.querySelector("#btnResetar").addEventListener("click", function() {
   resetRows(); // limpa todas as linhas da tabela
});

document.querySelector("#btnNovoCancelar").addEventListener("click", function() {
   document.querySelector("#frmMain").reset(); // limpa todos os inputs do formulário
});

function addRow(nome, valor, data) {
  let table = document.querySelector("table");
  let row = table.insertRow(-1); // será adicionado na última linha
  var nomeCell = row.insertCell(0); // o index "0" refere-se a coluna "Nome"
  var valorCell = row.insertCell(1); // o index "1" refere-se a coluna "Valor"
  var dataCell = row.insertCell(2); // o index "2" refere-se a coluna "Data"

  nomeCell.innerHTML = nome.value;
  valorCell.innerHTML = valor.value;
  dataCell.innerHTML = data.value;
}

function resetRows() {
  var table = document.querySelector("table"); // obtêm o elemento table
  var rowCount = table.rows.length; // faz a contagem total linhas na table
  for (var x = rowCount-1; x > 0; x--) {
     table.deleteRow(x); // deleta linha por linha
  }
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html {
    font-family: monospace;
    font-size: 16px;
    background-color: rgba(10, 5, 9, 0.233);
}

body {
    width: 90%;
    height: 90%;
    display: flex;
    flex-direction: column;
    font-family: monospace;
}

.left {
    background-color: gray;
    width: 350px;
    height: 270px;
    padding: 15px 30px;
    margin: 30px 30px;
}

.left form .formulario input {
    width: 275px;
    height: 30px;
    margin: 6px;
    padding: 10px;
}

.left form .btn {
    margin-top: 15px;
    display: flex;
    flex-direction: row;
    margin-left: -5px;
}

.left form .btn input {
    margin: 10px;
    width: 80px;
    height: 30px;
}

#btnResetar {
    background-color: rgb(187, 111, 111);
    font-weight: bolder;
    color: white;
}

.right {
    display: flex;
    flex-direction: column;
    width: 1440px;
    height: 900px;
}

.right table {
    border: 1px solid white;
    margin-left: 60px;
}
.right table thead tr th {
    border: 1px solid white;
    outline: solid white;
}
.right table thead tr th {
    margin-right: 100px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MyClients</title>

            <form action="#" id="frmMain">

                        Nome:

                        <input type="text" id="novoNome">

                        Valor:

                        <input type="text" id="novoValor">

                        Data:

                        <input type="text" id="novaData">

                    <input type="button" id="btnNovoCliente" value="Criar">
                    <input type="button" id="btnNovoCancelar" value="Cancelar">
                    <input type="button" id="btnResetar" value="Resetar">

            </form>

                        Nome
                        Valor
                        Data


elasticsearch regroups aggs by regex

Question: i would like to regroup aggs by regex to get only results who start with me same prefix like
For example, suppose I have three documents as below:
<code>{
    ...
    paths : [c:/]
    ...
}

{
    ...
    dimensions : [d:/]
    ...
}

{
    ...
    dimensions : [c:/new_folder]
    ...
}
</code>
i would like to get aggs by the HDD like
<code> "buckets" : [ {
    "key" : "c:",
    "doc_count" : 2
  }, {
    "key" : "d:",
    "doc_count" : 1
  }]
</code>
Answer: Use custom analyzer for those field with Keyword Tokenizer and Length Token Filter.
Or Keyword Tokenizer + Pattern Replace Char Filter if you need more complicated logic.
Comment: For the benefit of everyone, it would be a good idea to show a concrete example of how that can be achieved.
Comment: have you an example please ?
Comment: An others solution exist ? if i haven't acces to elasticsearch config ?
Comment: So, if you haven't acces to elasticsearch config, you can use scripted metric aggregation. But it will work not fast.

elasticsearch regroups aggs by regex


Given matrix $A$ and $B$, if matrix $B$ is not invertible what is matrix $C$ if $BC = A$?

Question: Find matrix $C$ if: $$ A = \begin{bmatrix}1&3&2\\-1&2&1\\0&1&0 \end{bmatrix} \space  B = \begin{bmatrix}3&2&1\\1&1&1\\1&2&3 \end{bmatrix}, \space BC = A $$
I started off this question by attempting to find the inverse of $B$, but then I discovered that $B$ is not invertible. Is it still possible to isolate for $C$ and solve or is this answer no solution?
Comment: In this case, $\begin{bmatrix} 1 & -4 & 1 \end{bmatrix} B = 0$ but $\begin{bmatrix} 1 & -4 & 1 \end{bmatrix} A \ne 0$ which makes it impossible for a solution to exist.
Comment: You can't say there's no solution just because B isn't invertible.  Pick some random matrix $C$ and compute $BC$.  Now you can call the answer $A$ and challenge your friends to find $C$.
Answer: The answer is no, twice.
If $B$ is singular, it is a zero divisor. Your equation does not have a unique solution.
However, this doesn't matter since your equation has no solutions at all. $B$ is singular, so $BC$ must be as well. This tells us $A$ is singular. However, $A$ is definitely invertible. This is a contradiction, so no solutions exist.
Answer: It depends.
Find a row vector $\vec v$ for which $\vec vB=\vec0$.
Then $\vec vBC=\vec0C=\vec0$.
If $\vec vA\ne\vec0$ then there is no solution.
Answer: Just as the equation $B\mathbf x=\mathbf b$ has a solution iff $\mathbf b$ is an element of the column space of $B$, the equation $BC=A$ can be solved iff every column of $A$ is in the column space of $B$. So augment $B$ with $A$ and row-reduce: $$\left[\begin{array}{ccc|ccc} 3&2&1 & 1&2&3 \\ 1&1&1 & -1&2&1 \\ 1&2&3 & 0&1&0 \end{array}\right] \to \left[\begin{array}{ccc|ccc} 1&0&-1 & -2&3&2 \\ 0&1&2 & 1&-1&-1 \\ 0&0&0 & 5&-5&1 \end{array}\right].$$ No column of $A$ is in $B$'s column space, so there's no solution. Perhaps there's an error in the problem or you've misread it.
Comment: Nope, the question is written as is. Your answer was clear and concise, thank you!
Answer: Yes let $c$ be the first column of $C$, and $a$ the first column of $A$, then solve the system
$$Bc=a.$$ do the same doe the other columns. Simplify the work by writing $B,A$ and do row reduction on $B$.


dimension of subspace of the vector space of polynomials of degree atmost $20$

Question: $V=\large P_{20}(x)$ and $W_1=\{p\in V:p(1/2)=p(7)=p(5)=p(1)=0\}$
$W_2=\{p\in V:p(1/2)=p(7)=p(3)=p(4)=0\}$
We need to find $\dim W_1\cap W_2$
$\dim V=21$, Can I say $\dim W_1=\dim W_2=4$? I need hint to solve this one.
Answer: No. Rather $\dim W_1=\dim W_2=21-4=17$.
Hint: Of which polynomials $W_1\cap W_2$ consists?
Comment: If $p\in W_1$ it has roots $1/2,7,5,1$. If $p\in W_2$ it has roots $1/2,7,3,4$. So if $p\in W_1\cap W_2$ it has roots $1/2,7,5,1,3,4$.
Comment: $W_1\cap W_2=\{p: p(1/2)=p(7)=0\}$
Comment: So $\dim (W_1\cap W_2)=15$ ?
Comment: Could you tell me where we are using rank nulity theorem?
Comment: No, $W_1\cap W_2=\{p\in V:p(1/2)=p(7)=p(5)=p(1)=p(3)=p(4)=0\}$.
Comment: I do not understand, please explain elaborately
Comment: What explain? The last comment?
Comment: @BorisNovikov can you please explain me how $dim W_1=dimW_2=17$?


How do I allow modules to provide their own view?

Question: In Drupal 7, there is hook_views_default_views() which allows modules to provide their own views. What's the equivalent for Drupal 8?
Answer: Views are config, so:

Create a View
Export the config for it as a single item using the UI or drush (removing the uuid if applicable).
Include it in your module's ./config/install folder
Install the module on a different site; the View will be created automatically
Comment: @liquidcms you can add a dependency on your module to the config file, so the View gets removed when the module is uninstalled. See https://drupal.org/node/2404447
Comment: but when i use drush to disable the module and then re-enable, it complains that the view is already in the active configuration.
Answer: I Have a reference URL for this. Go through, you can achieve this.
Creating views programmatically is quite different than we did in Drupal 7. In Drupal 7 we have hook_views_default_views(), we don't have this hook in Drupal 8. We will use configuration manager in Drupal 8 for creating views programmatically
How to create views programmatically in Drupal 8
Hope it will help for you.
Answer: You can use Drupal Console to export your views into custom module, e.g.
drupal config:export:view viewid --module="modulename"

See: config:export:view.

Export a view in YAML format inside a provided module to reuse in other website.

This will export views into module's config/install folder which would be imported on install.


what is bias and variance of an estimator?

Question: I know what Variance is. But what is Bias? I just have problems to understand this what is written!
Comment: Please explain what parts of the definition you follow. Do you understand what $\theta$ is? What $\hat{\theta}$ is? what the $E$ operator is? What the subscript on an $E$ operator is for?
Comment: @Glen_b I don't actually know what it is!
Comment: You don't know what *any* of those things are? Then I don't believe you when you say you know what the variance of an estimator is.
Answer: It may be that the math notation is somehow intimidating, but it's not that daunting. Take a look at what happens with an un-biased estimator, such as the sample mean:

The difference between the expectation of the means of the samples we get from a population with mean $\theta$ and that population parameter, $\theta$, itself is zero, because the sample means will be all distributed around the population mean. None of them will be the population mean exactly, but the mean of all the sample means will be exactly the population mean.
This is not the case for other parameters, such as the variance, for which the variance observed in the sample tends to be too small in comparison to the true variance. So if we want to estimate the population variance from the sample we divide by $n-1$, instead of $n$ (Bassel's correction) to correct the bias of the sample variance as an estimator of the population variance:

In both instances, the sample is governed by the population parameter $\theta$, explaining the part in red in the defining equation: $\text{Bias}E[\bar\theta]=E_\color{red}{{p(X|\theta)}}[\bar\theta]-\theta$. However, the $\bar\theta$ steers away from $\theta$ when the estimator is biased.


Showing $ λ_V(x) \leq min\{λ_1(x),\cdots,λ_n(x)\}$ Hazard function

Question:
Suppose $X_1, \cdots, X_n$ are independent, nonnegative continuous functions, each $X_i$ has hazard function $\lambda_i(x)$.
If $V=\max\{X_1, \cdots, X_n\}$, I need to show that $\lambda_V(x)\leq \min\{\lambda_1(x),\cdots, \lambda_n(x)\}$.

I know that $\displaystyle\lambda_V(x)=\frac{f_V(x)}{1-F_V(x)}=\frac{\sum_j f_j(x)\prod_{i\neq j}F_i(x)}{1-\prod_{i=1}^n F_i(x)}$.
However, I'm stuck here.
Any help would be appreciated.
Answer: The claim that you need to show seems to be false. For a counter example, let $X_1 \sim \textrm{Exp}(1)$ so that $\lambda_1(x) = 1$. Let us define $X_2$ by a piecewise hazard function:
\begin{equation}
\lambda_2(x) = \left\{ \begin{array}{ll}
       a & \quad x \leq 1 \\
       b & \quad x > 1 \end{array}
       \right.,
\end{equation}
where $a,b>0$. The CDF of $X_2$ is
\begin{equation}
F_2(x) = \left\{
        \begin{array}{ll}
            1-e^{-ax} & \quad x \leq 1 \\
            1-e^{-a}e^{-b(x-1)} & \quad x > 1
        \end{array}
    \right.
\end{equation}
Then, intermediate steps omitted, we work out the hazard rate of $V = \max(X_1,X_2)$ for $x>1$ to be
\begin{equation}
\lambda_V(x) = \frac{e^{-x}(1-e^{-a}e^{-b(x-1)}) +be^{-a}e^{-b(x-1)}(1-e^{-x})}{1 - (1-e^{-a}e^{-b(x-1)})(1-e^{-x})}.
\end{equation}
Now, let us consider the limit of this expression as $b\rightarrow 0$ (for some fixed $x>1$).
\begin{equation}
\lim_{b\rightarrow 0} \lambda_V(x) = \frac{e^{-x}(1-e^{-a})}{1-(1-e^{-a})(1-e^{-x})}>0.
\end{equation}
As the limit is some positive constant, selecting a suitably small $b>0$ will lead to $\lambda_V(x)>b$ which is then a contradiction with the claim.
Some intuition: say we have some system that breaks down when both components $1,2$ break. The claim is saying that the hazard rate of the system is smaller than either hazard rate of the components. However, our counterexample has one component that is likely to break during the first day of use, but after surviving the first day is extremely reliable. The system is still not extremely reliable during the second day: it is well plausible that the second component has broken during the first day and that the first component breaks now.


Best Way to Keep Page View Count in SQL Server

Question: I'll be keeping details of PageView counts for a specific table.
Table design is:
[IMAGE_ID] [int] IDENTITY(1,1) NOT NULL,
[IMAGE_PATH] [nvarchar](150) NOT NULL,
[CARTOON_ID] [int] NOT NULL,
[ADD_DATE] [datetime] NOT NULL,
[ADD_USER_ID] [int] NOT NULL,
[IMAGE_TEXT] [nvarchar](max) NULL

I'll be showing these images on each page and need the best way to keep the unique page view counts.
How would you do it?
Please remember that this table will have around 10000 images in short time and will a lot of activity. Updating this table on each request doesn't seem clever to me.
Comment: I've done this before by keeping the View count in the Application and periodically updating to the database in batches.
Comment: How were you keeping it in Application? Were you saving the details on the server(in a text file or something)
Comment: In a collection in memory in the application. Obviously it meant that in the event of an application restart some views would be lost but that wasn't particularly critical for my purposes.
Answer: I guess the best way is to keep a temp table with
IMAGE_ID
IP_ADDRESS
VISIT_DATE

and a view table that keeps
IMAGE_ID
COUNTER

And batch update the view table with the details of temp table and clear the content of it periodically.


Python problemas com Lista muito grande

Question: Estou fazendo um script Python e estou recebendo uma msg
de erro que não consigo resolver
x = [int(e) for e in input().split()]
msg de erro:
MemoryError
Command exited with non-zero status (1)
tentei usar o map:
x = list(map(int, input().split()))
msg de erro:
MemoryError
Command exited with non-zero status (1)
Geralmente as entradas não excedem 10.000 numeros
e o computador tem 32Gb de RAM? O que posso fazer, o SO é de 64Bits?
Comment: Não consegui reproduzir. O erro acontece quando você faz `entrada = input()` e cola o resultado? Suspeito que tenha a ver com o buffer de entrada, e não com a conversão pra `int`.
Comment: Quando coloco mais de 10000 entradas no input, acontece o erro! Vi na documentação que a lista tem uma limitação de entradas em 12000 elementos, tentei  criar um txt com o gravando o arquivo, mas não consigo usar os dados como listas da mesma forma.
Comment: @weltonvaz input() com mais de 10 mil elementos não tem sentido, são dados de entrada via teclado até onde eu me lembre, é insano para um usuário digitar essa quantidade de elementos não é não ?
Answer: Meu caro, seu script não esta errado, eu mesmo o testei no meu compilador e o aceitou de maneira correta, algo deve estar acontecendo com seu compilador ou coisa relacionada, visto que eu acabei de testar e não deu nenhum erro, caso queira mandar imagens poderia ficar mais fácil de lhe ajudar.
Comment: O Python tem uma limitação no numero de elementos de uma lista, este é o problema. Como sou novato, não consegui fazer ele gravar o input num txt e depois recuperar a linha com o dados(um inteiro qualquer). Ele sempre tem que ler o txt completo para acessar a linha que preciso, isso é demorado e custoso
Comment: Exato, ele tem que fazer isto toda vez porque ele não tem capacidade de ir apenas no local e pegar o inteiro, um grande problema e que nesse caso acarreta o erro, infelizmente não tem como concertar isso.
Comment: Obrigado Eron! Eu já tentei criar um arquivo na memoria com "import tempfile", mas ele não grava listas.
Comment: Dboas cara, a computação é limitada, nada podemos fazer, só seguir

Python problemas com Lista muito grande


Summation where upper bound is a function?

Question: I was attempting to understand asymptotic expansions when I came across this simple expression:
$$
\sum_{n=1}^{x^2}n.
$$
Of course, being an amateur mathematician, I threw it into Wolfram to see what it would say. To my surprise, it spit out an equation: $\sum_{n=1}^{x^2} n = \frac{1}{2} x^2 (x^2 + 1)$! My question is how? I attempted to approximate this sum by an integral, but I didn't quite get the right results:
$$
\sum_{n=1}^{x^2}n \approx \int_1^{x^{2}} ndn \\ \int_1^{x^{2}} ndn = \frac{n^2} {2}|_{1}^{x^2} = \frac{1}{2}(x^4-1)
$$
Is it applying the Euler–Maclaurin formula? Or is there some other formula or simple manipulation I just don't see?
Furthermore, as an aside, what can we say about functions of the form
$$
\sum_{n=1}^{f(x)}g(n)?
$$
Do they have simple expansions? What can we say about them?
Comment: I was very confused as to why a factorial appeared in your summation. Then it hit me
Answer: It is known that $$\sum_{n=1}^{u} n = \frac{u(u+1)}{2}$$
Plugging in $u = x^2$, we have that $$\sum_{n=1}^{x^2} n = \frac{x^2(x^2+1)}{2}$$
Answer: WAs proposed  result is  not  that   plausible, since we might rather assume in such cases $x$ being a real number.

According to rules when using the sigma-symbol $\sum$ we have for real  $x\geq 1$:
  \begin{align*}
\color{blue}{\sum_{n=1}^{x^2} n}&=\sum_{n=1}^{\lfloor x^2\rfloor} n\\
&=1+2+\cdots+\lfloor x^2\rfloor\\
&\,\,\color{blue}{=\frac{1}{2}\left\lfloor x^2\right\rfloor\left(\left\lfloor x^2\right\rfloor+1\right)}
\end{align*}
  where $\lfloor  a\rfloor$ is the greatest integer less or equal to $a$. See for instance   chapter 2: Sums , section 2.1 Notation in Concrete Mathematics
  by R.L. Graham, D.E. Knuth and O. Patashnik.

In the more general case we have, assuming $f(x)\geq 1$:
\begin{align*}
\sum_{n=1}^{f(x)}g(n)=\sum_{n=1}^{\left\lfloor f(x)\right\rfloor}g(n)=g(1)+g(2)+\cdots+g\left(\left\lfloor f(x)\right\rfloor\right)
\end{align*}
Note: We additionally have the rule $\sum_{n=a}^{b}f(n)=0$ if $b<a$ (see the referenced book).
Answer: The summation function works as the upper limit is an integer. In fact the sum is: $S_n=\frac{n(n+1)}{2}$. So if $n=f(x)$ then: $S_{f_{(x)}}=\frac{f_{(x)}(f_{(x)}-1)}{2}$.


SQL : instead of using a union want to use a where clause but one of the clauses is only true if another clause is true

Question: I would like to not use a union in my SQL query - how can I rewrite the following query?
select
    id,
    status,
    date
from
    table
where
    status = 'Active'
union
select
    id,
    status,
    date
from
    table
where
    status = 'Cancelled'
    and cancel_reason_id is not null

How can I rewrite this without the union?
Comment: OR the WHERE clause conditions. And perhaps SELECT DISTINCT is needed.
Answer: Use Boolean logic:
select
    id,
    status,
    date
from table
where status = 'Active'
or (status = 'Cancelled' and cancel_reason_id IS NOT NULL)

If you are combining with other conditions then make sure you have the correct parentheses to make it evaluate properly, e.g.:
select
    id,
    status,
    date
from table
where
(
  status = 'Active'
  or (status = 'Cancelled' and cancel_reason_id IS NOT NULL)
)
and some_other_condition

... so you aren't caught out by the condition precedence rules.
Answer: Looks like
select
    id,
    status,
    date
from table
where status = 'Active'
   or (status = 'Cancelled' and cancel_reason_id is not null)


How to connect Amazon Cloudfront with Elastic Beanstalk Single Instance in order to use HTTPS cert

Question: All of the tutorials I read pertain to an Elastic Beanstalk Load Balancer, which I am not using with a Single Instance.
I can access my app deployed through Elastic Beanstalk by either using the environment url or simply redirecting my Route 53 Type A record to either the Elastic Beanstalk environment or the ec2 public domain.
I want my webapp use HTTPS, so I created an SSL Cert through ACM and attempted to deploy the cert on my webapp through CloudFront. I created a CloudFront distribution domain but this is where I am stuck: I cannot use my Elastic Beanstalk environment as an Origin Domain, only an S3 bucket.
How do I get CloudFront to talk to Elastic Beanstalk/EC2?
Directly accessing S3 is not an option, not only do I get 403 errors but my project is an Angular App and .NET WebApi, which needs to be deployed and run, not simply accessed from an S3 folder. I also cannot bypass CloudFront and put the cert in my project, because you cannot download ACM certs.
Comment: Why not deploy SSL cert on your ALB? Do you really want to use CF?
Comment: I do not have a Load Balancer, I am using Single Instance.
Comment: In that case, even if you setup CF, entire traffic between CF and EB will be HTTP (not https). So its still very insecure setup. Do you have SSL setup on your EB instance?
Comment: what do you mean? I'm already telling CloudFormation to use HTTPS so it should communicate with ElasticBeanstalk in HTTPS right?

I don't think I can use SSL on ElasticBeanstalk because there's no way to add the ACM cert to that instance
Answer:
it should communicate with ElasticBeanstalk in HTTPS right?

Sadly this is not how it works. To have HTTPS between CF and EB, you must have valid, public SSL certificate on your EB instance. You can't use self-signed certificates nor EB gives you any SSL by default. If you do not have ALB on EB, you have to get SSL certificate from a third party (not ACM), such as LetsEncrypt and deploy in on the instance. You also must have your own domain for that to work.
Only if the above is satisfied, you will have HTTPS on the entire path:
Client --- (https) --> CF ---- (https) ----> EB

Otherwise, you can only have:
Client --- (https) --> CF ---- (http) ----> EB

Which is a security risk as you use http (plain text) over the internet.
Comment: Is it truly over the internet if these are both AWS Technologies existing within my VPC?

Is there really no other way to get an ACM Cert onto an EB instance? I would rather not use a Load Balancer as my project is pretty small and will never need that functionality. Is there a reason why Load Balancer accepts certs but EB Single Instance does not?
Comment: sorry for all the Q's, this is the first time I've gotten to talk to a human instead of the Documentation
Comment: @BrandonMiller CF is not in your VPC. It communicates with your EB over the internet.


How To Make a clone method using shared_ptr and inheriting from enable_shared_from_this

Question: I have seen that a useful way to write a clone method that returns a boost::shared_ptr is to do
class A
{
public:
  shared_ptr Clone() const
  {
    return(shared_ptr(CloneImpl()));
  }
protected:
  virtual A* CloneImpl() const
  {
    return(new A(*this));
  }
};

class B : public A
{
public:
  shared_ptr Clone() const
  {
    return(shared_ptr(CloneImpl()));
  }
protected:
  virtual B* CloneImpl() const
  {
    return(new B(*this));
  }
};

This allows the use of covariance with the regular pointer while still wrapping it in the safety of a smart pointer.  My problem is my class B needs to inherit from boost::enable_shared_from_this because right after construction it needs to register itself with a separate class, passing a shared pointer to itself.  I have a Create method that wraps construction and registration to make sure these always occur together.  The above clone method implementation cannot handle this requirement, however.  The registration cannot occur in CloneImpl since no shared_ptr yet exists "owning" the object, preventing a call to shared_from_this(), and if this logic is not in the virtual function then an shared_ptr that points to B, does not know about B's registration needs when cloned.  What is the best way to handle this problem?
Comment: Does this code compile? Looks like B::Clone() hides A::Clone().
Comment: This example compiled for me.  I believe it is purposeful that B::Clone() hides A::Clone() so that you get the correct return type.
Answer: Since you are already implementing the public interface covariance yourself via the non-virtual Clone() functions, you may consider abandoning the covariance for the CloneImpl() functions.
If you only need shared_ptr and never the raw pointer, so you could then do:
class X
{
public:
  shared_ptr<X> Clone() const
  {
    return CloneImpl();
  }
private:
  virtual shared_ptr<X> CloneImpl() const
  {
    return(shared_ptr<X>(new X(*this)));
  }
};

class Y : public X
{
public:
  shared_ptr<Y> Clone() const
  {
    return(static_pointer_cast<Y, X>(CloneImpl())); // no need for dynamic_pointer_cast
  }
private:
  virtual shared_ptr<X> CloneImpl() const
  {
    return shared_ptr<Y>(new Y(*this));
  }
};

CloneImpl() would always return a shared_ptr<Base> and now you could register your object inside the B::CloneImpl() function and return the registerd shared_ptr.
Comment: Thank you I believe this solves the problem very well.  In fact, even ignoring the registration requirement, doesn't this clone method seem even better than the one I listed, which is the example I always see when cloning with smart pointers?  This version seems to gives the same functionality while removing any possible misuse of the regular pointer that is created in the CloneImpl I listed.
Comment: @user334066 - I guess it depends. The example I posted can be found on the boost mailing list archives. Your Clone function allowed for class-internal use of the raw pointer which may make sense from time to time.


Django_filters with django-autocomplete-light

Question: I am using django-autocomplete-light with django_filters. I looked django-filter with django autocomplete-light, but my autocomplete doesn't work.
Models.py:
class ProfessionalDevelopment(models.Model):
   Name = models.CharField("Professional Development", max_length=20,default = "None")
   ProfessionalExperience = models.ManyToManyField(Person, through='PersonToProfessionalDevelopment')

class PersonToProfessionalDevelopment(models.Model):
   PersonID = models.ForeignKey(Person,  on_delete=models.CASCADE)
   ProfID = models.ForeignKey(ProfessionalDevelopment,  on_delete=models.CASCADE)
   Desc = models.CharField("Professional Development Description", max_length=30, default="None")

Views.py:
class ProfessionalDevelopmentAutocomplete(autocomplete.Select2QuerySetView):
 def get_queryset(self):
    qs = ProfessionalDevelopment.objects.all()
    if self.q:
        qs = qs.filter(name__istartswith=self.q)
    return qs

urls.py
urlpatterns = [url(r'^search/ProfessionalDevelopment-autocomplete/$', ProfessionalDevelopmentAutocomplete.as_view(),
    name='ProfessionalDevelopment-autocomplete']

Filters.py:
ProfessionalDevelopment = django_filters.CharFilter(name='professionaldevelopment__Name', lookup_expr='icontains',
                                                    widget=autocomplete.ModelSelect2(url='RSR:ProfessionalDevelopment-autocomplete'))

I got an error says 'list' object has no attribute 'queryset'. Then I changed the code to autocomplete.Select2 instead of autocomplete.ModelSelect2 (according to https://github.com/yourlabs/django-autocomplete-light/issues/763). Although no error, but I can not type in the text input box. Could someone help me? Thanks
Answer: You wan to filter model ProfessionalDevelopment against it's name.
You need to modify in these steps:

Complete str or Unicode on model ProfessionalDevelopment otherwise the option shows on filter will be id.
class ProfessionalDevelopment(models.Model):
   Name = models.CharField("Professional Development",
   max_length=20,default = "None")
   ProfessionalExperience = models.ManyToManyField(Person,
   through='PersonToProfessionalDevelopment')

   def __unicode__(self):
       return self.name

Change filter field of ProfessionalDevelopment:
ProfessionalDevelopment = django_filters.ModelChoiceFilter(
    queryset=ProfessionalDevelopment.objects.all(),
    widget=autocomplete.ModelSelect2(url="yourcompleteurl")
)

these steps should address you problem. Don't forget add {{ form.media }} in your template.
Comment: Hi, I followed your code. But it still does not work. The filter becomes a drop down list without any values in it.
Comment: @Doris did you add {{ form.media }} in template ?
Comment: No, I did not. What is this for? Where should I add in template? Thanks
Comment: @Doris  the {{ form.media }} will tell template to add js and css tags which are necessary, it's mentioned on dal document.
Comment: After I add {{form.media}} in template, still doesn't work. The filter in front end is still a box that does not allow me to type. Do you have any suggestions? thanks
Comment: Hi, I followed the code and it is working but you have a small typo in "django_filters.ModelChoiceField" -> "django_filters.ModelChoiceFilter". I tried to fix it but my change it was less than 6 chars. Thank you


Argument index out of range in datagrid view c# windows form

Question: Can anyone help me telling why argument index out range error occur in c# while selecting multiple rows in datagridview in c#...My code is also given bellow...the error is after the else if (comboBox2.Text == "Choice 2") portion......
<code> if (comboBox2.Text == "")
        {
            comboBox2.Focus();
            // comboBox2.BackColor = Color.Red;
        }
        else
        {
            if (comboBox2.Text == "Choice 1")
            {

                int ri = dataGridView1.CurrentCell.RowIndex;
                int ci = dataGridView1.CurrentCell.ColumnIndex;
                label4.Show();
                textBox2.Show();
                textBox2.Text = dataGridView1.SelectedRows[ri].Cells["course_name"].Value.ToString();

            }
            else if (comboBox2.Text == "Choice 2")
            {

                int ri = dataGridView2.CurrentCell.RowIndex;
                int ci = dataGridView2.CurrentCell.ColumnIndex;
                label3.Show();
                textBox4.Text = dataGridView2.SelectedRows[ri].Cells["course_name"].Value.ToString();
                textBox4.Show();
            }
            else if (comboBox2.Text == "Choice 3")
            {

                int ri = dataGridView3.CurrentCell.RowIndex;
                int ci = dataGridView3.CurrentCell.ColumnIndex;
                label2.Show();
                textBox3.Text = dataGridView3.SelectedRows[ri].Cells["course_name"].Value.ToString();
                textBox3.Show();
            }
        }
</code>
Comment: On which line exactly?
Comment: Have you tried debugging it? This type of issue is very easy to find if you debug.
Comment: Yeah I tried....I even used three seperate datagridview for this purpose but the result is same....I'll be very happy if you help me out.... thank you
Answer: DataGridView.SelectedRows is a collection that contains the Rows selected. It has the same number of rows of the grid only if you select every row in the grid. But I think you are only selecting a few rows. So, the RowIndex of the current cell is not a valid index inside the SelectedRows collection.
You need to change your code to something more secure
<code> if(dataGridView3.SelectedRows.Count > 0)
 {
      textBox3.Text = dataGridView3.SelectedRows[0].Cells["course_name"].Value.ToString();
      ....
</code>
or using the currentRow property.
<code> DataGridViewRow currentRow = dataGridView3.CurrentRow;
 if(dataGridView3.SelectedRows.Contains(currentRow))
 {
      textBox3.Text = currentRow.Cells["course_name"].Value.ToString();
      ....
</code>
but if you just want to set the TextBox3.Text to the cell "course_name" of the currentRow, then there is no need to involve the SelectedRows collection
<code> if(dataGridView3.CurrentRow != null)
      textBox3.Text = dataGridView3.CurrentRow.Cells["course_name"].Value.ToString();
</code>


How to force a service to run from a specified directory in Ubuntu Linux?

Question: I need to create a service that will automatically start my Rails server. Since the rails server command works correctly only in the application directory, I use the /lib/systemd/system/dev.fhc.name.service file with the following content:
[Unit]
Description=Puma development server for fhc.name domain

[Service]
ExecStart=cd /home/fhc/www && screen -dmS dev.fhc.name rails server -u puma -e development -p 3001
ExecStop=screen -X -S dev.fhc.name quit
Type=idle
KillMode=process

SyslogIdentifier=dev-fhc-name
SyslogFacility=daemon

Restart=on-failure

[Install]
WantedBy=multi-user.target

However, trying to run it:
sudo systemctl start dev.fhc.name

Leads to an error:

Aug 25 23:00:51 fhc.name systemd[1]:
/lib/systemd/system/dev.fhc.name.service:5: Executable "cd" not found
in path "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

What am I doing wrong?
Comment: https://unix.stackexchange.com/questions/200654/executing-chdir-before-starting-systemd-service
Comment: https://askubuntu.com/a/1063395/680869
Answer: Based on this answer you should use directive WorkingDirectory. Do not forget other directives like ExecStart should have full path.
And for me usage of screen look a bit odd and not in place.
Comment: You don't start services daemonized with systemd.
Comment: rails should create a pid file. Use it in systemd.
Comment: For some reason, Puma won't start with the `-d` flag. It writes a success notification as a daemon, and immediately stops without any errors. So you have to use `screen`.
Comment: @GeraldSchneider Yes, you're right, I didn't think about removing it when transferring the command to the service. True, now the question arises, how to write the command to stop this particular server in ExecStop?


Contour Integration Along Part of the Unit Circle

Question: How can you find the integral of a trigonometric function using contour integration that goes from $0$ to $\frac{\pi}{2}$ instead of the full unit circle i.e. $2\pi$?
I came across an integral of this type, it was along the lines of:
$$
\int_{0}^{{\pi}/{2}}\frac{d\theta}{1+8\sin^2\theta}
$$
Using classic technique the integral can be rewritten as:
$$
\frac{i}{2}\int_{\theta=0}^{\theta={\pi}/{2}}\frac{zdz}{(z^2-\frac{1}{2})(z^2-2)}
$$
Where the substitution was $z=e^{i\theta}$. This tells us in $z$ there are poles at $\pm\sqrt{2}$ and $\pm\frac{1}{\sqrt{2}}$, of which the latter are in the unit circle.
How do I go on, and/or am I even going about this correctly? I could do partial fraction but this defeats the purpose of using contour integrals. Any tips?
I thought about using a quarter wedge in the first quadrant, but this doesn't look promising since there is a need for going in straight lines to and from the origin, hence having to jump over/under the simple pole. The solution to this integral is $\frac{\pi}{6}$, for the curious.
Comment: Use the symmetries of $\sin$, that integral is a quarter of the integral from $0$ to $2\pi$. Or half of the integral from $0$ to $\pi$, then you can use a trigonometric identity to transform the $\sin^2 x$ into something involving $\cos (2x)$, reducing the degree of the rational function you get.
Comment: I got that integral to be $0$ since the sum of the residues is zero.
Comment: That is evidently wrong, so somewhere there must have occurred a mistake. I'm off to dinner now, if nobody has answered until I'm back, I'll take a look then.
Answer: We have the following integral:
$$I=\int_{0}^{\pi/2}\frac{\mathrm{d}\theta}{1+8\sin^{2}(\theta)}$$
We note that $\sin^{2}(\theta)$ is symmetric about $\pi/2$, so:
$$I=\frac{1}{2}\int_{0}^{\pi}\frac{\mathrm{d}\theta}{1+8\sin^{2}(\theta)}$$
But we know that $\sin^{2}(\theta)=\frac{1}{2}(1-\cos(2\theta))$, so:
$$I=\frac{1}{2}\int_{0}^{\pi}\frac{\mathrm{d}\theta}{1+4(1-\cos(2\theta))}=\frac{1}{2}\int_{0}^{\pi}\frac{\mathrm{d}\theta}{5-4\cos(2\theta)}$$
Now we make a substitution $\theta^{\prime} = 2\theta \implies \mathrm{d}\theta^{\prime} = 2\mathrm{d}\theta$, so:
$$I=\frac{1}{4}\int_{0}^{2\pi}\frac{\mathrm{d}\theta^{\prime}}{5-4\cos(\theta^{\prime})}$$
Now we substitute $z = e^{i\theta^{\prime}} \implies \mathrm{d}z=ie^{i\theta^{\prime}}\:\mathrm{d}\theta^{\prime}$, so:
$$I = \frac{1}{4i}\oint_{|z|=1}\frac{\mathrm{d}z}{5z-2z\left(z+\frac{1}{z}\right)} = \frac{1}{4i}\oint_{|z|=1}\frac{\mathrm{d}z}{-2z^{2}+5z-2}$$
We can solve for the roots of the polynomial on the denominator of the integrand to get: $z=\{2,\frac{1}{2}\}$. Only $z=\frac{1}{2}$ lies within the unit circle, so by Cauchy's Residue Theorem:
$$\begin{align*}I &= \frac{1}{4i}\cdot 2\pi i\operatorname{Res}\left(\frac{1}{-2z^{2}+5z-2},\frac{1}{2}\right) \\
&= \frac{\pi}{2} \cdot \frac{2}{6} = \frac{\pi}{6}\end{align*}$$

Off-topic P.S: This may be just co-incidence, but this question appeared in an exam I took yesterday. If this is where you got it, good luck, I hope it went well!


Como fazer redirecionamento utilizando AngularJs

Question: Estou utilizando o angularjs, e preciso redirecionar para outra página dentro do meu controller. Como faço isso?
Segue o código do meu controller:
meuController.controller('Controller', function ($scope) {
    $scope.save = function(){
        $scope.tasks.push({
            'name': $scope.title
        });
        //redirecionar aqui. Como ???
    };
});

Answer: Antes de começar, todo o código abaixo está funcionando em: http://jsbin.com/roqil/edit
Para ter o controle de redirecionamento de páginas você precisa seguir alguns passos antes.
Referenciar as bibliotecas de roteamento do AngularJS
Referencie o módulo ngRoute no seu html:

Modularizar seu App
Só é possivel controlar o roteamento da página com um aplicativo modularizado, crie seu módulo referenciando o angular-route dessa forma:
var app = angular.module("app", ["ngRoute"]);

E na tag  adicione :

A variavel app é global e nela você pode chamar services, factories, e métodos de configuração.
Vamos adicionar um factory de tasks apenas para garantir que os controllers estão usando a mesma lista de tasks. Conseguinte, os dois controllers, um para a view de Detalhes e outro para Listagem:
/*1*/   app.factory("TaskFactory",function(){
/*2*/     var tasklist =  [
/*3*/        {name:"terminar meu app",id:0},
/*4*/        {name:"comprar presente para minha irmã",id:1}
/*5*/        ];
/*6*/          return{
/*7*/            get : function(){
/*8*/            return tasklist;
/*9*/          }
/*10*/       };
/*11*/   });
/*12*/    app.controller('TaskListCtrl', function ($scope,TaskFactory) {
/*13*/      (function(){$scope.tasks=TaskFactory.get();})();
/*14*/    });
/*15*/    app.controller('TaskDetailCtrl', function ($scope,TaskFactory,$routeParams) {
/*16*/      (function(){$scope.task=TaskFactory.get()[$routeParams.taskId];})();
/*17*/    });

Detalhes das Linhas:
Linha 1 - Criando a factory
Linha 3 - Vamos utilizar o id da task para chama-la da view de listagem para detalhes
Linha 6 - Retornando um método para chamar a lista de tasks do factory
Linha 12 - Criando o controller TaksListCtrl que está recebendo por argumento o $scope e TaskFactory que é o factory. Tem que ser o mesmo nome chamado no argumento e registrado no app.factory()
Linha 13 - Populando $scope.tasks com a lista de tasks que retorna de TaskFactory.Get();
Linha 15 - Criando o controller TaskDetailCtrl que será responsavel por apresentar a task selecionada na outra view. O diferencial é que agora estou recebendo por argumento o $routeParams do módulo ngRoute que é responsavel por manter os dados que vc passa na URL
Linha 16 - Novamente estou pegando tasks do TaskFactory mas desta vez estou filtrando por aquelas que contém o id = $routeParams.taskId (veremos pra frente o porquê deste) então ele trará apenas uma task.
Poderia fazer assim também se preferir:
//esta forma
var tasks = TaskFactory.get();
var id = $routeParams.taskId;
$scope.task = tasks[id];

//é a maneira simplificada desta
$scope.task=TaskFactory.get()[$routeParams.taskId];

Configurar as rotas em app.config()
É necessário reservar um espaço no html para permitir que o AngularJS manipule seu DOM

    <ng-view></ng-view>

Apenas use a diretiva ng-view em alguma tag
 e pronto, nao precisa referenciar controllers ou algo do tipo, isso será registrado em app.config() com a seguir:
/*1 */   app.config(function($routeProvider) {
/*2 */       $routeProvider.when('/',{
/*3 */           template: 'Lista de Tasks:'+
/*4 */             '
'+
/*5 */           '
'+
/*6 */         '{{task.id}} - {{task.name}}'+
/*7 */           '
detalhes'+
/*8 */       '

'+
/*9 */     '
',
/*10*/            controller: "TaskListCtrl"
/*11*/          }).
/*12*/        when('/:taskId',{
/*13*/            template: 'Detalhes da Task {{task.id}}:'+
/*14*/              '
Nome: {{task.name}}
'+
/*15*/              '
'+' Voltar',
/*16*/            controller: "TaskDetailCtrl"
/*17*/          }
/*18*/        ).otherwise({redirect:'/'});
/*19*/    });

O que o código acima faz é:
Linha 1 - invoca o método config do módulo passando uma function que recebe o $routeProvader
Linha 2 - No $routeProvader você tem os métodos when() e otherwise() , cada um recebe um objeto com as propriedades de roteamento, por exemplo:
when("/url que vc deseja",{
  template: "aqui vai o html que será renderizado dentro de ng-view"
  controller: "aqui o nome do controller correspondente àquela url"
});

otherwise({redirect:"/"}) //quer dizer que se nao for nenhuma das url registradas,
// redirecionara para a principal

No primeiro when() estou passando que caso nao tenha parametros, chamará aquele template utilizando o "TaskListCtrl". Se o template for muito grande, é recomendado guardar ele em outro arquivo e chama-lo assim {templateUrl:'exemplo.html'} ai invés de apenas template
Na linha 7 estou simplesmente criando um link para #/{{task.id}}, o angular irá substituir o taskId pelo id da task.
IMPORTANTE: Na linha 12 o when está recebendo \:taskId, o sinal : indica que é um parametro, isso é necessário para dizer para o $routeParams que é chamado no controller, que ele terá a a propriedade taskId, veja:

Ademais, está passando o template e amarrando ao controller TaskDetailCtrl
Resumo
Pronto, são necessários esses passos para fazer um controle de roteamento simples utilizando AngularJS
resumindo:

Referenciar angular.js e angular-route.js
Criar um módulo para a aplicação referenciando ['ngRoute']
Adicionar
Criar os controllers e factories/serivces
Adicionar o argumento $routeParams no controller que utiliza-ra deste.
Chamar ng-view no html assim:

Invocar app.config(function($routeProvider){...}) para fazer o registro de rotas (inclusive o $location só funciona se a rota direcionada estiver registrada aqui.
Chamar o método $routeProvider.when() para cada rota do seu aplicativo passando os parametros corretos
Distribuir tags
Utilizar $routeParams.qualquerPropriedadeRegistrada conforme necessidade.

App funcionando aqui: http://jsbin.com/roqil/edit
Update
Nesse exemplo usei o router nativo do angular, mas existe outro muito melhor que é o Ui-Router
Vale a pena dar uma conferida nesse link:
Como usar Angular UI Router? e quais as vantagens?
Comment: escreveu esse código e esse post todo muito rápido! parabéns.
Comment: Obrigado (: na verdade levei algumas horas para escreve-lo
Comment: Ja tentei montar um blog, nao deu muito certo kk. Vou compartilhar meu conhecimento aqui, sob demanda das perguntas [:
Comment: agora que vi que o post foi feito à 10 dias, de qualquer modo, sua resposta foi ótima. faz um blog e passa seu conhecimento pra gente. ;-)
Answer: Para fazer isso você precisa modificar sua função para receber o parâmetro $location.
Depois disso utilizar este parâmetro fazer o redirecionamento
Exemplo:
meuController.controller('Controller', function ($scope,$routeParams,$location) {
    $scope.save = function(){
        $scope.tasks.push({
            'name': $scope.title
        });
        $location.path("/algumCaminho");
    };
});

Se tiver mais alguma duvida pode procurar na documentação oficial do location do controller.
Comment: Chamar direto `$routeParams` e `$location` só funciona para a versão `1.0.7` do Angular. Se estiver usando a versão `1.2.14` deve referenciar também o `angular-route.js`


How to update custom user field on form submit

Question: I want to create a basic page that has only one of my custom user account fields listed, and available to edit.
For example, I have a custom user account field: field_companyname
Rather then directing the user to go to www.example.com/?q=user/1/edit,
I want the user to go to a different page (i.e www.example.com/node/5).
On this page, there should only be a single text input field, and a submit button to save the new data to the user account.
I'm pretty sure I need to implement user_save(), but I just don't know where to go from here.
// load user object
$existingUser = user_load('USERID');

// update some user property
$existingUser->some_property = 'foo';

// save existing user
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);

Any help or pointers would be much appreciated. Thanks for looking!
EDIT: I was able to load the entire user account edit form onto a node using the following code:
<?php
  module_load_include('pages.inc', 'user', 'user');
  global $user;
  $account = user_load($user->uid);
  $output = drupal_render(drupal_get_form('user_profile_form', $account));
  return $output;
?>

However, I still cannot figure out how to display ONLY my single custom field. Any help is greatly appreciated.
EDIT #2: I used CSS to hide the other fields that I did not want to display. Seems like there should be a better way to do this. But I guess this will work for now, unless anyone else can chime in :-)
Thanks again for looking.
Comment: if you are using profile2 module use this function to load profile2 fields:
`profile2_by_uid_load($uid, $type_name)`
Comment: I don't get why you want to do it in a node? Rather do it on a custom form and then you can add form items as you please. You will just be reading the user data and submitting to it but never have to work with the actual account edit form.
Answer: Use field_attach_form in your page with the field name and user object. You can use field_attach_form_validate and field_attach_submit
to validate and submit the values.
Answer: Use hide() function hide unnecessary fields. You can hide form field like:
hide($form['field_name']);

Implement hook_form_FORM_ID_alter() to do your magic with a hide() function


mounting a windows software raid volume in linux

Question: i have a windows 2000 server box with 6 drives in it configured as RAID 5 using windows dynamic volumes. windows will not boot.
is it possible to mount this volume using linux? i looked at dmraid but it doesn't appear to support windows software raid.
acceptable answers also include live or resuce boot CD's (such as TRK) that would allow me to access the volumne without having to boot windows from the boot drive in the computer.
Answer: I don't believe you can do this from linux. Looks like your best option would be to use a BartPE Windows Live CD to access the RAID volume and rescue the data.
Comment: Doing some quick Googling, it doesn't look like BartPE supports dynamic disks. Some commercial data recovery products do.
Comment: you would have thought it would occur to me that i can make a PE disk from a server 2003 CD, but it didn't. duh!
Comment: ok, i have confirmed that this works if you user a windows 2003 server cd. windows 2000 server is not supported.


Sum of series: $1*3*(2^2) + 2*4*(3^2) + 3*5*(4^2) + \dots$?

Question: I am trying to find the sum of the above series.
The sum till n terms can be found using power series expansion. However, I'm trying to solve this using the method of difference (a.k.a. Telescoping sum or $V_n$ method).
In this method, the general term is expressed as the difference between two consecutive values of some function. Like the following:
$T_n = V_n - V_{n-1}$
and then the sum is taken which comes to be
$S_n = V_n - V_0$
The general term of the series in question can be represented as a product:
$T_n = n(n+1)^2(n+2)$
But I am unable to represent this as a difference. How can I proceed from here to find the sum?
Comment: Duplicate of https://math.stackexchange.com/questions/1903470/sum-of-the-series-1-cdot3-cdot222-cdot4-cdot323-cdot5-cdot42-cdots?rq=1
Answer: Since $V_n = S_n + V_0$ you have that $V_n - V_{n-1} = S_n - S_{n-1}$ so your search for $V_n$ is identical to finding $S_n$, besides a free constant.
So you may well set $V_n$ to the (known or guessed) sum $S_n$ and write
$$V_n =  \frac{1}{10} n (n + 1) (n + 2) (n + 3) (2 n + 3)$$
Comment: I didn't understand what you mean by setting Vn to the sum. I don't know the sum and can't guess it. Also, how did you arrive at the last equation? Can you please elaborate more?
Comment: I got $V_n = S_n$ by using power series expansion. As $T_n$ is of order $n^4$, $S_n$ has to be of order  $n^5$.  You may therefore also set a general formula $V_n = a_0 + a_1 n + a_2 n^2 + a_3 n^3  + a_4 n^4 + a_5 n^5$  and determine the coefficients $a_i$  by setting all powers $n^k$ equal in $V_n - V_{n-1} = T_n$.
Comment: I have mentioned in the question that I don't want to use Power series expansion. I am in high school and don't know calculus or Power series expansion. However, thanks for the answer.
Comment: I've laid out another path to arrive at $V_n$ - with unknown coefficients to be determined - in my previous comment. Kindly use that one.


Data mining classification competition

Question: I'm currently taking a data mining class, and for one our projects we're required to predict the class label for an unknown data set by first building a classifier on a training data set which already provides the class label.
We're only required to get an accuracy of 80% to get a full mark on the assignment. I have already achieved this using the J48 Decision Tree algorithm (acc=84.08%).
There is also an ongoing competition on who can get the highest accuracy (determined by a Judge system we can't see).
I have two questions:

How can I use an ensemble method with to do this
Is there a way to optimize the parameters for each classifier?

<code> import java.io.*;
 import weka.core.Instances;
 import weka.filters.Filter;
 import weka.filters.unsupervised.attribute.*;
 import weka.classifiers.trees.*;
 import weka.classifiers.Evaluation;

public class CompClassifier {
public static FileOutputStream Output;
public static PrintStream file;

public static void main(String[] args) throws Exception {
    // load training data
    weka.core.Instances training_data = new weka.core.Instances(new
java.io.FileReader("/Users//Weka/training.arff"));

    //load test data
    weka.core.Instances test_data = new  weka.core.Instances(new
java.io.FileReader("/Users//Weka/unknown.arff"));

    //Clean up training data
    ReplaceMissingValues replace = new ReplaceMissingValues();
    replace.setInputFormat(training_data);
    Instances training_data_filter1 = Filter.useFilter(training_data, replace);

    //Normalize training data
    Normalize norm = new Normalize();
    norm.setInputFormat(training_data_filter1);
Instances processed_training_data = Filter.useFilter(training_data_filter1, norm);

    //Set class attribute for pre-processed training data
 processed_training_data.setClassIndex(processed_training_data.numAttributes() - 1);

    //output to file
Output = new  FileOutputStream("/Users//Desktop/CLASSIFICATION/test.txt");
    file = new PrintStream(Output);

    //build classifier
    J48 tree = new J48();
    tree.buildClassifier(processed_training_data);

    //Clean up test data
    replace.setInputFormat(test_data);
    Instances test_data_filter1 = Filter.useFilter(test_data, replace);

    //Normalize test data
    norm.setInputFormat(training_data_filter1);
    Instances processed_test_data = Filter.useFilter(test_data_filter1, norm);

    //Set class attribute for pre-processed training data
    processed_test_data.setClassIndex(processed_test_data.numAttributes() - 1);

    //int num_correct=0;
    for (int i = 0; i < processed_test_data.numInstances(); i++) {
        weka.core.Instance currentInst = processed_test_data.instance(i);
        int predictedClass = (int) tree.classifyInstance(currentInst);
        System.out.println(predictedClass);
        file.println("O"+ predictedClass);
    }

}
</code>
Comment: On a side note, even though the Weka book is titled "Data mining", it actually is about regular machine-learning. You can even find a statement by the authors that it was supposed to be called "practical machine learning", and the publishing house changed it to "data mining" for marketing and sales reasons. All the classification material clearly belongs to AI and ML, not to data mining (no integration with database management!)
Comment: Access of the originating database seems to me a logistical issue.  Although in-database modeling methods exist, I believe that it is much more common to fit models in RAM, which becomes larger and cheaper every passing year.  Also, there are a variety of techniques for either scaling up modeling processes, or scaling down the data (sampling, progressive sampling, data squashing, etc.).  The core modeling techniques of data mining and machine learning (and inferential statistics, pattern recognition, etc.) are otherwise indistinguishable.
Answer: An easy way to build an ensemble is by using a random forest.  I'm fairly sure weka has a random forest algorithm, and if other tree-based models are performing well it's worth trying out.
You could also build your own ensemble by training multiple (say 50 or 100) J48 decision trees and using them to "vote" on the classification of each object.  For example, if 60 tress say a given observation belongs to class "A", and 40 say it belongs to class "B", you classify the object as class "A."
You can further improve such an ensemble by training each tree on a random sub-sample of the training data.  This is called "bagging," and the random sub-samples are usually created with replacement.
Finally, you can additionally give each tree a random subset of variables from the training set.  This is called a "random forest."  While your professor will probably be impressed if your write your own random forest algorithm, it's probably best to use an existing implementation.
Answer: A model ensemble is simply a collection of models whose output is combined (hopefully generating superior performance in the process).  Obviously, to be of any interest, the base models must vary somehow, and there are several ways to do this: vary the model type (tree induction, neural network, discriminant function, etc.), vary the starting conditions of the model training (such as differing weight initializations for feedforward neural networks), vary the observations used (typically random samples of the entire training set), vary the candidate input variables (again, typically random samples of all those available), etc.
There are several ways to combine the base model outputs.  The simplest are averaging or voting, though these may require some calibration.
Answer: You could try the new machine learning library called ML-Flex (http://mlflex.sourceforge.net). It is designed to execute a variety of ensemble methods and can also provide side-by-side comparisons when different algorithm parameters are used (though perhaps not exactly as you desire). If you're interested, give it a try and provide any feedback you may have. Full disclosure: I am the author of this package.

Data mining classification competition


How to compile Thingsquare (Contiki-port) for TI MSP430

Question: I need to operate my wireless mesh network on the European ISM band  at 868 MHz. My interest has fallen upon Contiki-OS, and Thingsquare Mist is a Contiki port that supports some of Texas Instruments 868MHz transceivers.
Now, I have successfully finished the simulation in Instant Contiki from the starting guide, but I have trouble compiling the example codes from Thingsquare Mist.
When trying to add a mote in the simulation with firmware from
thingsquare-mist-1.0.1/platform/mist-exp5438/contiki-exp5438-main.c

I get:
$ make contiki-exp5438-main.exp5438 TARGET=exp5438
make: *** No rule to make target `contiki-exp5438-main.exp5438'

Trying to compile some of the examples states that ip64-conf.h is missing from apps/ip64/, and renaming the existing file ip64-conf-example.h to ip64-conf.h in said folder just gives me a lot of compile time errors.
Obviously I am doing some fundamentally wrong here, could someone point me in the right direction?
Answer: Try with this command:
make contiki-exp5438-main.exp5438 TARGET=mist-exp5438

Answer: contiki-exp5438-main.c isn't an application, try building anything from the examples directory instead.
That said, I don't really know what I'm doing and I haven't managed to successfully simulate any Mist applications in Cooja myself, but trying to build anything from the examples directory at least gives you a valid make target
Edit: Oops I didn't read the entire question, I saw now that you already tried that as well. The other answer suggested building for mist-exp5438, but as suggested here you should use exp1101 or exp1120 instead. Except that the application doesn't fit in ROM for those targets...


Access-Control-Allow-Origin cannot contain more than one origin

Question: I have developed my backend solution with spring boot (microservice) and the frontend with angular. When I request through postman it's ok. But from the frontend side, it's not loaded, and there shows an error (i.e. Access Control Origin header not present). When I added 'CorsWebFilter' this error is different (Access-Control-Allow-Origin cannot contain more than one origin). I searched a lot but doesn't find any solution. Please, help me.
[NOTE: Other services don't contain any origin header]
Spring Boot Application
@SpringBootApplication
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

}

My API Gateway Configuration:
@Configuration
public class ApiGatewayConfiguration {

    @Autowired
    private JwtAuthenticationFilter filter;

    @Value("${service.security.secure-key-username}")
    private String SECURITY_KEY_USERNAME;

    @Value("${service.security.secure-key-password}")
    private String SECURITY_KEY_PASSWORD;

    private static String authorizationKey = "Authorization";

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {
        String authorizationValue = getAuthorization();
        return builder.routes()
                .route("auth-service", r -> r.path("/auth-service/**").filters(f -> f.filter(filter)).uri("lb://auth-service"))
                .route("currency-exchange", r -> r.path("/currency-exchange/**").filters(f -> f.filter(filter).addRequestHeader(authorizationKey, authorizationValue)).uri("lb://currency-exchange"))
                .route("currency-conversion", r -> r.path("/currency-conversion/**").filters(f -> f.filter(filter).addRequestHeader(authorizationKey, authorizationValue)).uri("lb://currency-conversion"))
                .route("hindu-religious", r -> r.path("/hindu-religious/image/**").filters(f -> f.addRequestHeader(authorizationKey, authorizationValue)).uri("lb://hindu-religious"))
                .route("hindu-religious", r -> r.path("/hindu-religious/**").filters(f -> f.filter(filter).addRequestHeader(authorizationKey, authorizationValue)).uri("lb://hindu-religious"))
                .build();
    }

    private String getAuthorization() {
        String auth = SECURITY_KEY_USERNAME + ":" + SECURITY_KEY_PASSWORD;
        String base64Text = java.util.Base64.getEncoder().encodeToString(auth.getBytes());
        String authKey = "Basic " + base64Text;
        return authKey;
    }
}

CROS Configuration:
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        final CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setMaxAge(3600L);
        corsConfig.addAllowedOrigin("*");
        corsConfig.addAllowedHeader("*");
        corsConfig.addAllowedMethod("OPTIONS");
        corsConfig.addAllowedMethod("HEAD");
        corsConfig.addAllowedMethod("GET");
        corsConfig.addAllowedMethod("PUT");
        corsConfig.addAllowedMethod("POST");
        corsConfig.addAllowedMethod("DELETE");
        corsConfig.addAllowedMethod("PATCH");
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);
        return new CorsWebFilter(source);
    }
}

Answer: corsConfig.addAllowedOrigin("*") is generally bad practice, while you call it twice.
Comment: I've given my host origin but there show the same multiple origin header (host_ip, *) issue.
Comment: Anyway, I've bypassed it using filterer. I'm not sure if this is a temporary or permanent solution.


Yahoo finance query api, want to limit to one country search result (Ionic cordova)

Question: As we search a stock a ticker in Yahoo search, there will be search suggestion. Example, when I type 'TPM' in search, I only want Australia stocks which is TPM.AX or other Australia stocks appear in the stocks suggestion. I do not want to show other exchanges stocks tickers.
<code>    cacheKey = ticker,
    stockDetailsCache = stockDetailsCacheService.get(cacheKey),

    query = 'select * from yahoo.finance.quotes where symbol IN ("' + ticker + '")',
    url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIService.encode(query) + '.AX&format=json&env=http://datatables.org/alltables.env';

    if(stockDetailsCache) {
      deferred.resolve(stockDetailsCache);
    }
    else {
      $http.get(url)
        .success(function(json) {
          var jsonData = json.query.results.quote;
          deferred.resolve(jsonData);
          stockDetailsCacheService.put(cacheKey, jsonData);
        })
        .error(function(error) {
          console.log("Details data error: " + error);
          deferred.reject();
        });
    }

    return deferred.promise;
  };

  var getPriceData = function(ticker) {

    var deferred = $q.defer(),

    cacheKey = ticker,

    url = "http://finance.yahoo.com/webservice/v1/symbols/" + ticker + ".AX/quote?format=json&view=detail";

    $http.get(url)
      .success(function(json) {
        var jsonData = json.list.resources[0].resource.fields;
        stockPriceCacheService.put(cacheKey, jsonData);
        deferred.resolve(jsonData);
      })
</code>
I have put .AX in the url but still unable to shows Australia stocks for my app which is written in Ionic 2. Currently, all stocks from exchanges still shown.
How to make it only show Australia stocks in search suggestion?
Answer: <code>query = 'select * from yahoo.finance.quotes where symbol IN ("' + ticker + '")',
    url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIService.encode(query) + '+'.AX'+&format=json&env=http://datatables.org/alltables.env';
</code>
Use +'AX'


Div invisível com pointer-events: none é uma boa idéia?

Question: Eu tenho uma div, chamada #dim-bg, a qual propósito é ofuscar a tela quando uma janela é focada. É um elemento fixado, vazio, invisível, que não se interage com o usuário, e ocupa toda a tela.
Eu tive a ideia de combinar pointer-events: none para simular que ela não está ali, sem ter que mexer em display, height ou visibility. A ideia é fazer uma transição em sua opacidade de forma suave.
#dim-bg {
    pointer-events: none;
    opacity: 0;
    transition: opacity .5s;
}
#dim-bg.visible {
    pointer-events: all; /* previne clicar onde foi ofuscado */
    opacity: 1;
}

Abaixo, tenho uma demonstração da funcionalidade.

const dimBgElement = document.getElementById('dim-bg');

function dimBg() {
  dimBgElement.classList.add("visible");
  document.getElementById('topper').classList.add("visible");
}

function undimBg() {
  dimBgElement.classList.remove("visible");
  document.getElementById('topper').classList.remove("visible");
}
#dim-bg {
  background-color: #000;
  opacity: 0;
  pointer-events: none;
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 1;
  transition: opacity .5s cubic-bezier(0.075, 0.82, 0.165, 1);
}

#dim-bg.visible {
  opacity: .8;
  pointer-events: all;
}

/* código não relatado à postagem */

#topper,
#bottom {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

#topper {
  top: 30px;
  z-index: 5;
  display: none;
}

#topper.visible {
  display: block;
}

#bottom {
  bottom: 30px;
}

  É possível interagir com isso

  <button onclick="undimBg()">
    Clique para voltar ao normal
  </button>

  <button onclick="dimBg()">
    Clique para ofuscar o fundo
  </button>

O conteúdo que fica por baixo de #dim-bg inclui botões, textos, imagens, as vezes animações ou vídeos. Não quero usar JavaScript para simular os efeitos de animação.
Minha dúvida é: tenho a performance geral reduzida por ter uma div invisível por cima de tudo? Há alguma contra indicação em fazer isso?

Minha dúvida surgiu depois de ler essa notícia, a qual foi publicada há bastante tempo, mas me deixou com uma pulga atrás da orelha.
Comment: Primeiro de tudo, você está tendo problemas de performance? Provavelmente não, certo? Então não tem muito motivo para se preocupar, mesmo que tenha uma forma de se fazer melhor, a diferença será ínfima, dificilmente você conseguiria mensurar, além disso, pode variar de navegador para navegador e entre suas versões. Mas, se você realmente quer fazer da melhor forma possível, provavelmente o ideal é você não manter essa div renderizada sempre, quando precisar, adicione ela ao DOM, quando não precisar mais, a remova
Answer:
Minha dúvida é: tenho a performance geral reduzida por ter uma div invisível por cima de tudo? Há alguma contra indicação em fazer isso?

Resposta curta: Sim. Mas é praticamente ínfima. Quanto mais DOM Nodes você tiver em seu documento, mais coisa pra baixar. O que diminui a performance caso esteja usando divs vazias em todo lugar e seu site seja complexo.
Esse artigo explica bem isso:
Don't fear empty divs
E esse do StackOverflow também esclarece bastante:
Are empty divs bad?
No artigo recomendam usar pseudoelementos (:before, :after) pra resolver o problema. Veja se consegue resolver. Se não, use divs vazias mesmo.

Minha dúvida surgiu depois de ler essa notícia, a qual foi publicada há bastante tempo, mas me deixou com uma pulga atrás da orelha.

Sobre a notícia:
Basicamente, a Google tava se aproveitando de alguns problemas no software da Microsoft. Nesse artigo eles disseram que resolveram o problema no Windows 10.

Joshua Bakita wrote:
I very recently worked on the Edge team, and one of the reasons we decided to end EdgeHTML was because Google kept making changes to its sites that broke other browsers, and we couldn't keep up. For example, they recently added a hidden empty div over YouTube videos that causes our hardware acceleration fast-path to bail (should now be fixed in Win10 Oct update). Prior to that, our fairly state-of-the-art video acceleration put us well ahead of Chrome on video playback time on battery, but almost the instant they broke things on YouTube, they started advertising Chrome's dominance over Edge on video-watching battery life. What makes it so sad, is that their claimed dominance was not due to ingenious optimization work by Chrome, but due to a failure of YouTube. On the whole, they only made the web slower.

Então, vá e escreva seu código sem se preocupar.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How many configurations are possible for this unique circle-arrow arrangement?

Question: 8 unique points - A,B,C,D,E,F,G,H are arranged symmetrically on a circle. You are given 8 arrows. You have to connect these 8 points with these arrows in such a way that:

You can connect a point only to its adjacent points (A->B connection is possible, but A->C connection is not possible, unless A and C are adjacent points).

There should be at least AND at most 1 arrow directed outwards from all points (Directed outwards means that tail of the arrow has to be on the point and tip of the arrow on its adjacent point).

How many such configuration are possible? (You have to use all 8 arrows in a configuration)
Here is one such configuration:
enter image description here
Comment: Each point $A-H$ has one arrow starting from it, and that arrow can go in two different directions, so the obvious answer is $2^8=256$. Am I missing something?
Comment: Even I thought the same, but since the question seemed a bit twisted, I thought maybe I was overcounting or something. Thanks.
Answer:
Count the number of ways to position the eight points on the circle.
For each point, there are two choices for the arrow directing outward from that point.
Account for over-counting. If you rotate a configuration, does it count as a different configuration? If you flip a configuration so that the arrangement of the points is in reverse order, but the arrows still start and end at the same points, does it count as a different configuration? [This will depend on the question-asker, it is not particularly clear to me from the question statement as-is.]


Codingbat challenge: notAlone Stream API Solution

Question: Given the task notAlone from CodingBat:

We'll say that an element in an array is "alone" if there are values
before and after it, and those values are different from it.
Return a
version of the given array where every instance of the given value
which is alone is replaced by whichever value to its left or right is
larger.

notAlone([1, 2, 3], 2)            →   [1, 3, 3]
notAlone([1, 2, 3, 2, 5, 2], 2)   →   [1, 3, 3, 5, 5, 2]
notAlone([3, 4], 3)               →   [3, 4]

My solution to this problem passes the vast majority of the tests, but not all of them:
public int[] notAlone(int[] nums, int val) {
  int[] notAlone = new int[nums.length];
  int largestNeighbour = 0;

  if (notAlone.length >= 1) {
    notAlone[0] = nums[0];
    notAlone[notAlone.length - 1] = nums[nums.length - 1];
  }

  for (int i = 1; i < notAlone.length - 1; i++) {
    if (nums[i] != val) {
      notAlone[i] = nums[i];
    }

    if (nums[i] == val) {
      notAlone[i] = Math.max(nums[i - 1], nums[i + 1]);
    }
  }

  return notAlone;
}

My questions are the following:
What can be done in order to fix my solution?
Is it possible to solve this task using Stream API ?
Test results
Comment: I have removed the inline image (and reverted to just a link), because of the excessive whitespace in the image. Please crop the image. It also looks like something that could have been posted as a markdown table instead.
Comment: `if (nums[i] == val)` could be replaced by `else`.
Answer:
element in an array is "alone" if there are values before and after it, and those values are different from it

Your solution doesn't pass all tests because you're not checking whether the current array element is alone or not, i.e. you're only checking if the current element is equal to the target value, but not if there's an equal element on the left or on the right.
That's how it can be done using streams, the code below passes all tests on CodingBat:
public int[] notAlone(int[] nums, int val) {
    return IntStream.range(0, nums.length)
        .map(i -> isAlone(nums, val, i) ?
            Math.max(nums[i - 1], nums[i + 1]) : nums[i])
        .toArray();
}

public boolean isAlone(int[] nums, int val, int i) {
    return nums[i] == val && i > 0 && i < nums.length - 1
        && nums[i - 1] != val && nums[i + 1] != val;
}

The imperative code you've provided can be fixed like that (passes all test):
public int[] notAlone(int[] nums, int val) {
    if (nums.length == 0) return nums; // guarding against an empty array

    int[] notAlone = new int[nums.length];
    notAlone[0] = nums[0];
    notAlone[nums.length - 1] = nums[nums.length - 1];

    for (int i = 1; i < notAlone.length - 1; i++) {
        if (nums[i] == val && nums[i - 1] != val && nums[i + 1] != val) { // is "alone"
            notAlone[i] = Math.max(nums[i - 1], nums[i + 1]);
        } else { // is not "alone"
            notAlone[i] = nums[i];
        }
    }

    return notAlone;
}


Somar valores de várias linhas sob condição

Question: Boa tarde senhores, tenho uma consulta que me retorna alguns campos preciso da soma deles, só que perante uma condição
 select adm.adm_ds_administradora as descricao,
        sum(car.car_vl_cartao) as valor,
        'Cartão TEF'        as cartao,
        cast ('' as varchar) as fun_ds_funcionario,
        cast ('' as varchar) as ntd_vl_acrescimo,
        cast ('' as varchar) as ntd_vl_desconto,
        cast ('' as varchar) as ntd_vl_pago,
        cast ('' as varchar) as ntd_vl_saldo,
        cast ('' as varchar) as agrupamento,
        rank() over(
 order by adm.adm_ds_administradora) as ordenacao,
          adm.adm_fl_tipo,
          *CASE WHEN adm.adm_fl_tipo = 'D' then
            SUM(car.car_vl_cartao)
          END as total,*
          1 as CONSTANTE
 from financeiro.cartao car,
      cadastro.administradora adm
 where car.car_cd_administradora = adm.adm_cd_administradora
       and car.car_cd_caixa in (576785)
       and adm.adm_ds_bandeira_tef is not null
 group by adm.adm_cd_administradora
 order by 3,
          ordenacao,
          1

(CASE WHEN adm.adm_fl_tipo = 'D' then
                SUM(car.car_vl_cartao)
              END as total,) Não está funcionando!

Preciso de um total acumulativo para quando o tipo for igual a 'C' e quando for igual a 'D'.Ir somando os valores onde o tipo for igual a 'C' simplificando.
Comment: Mesmo com o else não está funcionando.
Comment: coloca adm_fl_tipo no group by
Comment: Fiz isso, mudou nada, pois os tipos são iguais mas valores diferem..Pensei em usar laço de repetição talvez.. não sei
Comment: monta o ambiente aqui por favor: http://sqlfiddle.com/#!15
Answer: A função de agregação sum() deve ficar fora do CASE, veja só:
SUM( CASE WHEN adm.adm_fl_tipo = 'D' THEN car.car_vl_cartao ELSE 0 END ) AS total

Isso vai fazer com que o valor zero (0) seja somado ao resultado total sempre que a condição do CASE WHEN não for verdadeira.
Answer: RESOLVIDO:
sum(sum(car.car_vl_cartao) filter(where adm.adm_fl_tipo = 'D')) over(order by adm.adm_ds_administradora) as accum_debito,
sum(sum(car.car_vl_cartao) filter(where adm.adm_fl_tipo = 'C')) over(order by adm.adm_ds_administradora) as accum_credito,

Desta forma acima, consegui fazer os acumulativos, obrigado a todos que contribuíram de alguma forma.


How many potential different endings are there for a football match?

Question: To narrow down the scope of the question, I mean a scenario of a World Cup final where by end of the day one of the teams is declared a winner. E.g. there's a team scoring more goals during normal time, team scoring more goals during penalty shootouts, etc. What further options does the rulebook provide?
Answer: The laws provide for only three different endings to a football match, regardless of how they arise.

One team wins
The match is drawn
The match is abandoned

The first two cases are determined from Law 10.2, Winning team, as either one team has scored more goals (that team wins) or neither team has (match is drawn).
The competition may require a winning team, where case 2 must become case 1, through away goals or extra time or through kicks from the penalty mark (or any combination of these). The result is still case 1.
The last case is determined from Law 5.3, Powers and Duties [of the Referee], where the match may be abandoned "for any offences or because of outside interference". If replayed, the result must then again be one of the 3 cases.
Practically speaking, there are seven final "endings" to a competition match as differentiated by the details, not all of which may be actually possible for a particular match or competition.

One team scores more goals in normal time, and wins
The match is drawn after normal time, and one team scores more goals after extra time, and wins
The match is drawn after extra time, and one team scores more goals in the kicks from the penalty mark
The match is drawn
The match is forfeited by one team for whatever reason, and the opposing team wins
The match is forfeited by both teams for whatever reason, and neither team wins
The match is abandoned and is not replayed
Comment: "3. The match is abandoned" due to either "5. The match is forfeited by one team ..." or possibly "6. The match is forfeited by both teams ...".
Comment: If too many red cards are handed out or there's too many injuries, so that there's too few players on the field, what would the match result be?