Jquery calcular média e inserir o resultado no campo média que está disable

Question: Boa tarde,
Necessitava de fazer um calculo da média dos valores inseridos nas 4 caixas de texto, e só a aprecer o resultado da média na caixa de texto média após todos serem preenchidos
HTML

                                            MAT
                                            <input type="text" name="txtMat" id="txtMat" class="form-control media" placeholder="" required>

                                            C NAT
                                            <input type="text" name="txtCNat" id="txtCNat" class="form-control media" placeholder="" required>

                                            Média
                                            <input type="text" name="txtMedia" id="txtMedia" class="form-control" placeholder="" disabled required>

                                            LING
                                            <input type="text" name="txtLing" id="txtLing" class="form-control media" placeholder="" required>

                                            RED
                                            <input type="text" name="txtRed" id="txtRed" class="form-control media" placeholder="" required>

JQUERY:
$('.media').change(function(){

            var MAT = Number(document.getElementById("txtMat"));
            var CNAT = Number(document.getElementById("txtCNat"));
            var LING = Number(document.getElementById("txtLing"));
            var RED = Number(document.getElementById("txtRed"));

            var valorMAT = toNumber(MAT.value);
            var valorCNAT = toNumber(CNAT.value);
            var valorLING = toNumber(LING.value);
            var valorRED = toNumber(RED.value);

            MEDIA.textContent = ((valorMAT*45)+(valorCNAT*45)+(valorLING*5)+(valorRED*5))/100;

        });

Segue a imagem do layou
Comment: Olá, o que você fez até o momento? Posta um código aí que agente pode te ajudar.
Answer: Boa tarde,
Primeiramente, você deixou o evento bindado em um controle que esta disable, segundo você pega os controles joga em variável depois cria outras variáveis para receber o valor, tudo isso não é para funcionar de fato.
Fiz um exemplo com a media sendo gerada por um botão, assim temos como iniciar o processo que calcula.
$('#btnAcao').on('click',function(){
        //Guarda os valores dos controles em variaveis
        var MAT = parseFloat($("#txtMat").val());
        var CNAT = parseFloat($("#txtCNat").val());
        var LING = parseFloat($("#txtLing").val());
        var RED = parseFloat($("#txtRed").val());

        //Calcula os valores
        var media = ((MAT*45)+(CNAT*45)+(LING*5)+(RED*5))/100;

        //Atribui valor no campo media
        $('#txtMedia').val(media);

    });

Dei um parseFLoat pois não sei o tipo de dados que você irá trabalhar.
Veja aqui um exemplo no jsFiddler
Comment: Obrigado, perfeito, fiz só a alteração para o on.('change'...
Answer: Você pode usar a função filter() para checar se existem inputs vazios a cada evento de mudança, e, somente quando o número de inputs for zero o cálculo é realizado:
var temInputVazio = $('input').filter(function(){
  return this.value == '';
}).length;

if(!temInputVazio){
  // Tira a média.
}

Exemplo:

$(function() {

  // Função de média somente para exibição.
  var media = function(sel) {
    var soma = 0;
    $(sel).each(function() {
      soma += Number($(this).val());
    });
    return soma / $(sel).length;
  }

  $('input').on('change', function() {

    // Pega o número de inputs vazios.
    var temInputVazio = $('input').filter(function() {
      return this.value == '';
    }).length;

    // Se o 'length' for zero, todos foram preenchidos, então o cálculo é feito:
    if (!temInputVazio)
      $('p').text('A média é: ' + media($('input')));
  });

});

<input type='text' placeholder='MAT' />
<input type='text' placeholder='C NAT' />
<input type='text' placeholder='LING' />
<input type='text' placeholder='RED' />

Answer: Usando a mesma lógica mostrada no teu código, uma solução é verificar se algum input está vazio e sair da função utilizando o return. Veja esse exemplo.

$('input').on('change', function() {
  var $txtValor1 = $("#txtValor1");
  var $txtValor2 = $("#txtValor2");
  var $txtValor3 = $("#txtValor3");
  var $txtValor4 = $("#txtValor4");
  var $txtMedia = $("#txtMedia");

  if ($txtValor1.val() == '')
    return limparMedia();
  if ($txtValor2.val() == '')
    return limparMedia();
  if ($txtValor3.val() == '')
    return limparMedia();
  if ($txtValor4.val() == '')
    return limparMedia();

  var valor1 = parseFloat($txtValor1.val());
  var valor2 = parseFloat($txtValor2.val());
  var valor3 = parseFloat($txtValor3.val());
  var valor4 = parseFloat($txtValor4.val());

  var media = (valor1 + valor2 + valor3 + valor4) / 4;

  $txtMedia.val(media)

});

function limparMedia() {
  var $txtMedia = $("#txtMedia");
  $txtMedia.val('');
  return false;
}

Valor 1:
<input type="text" id="txtValor1" />

Valor 2:
<input type="text" id="txtValor2" />

Valor 3:
<input type="text" id="txtValor3" />

Valor 4:
<input type="text" id="txtValor4" />

Média:
<input type="text" id="txtMedia" />

Porém acho que ainda é melhor seguir a dica do @RBoschini criando um botão para disparar o evento.


How to get the data between two strings from a file in tcl?

Question: In TCL Scripting:
I have a file in that i know how to search a string but how to get the line number when string is found.please answer me if it is possible
or
set fd [open test.txt r]
while {![eof $fd]} {
    set buffer [read $fd]
}

set lines [split $buffer "\n"]
if {[regexp "S1 Application Protocol" $lines]} {
    puts "string found"
} else {puts "not found"}

#puts $lines

#set i 0
#while {[regexp -start 0 "S1 Application Protocol" $line``s]==0}  {incr i
#puts $i
#}

#puts  [llength $lines]
#puts [lsearch -exact $buffer  S1]
#puts [lrange $lines 261 320]

in the above program i am getting the output as string found .if i will give the string other than in this file i am getting string not found.
Comment: What have you tried so far? You'll get a better response if you show us what you've done.
Comment: i tried with regexp command.i am able to find the string but how to find a line number from a file?
Answer: The easiest way is to use the fileutil::grep command:
package require fileutil

# Search for ipsum from test.txt
foreach match [fileutil::grep "ipsum" test.txt] {
    # Each match is file:line:text
    set match      [split $match ":"]
    set lineNumber [lindex $match 1]
    set lineText   [lindex $match 2]

    # do something with lineNumber and lineText
    puts "$lineNumber - $lineText"
}

Update
I realized that if the line contains colon, then lineText is truncated at the third colon. So, instead of:
    set lineText   [lindex $match 2]

we need:
    set lineText   [join [lrange $match 2 end] ":"]

Answer: The concept of 'a line' is just a convention that we layer on top of the stream of data that we get from a file.  So if you want to work with line numbers then you have to calculate them yourself.  The gets command documnetion contains the following example:
set chan [open "some.file.txt"]
set lineNumber 0
while {[gets $chan line] >= 0} {
    puts "[incr lineNumber]: $line"
}
close $chan

So you just need to replace the puts statement with your code to find the pattern of text you want to find and when you find it the value of $line gives you the line number.
To copy text that lies between two other lines I'd use something like the following
set chan [open "some.file.txt"]
set out [open "output.file.txt" "w"]
set lineNumber 0
# Read until we find the start pattern
while {[gets $chan line] >= 0} {
    incr lineNumber
    if { [string match "startpattern" $line]} {
        # Now read until we find the stop pattern
        while {[gets $chan line] >= 0} {
            incr lineNumber
            if { [string match "stoppattern" $line] } {
                close $out
                break
            } else {
                puts $out $line
            }
        }
    }
}
close $chan

Comment: thanks for your helping but it is working only for startin string. after that it is not working.it is copying all the file after finding first string
Comment: So what does your data file look like? What are the start and stop strings? Have you checked that your detecting the stop string correctly? Can you post a short datafile, 6 lines or so that doesn't work?
Comment: hi thanks for your solution.i am getting the data between the 2 strings but the error  message it is showing
C:\Users\atangutu\Desktop\anwesh>tclsh task1.tcl
can not find channel named "file1276940"
    while executing
"puts $out $line"
    ("while" body line 11)
    invoked from within
"while {[gets $chan line] >= 0} {
    incr lineNumber
    if { [string match "S1 Application Protocol" $line]} {
        # Now read until we find the s..."
    (file "task1.tcl" line 5)

C:\Users\atangutu\Desktop\anwesh>


GetPrivateProfileString() Gives Access Denied Error on Vista

Question: A GetPrivateProfileString() call works fine on Windows XP but fails with an Access Denied error when run on Vista.
The call is being made inside a thread spawned by a Windows service which I wrote. The Windows service itself is run using the credentials of a user account on the local machine (thought to be needed because the code requires access to HKCU).
I suspect this has something to do with the UAC or virtualization.
I would welcome any suggestions on how I can get this call to work on Vista, or on experiments I can run to help track down a solution.
Thanks
Answer: Parts of the Windows registry are locked down in Vista for security reasons.
For example if you are trying to access the HKEY_LOCAL_MACHINE this will fail for a user with out the correct privileges.
If you give the user a sufficient privilege level they will be able to access the registry but the recommended approach is to move the registry settings to the HKEY_CURRENT_USER branch of the registry, since this is not locked and is accessible by all users.
Comment: Just to clarify, my problem here is not accessing the HKLM but reading a setting out of .INI file located on network share.


Bayesian comparison of differing model size

Question: This issue is related to a real problem, but I've boiled down to a minimal example.
Simplest version
Suppose I get to observe two variables, $X_1$ and $X_2$. We can think of these data being generated by a mixture/hierarchical model, in which they have a 50% chance of actually being the same uniform(0, $\alpha$) and 50% chance of being two independent draws from a uniform(0, $\alpha$), where $\alpha$ is known in advance. We can more formally define this as
$Z \sim \text{Bern}(0.5)$
If $Z = 0$, $X_1 = X_2 \sim \text{Unif}(0, \alpha)$
If $Z = 1$, $X_1 \sim \text{Unif}(0, \alpha), X_2 \sim \text{Unif}(0, \alpha)$
and we observe $X_1, X_2$ but not $Z$.
Now let's suppose we observe $X_1 = X_2 = \alpha/2$. This case, we should know that they must have come from the same uniform variable (i.e., $Z = 0$), as the probability that two continuous variables are exactly equivalent is 0.
But what happens to the posterior? If we want to calculate
$P(Z = 0 | X_1 = X_2 = \alpha/2) =$
$\frac{P(Z = 0 \land X_1 = \alpha/2 \land X_2 = \alpha/2)}{
P(X_1 = \alpha/2 \land X_2 = \alpha/2)}$
Here's definitely where the issue lies, but as we normally apply Bayes Theorem, we would switch to density functions for $X_1$ and $X_2$. In that case, we would get that
$f_{X_1, X_2|Z = 0}(x_1, x_2) = \alpha^{-1}$ if $x_1 = x_2 \land x_1 \in [0, \alpha]$.
Similarly,
$f_{X_1, X_2|Z = 1}(x_1, x_2) = \alpha^{-2}$ if $x_1, x_2 \in [0, \alpha]$.
If we plug that back into our original problem, we get something that is clearly wrong:
$P(Z = 0 | X_1 = X_2 = \alpha/2) = \frac{0.5 \times \alpha^{-1}}{0.5 \times \alpha^{-1} + 0.5 \times \alpha^{-2}} = \frac{1}{1 + \alpha^{-1}}$
Not only is that not 1, it approaches 0 as $\alpha$ approaches 0!
Above has a clear answer and you can at least reason with it by saying that the issue is that $x_1 = x_2$ is infinitely more likely if $Z = 0$...but directly looking at the density functions does not make this obvious. In general, how should I have recognized this type of error when comparing two models of differing dimensions?
Answer: The problem presented here is not a problem of comparing models of different dimensions. The problem is that the model is incomplete. We can amend the model by defining a joint distribution for $X_1, X_2$ using a conditional distribution as follows:
$Z \sim \text{Bernoulli}(0.5)$
$X_1 \sim \text{Uniform}(0, \alpha)$
$X_2 | Z = 1, X_1=x_1 \sim \text{Uniform}(0, \alpha)$
$X_2 | Z = 0, X_1=x_1 \sim \delta_{x_1}$
$\delta_{x_1}$ is the Dirac measure or Dirac delta (density) function (point mass) at $x_1$; you can think of it as a $\text{Normal}(x_1, \sigma^2)$ distribution with $\sigma^2\to 0$. This is the key component missing from your original model.
Next we plug everything into Bayes formula
$P(Z | X_1, X_2) \propto P(Z)P(X_1 | Z)P(X_2 | Z, X_1)$
If $X_1=X_2$, then
$P(Z=1 | X_1=x_1, X_2 = x_1) \propto 0.5 (\alpha^{-1})\alpha^{-1} $
$P(Z=0 | X_1=x_1, X_2 = x_1) \propto P(Z=0, X_1=x_1, X_2 = x_1) = 0.5(\alpha^{-1}) \infty = \infty $, thus the posterior is a $\text{Bernoulli}(0.0)$.
Otherwise
$P(Z=1 | X_1=x_1, X_2 = x_2) \propto 0.5(\alpha^{-1})\alpha^{-1}$
$P(Z=0 | X_1=x_1, X_2 = x_2) \propto 0.5(\alpha^{-1})0 = 0$ implying the posterior is a $\text{Bernoulli}(1.0)$.
The Spike and slab (regression setting) model is an indirectly related topic that may be of interest to you. In short, it is a mixture model consisting of a discrete component and a continuous component.
Comment: Can you explain why the previous model is incomplete? I think the fallacy comes from the fact that we're defining a 2D density function ($f_{X_1, X_2 | Z = 0}$) that only has positive density along a single line.
Comment: What you wrote is correct, and a more formal version of the statement "Above has a clear answer and you can at least reason with it by saying that the issue is that
$x_1=x_2$ is infinitely more likely if $Z=0$", but I'm really interested in understanding the mistake in the naïve approach.
Comment: Actually, I am not sure I am correct to state that the model is incomplete, maybe someone more knowledgeable can comment on it. With that said, your first comment points out the right idea. There is a clear dependence between $X_1$ and $X_2$, thus we should state its dependence (one or depending on the other or vice versa)  mathematically, and that is where the Dirac measure came in. Once we have a condition and a marginal, we can combine them to form a joint distribution, so we no longer have a density "along a single line". In summary: we need a joint distribution. I hope that helps.


Unable to locate package openjdk-7-jdk

Question: I am using a base edition of Debian and am trying to install Java 7 on it using this command:
root@server:~# apt-get install openjdk-7-jdk

However, I end up getting this error:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package openjdk-7-jdk

It seems like the package is not in the repository, so I am not sure how to proceed.
Answer: Try a quick apt-get update to get the latest package lists from repos, and then apt-cache search openjdk to check out what the latest offered version is that's available to you, if any are.
Most likely if this is a fresh base install you're going to have to go into your /etc/apt/sources.list and make sure you have the non-free package lists enabled, which aren't enabled by default in Debian I believe. So check this How do I enable non-free packages on Debian?

Unable to locate package openjdk-7-jdk


Centralizar conteúdo

Question: Estou fazendo um teclado em HTML e CSS mas não estou conseguindo centralizar o conteúdo, ou fica em left como no exemplo abaixo ou em right, como posso centralizar?

#calculator {
  width: 720px;
  height: auto;
  padding: 0;
  border-radius: 5px;
}

.keys {
  overflow: hidden;
}

.keys span {
  float: left;
  position: relative;
  top: 0;
  background: #FFFF00;
  font-size: 24px;
  cursor: pointer;
  width: 64px;
  height: 42px;
  border-radius: 5px;
  box-shadow: 0px 4px rgba(206, 206, 0, 1);
  margin: 0 7px 11px 0;
  color: #000;
  line-height: 44px;
  text-align: center;
  user-select: none;
  outline: 0 solid;
  transition: all 0.2s ease;
}

.keys span:hover {
  background: #fff;
  color: #000;
}

.keys span:active {
  box-shadow: 0px 0px #6b54d3;
  top: 4px;
}

    Q
    W
    E
    R
    T
    Y
    U
    I
    O
    P

    A
    S
    D
    F
    G
    H
    J
    K
    L

    Z
    X
    C
    V
    B
    N
    M
    Ç

    <<

https://codepen.io/anon/pen/JqxQqQ
Answer: Você está usando float: left nos spans, por isso fica tudo à esquerda.
Retire o float: left e adicione duas propriedades:
vertical-align: top;
display: inline-block;

A primeira para alinhar os elementos verticalmente, e a segunda (display) para que os spans possam ser redimensionados.
E finalmente coloque as propriedades font-size: 0; (para remover espaços entre os spans) e text-align: center; (para centralizar horizontalmente) na div#calculator:

#calculator {
  width: 720px;
  height: auto;
  padding: 0;
  border-radius: 5px;
  text-align: center;
  font-size: 0;
}

.keys {
  overflow: hidden;
}

.keys span {
  /*float: left;*/
  vertical-align: top;
  display: inline-block;
  position: relative;
  top: 0;
  background: #FFFF00;
  font-size: 24px;
  cursor: pointer;
  width: 64px;
  height: 42px;
  border-radius: 5px;
  box-shadow: 0px 4px rgba(206, 206, 0, 1);
  margin: 0 7px 11px 0;
  color: #000;
  line-height: 44px;
  text-align: center;
  user-select: none;
  outline: 0 solid;
  transition: all 0.2s ease;
}

.keys span:hover {
  background: #fff;
  color: #000;
}

.keys span:active {
  box-shadow: 0px 0px #6b54d3;
  top: 4px;
}

    Q
    W
    E
    R
    T
    Y
    U
    I
    O
    P

    A
    S
    D
    F
    G
    H
    J
    K
    L

    Z
    X
    C
    V
    B
    N
    M
    Ç

    <<

Comment: era exatamente isso, obrigado pela ajuda vou dar uma estudada.

Centralizar conteúdo


Calling a view from code gives no results

Question: I have a view that I use to grab a related node field given a user ID. I only call this view from code. The problem is, I just can't get it to work for a certain case.
To start with, here's the code that I use to call the view. The view accepts one argument (the user ID) and displays one field (the related node field). (I use multiple displays in this view for different code functions, thus why I build 'block_3'. Also, I'm calling this code from within a "User has logged in" Rule, which is why I use $account instead of global $user.)
$view = views_get_view('my_view_name');
$view->set_arguments( $account->uid );
$view->build('block_3');
$view->execute();

For the user ID "5", this works perfectly. But for the user ID "14", it returns no results. The frustrating part is that in the View settings, I can enter "14" for the preview argument and it ALSO works perfectly!
I'm at my wit's end. Why would the view work perfectly fine in the preview and for one user ID, but not for another?
Some notes
I've confirmed with dpm() that $account->uid is being set properly. I've also changed User ID 14's roles to match User ID 5's, and even swapped the related nodes for the two accounts, but User ID 14 always fails to work while User ID 5 has no issues.
If I pass $view->result to dpm(), I get empty text; dpm($view) returns the $view object, where I can see that $view->result is an empty text.
Answer: The View set_arguments() method takes an array as it's first parameter; currently you're passing a string/int.
This code will work.
$view->set_arguments(array($account->uid));

I think you're right about the C-style access to a string-as-an-array-of-chars in PHP. The following code prints the letter e, which would certainly support that theory.
$x = 'test';
print $x[1];

I must say I'm surprised that Views doesn't check the validity of the parameter passed to it, but hey ho!
Answer: Don't you need to print the output, or return it in an output variable?
I've used something to this before.
print views_embed_view($name, $display_id);

Use print in a template file; use $output = in a module.
View arguments can follow the display ID.
Comment: Sorry, I neglected the output code because I just use the generated result as another php variable. Here's what it looks like.

`$node_field_value = $view->result[0]->node_data_field_user_account_field_person_id_value;`


Expansion of $e^x$ - correct form

Question: I have come across in a textbook to an expansion of e to the x in the following form:
$$
1+ \frac1x + \frac1{x^2} + \frac1{x^3} + \ldots
$$
Is the above correct or is it a typo?
I am familiar with this type of expansion for e to the x:
$$
1+ \frac{x}{1!} + \frac{x^2}{2!} + \frac{x^3}{3!} + \ldots
$$
Are they both correct? If yes, how is the first one above arrived at? I could not find it online anywhere.
Thank you in advance.
Comment: No.  There is a unique expansion of $e^x$.  The second one you list is it.
Comment: The first one is a geometric series and sums to $\frac{1}{1-\frac{1}{x}} = \frac{x}{x-1}$ when $|x|>1.$
Comment: The second provide an upper bound for $e^x$ for $x<1$.  It is not equal to $e^x$ unless $x=0$.
Comment: The second series is exactly equal to $e^x$ for all real numbers $x$.
Answer: Note the first series has a ratio of terms of $1/x$, thus, assuming $|1/x| < 1$,
$$
\sum_{k=0}^\infty \frac1{x^k}
 = \sum_{k=0}^\infty (1/x)^k
 = \frac{1}{1-(1/x)}
 = \frac{x}{x-1}
 = 1 + \frac{1}{x-1} \ne e^x.
$$
Comment: ok. So my math is not so great. but i guess you are saying that the textbook with that form of expansion for e^x is actually wrong then?
Comment: @adriano yes, that expansion is incorrect
Comment: thank you for confirming

Expansion of $e^x$ - correct form


Is there a measure other than variance to know dispersion?

Question: I have (x,y) values where x are integers that range from 0 to 843, and there is only one y value per x value.
And then I have a set S, which are (x,y) values. If an element of S is selected, it should add up to the y value of the corresponding x in the above (x, y) values.
I want to select a subset of S, that would make the sum of all y values close to N while having the y values distributed flat (i.e., (x,y) graph looking as if it is a straight vertical line if seen in a bigger scale).
I tried with variance, having variance biggest as possible, but it would also make only the y values of the beginning and end big.
So I wonder if there's any other measure to use or whether I should add any other metrics to achieve my goal along with variance. Thank you!
Comment: It is not altogether clare what you want, but it looks like a measure of ûniformity^is what you need, not dispersion. Entropy is one such, see https://stats.stackexchange.com/questions/484406/how-to-measure-whether-a-discrete-distribution-is-uniform-or-not  and search this site!
Comment: Is the number of selected elements fixed? Or are you happy with any number as long as the sum of the $y$ is close to $N$ and the distribution of $y$ "flat"? A problem here is that "flatness" may be hard to compare between different numbers of elements. If you select just one element with $y=N$, is this flat or not? Also, "flatness" may depend on whether the $x$ are distributed more or less uniformly (for example there could be lots of $x$ on the left side and a lonely one far on the right side).
Comment: @ChristianHennig I want it to be flat in that if seen in a bird eyes' view when drawn a line between the x,y values it will be something without any peak. Ideally, all the values to be y=N/843
Also, the number of selected elements is not fixed
Comment: If you want all the values of $y$ approximately equal, you want *low* variance, not high.
Comment: @ChristianHennig Oh I tried with weighted variance while having the x values as weight, instead of calculating the variance of the occurrence of y.
Comment: @kjetilbhalvorsen wow thank you so much!! I think entropy is one of the measure I can use!
Answer: I was able to achieve my goal by using entropy. Since I want the distribution to be seen uniformly on a larger scale, I used binning and then calculated the entropy. I used this approach with multiple bin sizes together.


Calculate height of div with dynamically populate ID value

Question: I have a div tag in in my JSP page. Its ID is autopopulated by other parameters that I don't have control over.
The div tag looks like this. I am skipping the contents in the div in this post.

I want to calculate the height of this div. I was able make that work for div with static ID
$(".testt").height();

http://jsfiddle.net/m7cyw70y/
How can I use the nodeId variable value in the JS to get the div's height? My JS code is in in the JSP page wrapped around script tags.
Answer: You can use another attribute instead of the id. An example using the class attribute:
$('div.parallax').height();

You can also use a custom attribute:

$("div[custom-attr='myCustomAttr']").height();

There are even more approaches.
Comment: You can use the `eq(index)` to filter which div you are getting: `$('div.parallax').eq(0).height();`. Also there are more ways to filter a colection of elements called by a generic selector.
Comment: Yes, certainly. But I have a few more divs with same class but all of them have different IDs. So I want to use the ID to get the height.
Answer: In the JS code, use the auto-populated parameters to your benefit on server-side:
var nodeToGetHeight = "${nodeId}";
$("#" + nodeToGetHeight).height();

These auto-populated parameters could be used to populate an array that could then be looped through for multiple heights.


HTML tags are stripped away

Question: I'm new with Drupal but have to use it to develop a web form for my workplace. I have to insert a form in a drupal web page and I am allowed to insert it in full HTML.
However, since I must paste code directly in a little editor box, I have to cut all my CSS code and paste it in a
            <form action="" method="post">

                        Your Name
                        <input class="u-full-width" name="user_name" id="user_name" placeholder="John Doe" type="text"></input>

                        Your E-mail
                        <input class="u-full-width" name="email" id="email" placeholder="email@example.com" type="email"></input>

                        Request Description
                        <textarea class="u-full-width" name="job_description" id="job_description" placeholder="Description of your job here" style="height:200px"></textarea>

                        Request Support For
                        <select class="u-full-width" name="purpose" id="purpose">
                            <option value="simulation">Simulation</option>
                            <option value="detector_development">Detector Development</option>
                            <option value="detector_electronics">Detector Electronics</option>
                            <option value="electronics_development">Electronics Development</option>
                            <option value="data_acquisition">Data Aquisition</option>
                        </select>

                            <input type="checkbox" name="sub_support" value="sub_support">Mechanical</input>
                            <input style="margin-left:10%;" type="checkbox" name="sub_support" value="sub_support">PCB</input>
                            <input style="margin-left:10%;"  type="checkbox" name="sub_support" value="sub_support">Firmware</input>
                            <input style="margin-left:10%;"  type="checkbox" name="sub_support" value="sub_support">DAQ Hardware</input>

                <input class="button-primary" value="Submit" type="submit" name="submit" id="submit">
            </form>

Also, is there any way I can include PHP code as well?
I'd be grateful if anyone could point me in the right direction.
Thanks in advance.
Answer: There are several answers to this. I am assuming that you are using Drupal 7.
1) If this is really what you want to do (not recommended), you'll need to do some work with your text filters (Configuration->Content Authoring->Text Formats). I could go into greater detail here, however..
2) You could simply use the Webform module. You will need to download it to your modules folder (probably sites/all/modules/contrib) and then enable it. Then you can construct your webform using the webform's UI editor. Finally, you would want to apply your CSS in your theme, not paste it into the editor textarea.
As for the PHP Filter, this is a module you can just turn on and then configure like the other Text Formats (the module is just called "php"). However, I would STRONGLY recommend against it! Certainly do not do this on a production site, it's a pretty big security risk. It also makes it very easy to put code someplace in your content that you later forget about, causing all kinds of headaches when you go to troubleshoot issues. Instead, create your own module. Learn how to use Drupal's function hooks instead. They are one of the reasons Drupal is such a powerful platform.
Good luck!

HTML tags are stripped away


How to create a block to show a digital clock?

Question: I need to create a block to show a LIVE digital clock?
I tried to use the http://drupal.org/project/clock and the http://drupal.org/project/jstimer  modules but it doesn't use javascript to refresh the time, it shows the time when the page is load, to refresh the time I need to reload the page.
How can I do this?
Something like this http://drupal.org/project/timeblock but for D7
Comment: have you looked at how simple the timeblock module is and how easily it could be incorporated into a/your D7 site?
Comment: (although its use of a body element is puzzling/troublesome :)
Comment: Amazing what one can find when you start peeking in 3rd party code.
Answer: 100% agree with Jimajamma above on extracting the stuff you need from the timeblock module, all it is really doing is just adding two javascript blocks with a minimal amount of formatting. For example, to replicate the 24-hour clock, all you have to do is create a new block with an 'unformatted' input format and add this code (extracted from the time block module):

Quick fix to replace the body unload with a jquery $(document).ready() call, though probably not necessary inside a block.
Comment: yep, and fix the formatting bug still found in the original code: `if (hours<12)` should be `if (hours<=9)` so you have 01-09 but not 011 or 010 :)
Comment: yeah. Nice catch ;)


Intuition behind the Formula for an estimator

Question: An estimator for a set of i.i.d samples drawn from a Gaussian distribution can be
$ \sigma^{2}_{m} = \frac{1}{m}\sum_{i=1}^{m} (x^{(i)} - \mu_{m})^{2}$
this is called the sample variance and $\mu_{m} = \frac{1}{m}\sum_{i=1}^{m} x^{i} $ is the sample mean. As $x^{(i)}$ is a random variable (a sample drawn from the Gaussian distribution), how do we proceed to calculate $\sigma_{m}^{2}$? if $x^{(i)}$ were data points, it would have been obvious but this is not the case here. Should we calculate $\sigma_{i}^{2}$ for $i=1,..,m$ for each sample $x^{(i)}$ and then sum them over?
Comment: A random sample of length $m, m \in \mathbb{N}$ is a set of realizations of $m$ independent, identically distributed (iid) random variables with distribution F: https://en.wikipedia.org/wiki/Sample_(statistics) Hence, sample consists of observations and not of random variables. Sample variance is calcualted based on the observations as well: https://en.wikipedia.org/wiki/Variance  What exactly does your notation $x^{(i)}$ mean?
Comment: To be honest, I do not think that this book is very good in all of these mathematical nuances. I would write $E[X_i]$ or even $E[X]$ since all is iid. Maybe this answer can help you: https://stats.stackexchange.com/a/396949/324942. In brief, if you are interested in just an estimator for the data that you already have, then $\hat{\sigma}^2$ is just a number calculated from the observations, but if you would like to know the general properties of an estimator (like expectation, bias, asymptotic properties), then you should regard it as a function of random variables.
Comment: My source is Goodfellow's book (Introduction to deep learning). According to him: ${x^{1}, ... , x^{(m)}}$ are a set of samples that are independently and identically distributed according to a (let's say Gaussian) distribution $p(x^{(i)}) = N(x^{(i)}; \mu, \sigma^{2})$
Comment: I have only access to this book https://www.deeplearningbook.org/, but there in the notation (page xvi) it is said: $x^{(i)}$ The $i$-th example (input) from a dataset. So I guess they have in mind the observations, or real data points. Do you then maybe have $\mu_n = \frac{1}{m}\sum x^{(i)}$ as well? I would say it is a little uncommon notation from the point of statistical literature, but I guess in the machine learning literature it can be different.
Comment: I am referring to the page 125, Example: Gaussian Distribution Estimator of the Mean.
Comment: The notation is used consistently throughout the book. On page 123 the sample mean is also defined with the help of $x^{(i)}$, which is consistent with what I was telling about regarding $x^{(i)}$: it is a single observation. Moreover, on page 120 they say "let $\{x^{(1)}, \ldots, x^{(m)}\}$ be a set of $m$ independent and identically distributed data points" and they they define statistic based on this. What I am trying to say is that: an estimator or statistic is constructed based on the data you have. Personally I think that "a set of samples" is not used correctly here.
Comment: Thank you. What confuses me is that they have a derivation (equations 5.31 to 5.35) and there $E[x^{(i)}]$ is equal to $\mu$. If $x^{(i)}$ is only an observation then how should I justify this. This derivation is part of calculating the bias of the sample mean estimator.
Answer: Edited after reading comments below to avoid making two answers.
Consider $X_1, X_2,...,X_m$ an iid random sample.
Let $x_1, x_2,...,x_m$ a realization from $X_1, X_2,...,X_m$. Then $x_1, x_2,...,x_m$ are actual numbers. Since $X_1, X_2,...,X_m$ are iid, we can think of $x_1, x_2,...,x_m$ as m realizations of one stochastic variable $X$ which is iid. with $X_1, X_2,...,X_m$ (or just $X_1$).
$\sigma^2_m=\sigma^2_m(X_1,X_2,...,X_m)$ as described above is called an estimator. The notation with $m$ is because $\sigma^2_m$ depends on the sample size. The stochastic variables $X_1, X_2,...,X_m$ are often suppressed in the notation.
In practice we cannot calculate $\sigma^2_m$ before we have an actual sample $x_1,..,x_m$ of known values. We call $\hat{\sigma^2_m}= \sigma^2_m(x_1,x_2,...,x_m)$ the estimate of $\sigma^2_m$.
For each sample there is one variance estimate, and one mean estimate.
I hope this helps with the confusion.
Comment: Thank you for your answer. So, what you mean is we calculate the estimate for just one random variable? doesn't it violate the definition above. I also need to mention that $\sigma_{m}^{2}$ is actually $\^\sigma_{m}^{2}$
Comment: It is sigma hat. I am not able to write it down correctly. My apologies.
Comment: Yes and no. $X_1, X_2,...,X_m$ are each one random variable, however they are i.i.d. so you can think of $x_1,...,x_m$ as $m$ realizations of one random variable, $X$ , that is identical distributed with $X_1$.
Comment: Thank you but I don't think I get it.
Comment: I tried to edit the answer above to incorporate the comments. I hope it improves the answer.


Does exponential family of distributions have finite expected value?

Question: I am curious about this question, because in definitions I have never seen this property. Is it true? If yes, why?
Comment: Don't they have finite moments?
Answer: As fairly well-explained on Wikipedia, for any exponential family, there exists a parameterisation such that the density of the family is$$f(x|\theta)=\exp\{\theta\cdot T(x)-\Psi(\theta)\}$$wrt a constant measure $\text{d}\mu(x)$, where the components of $T(\cdot)$ are linearly independent. In this representation, the moment generating function of the random variable $T(X)$ is given by$$M(\upsilon)=\exp\{\Psi(\theta+\upsilon)-\Psi(\theta)\}$$and therefore$$\Psi(\theta+\upsilon)-\Psi(\theta)$$ is the cumulant generating function for T. This implies that all order moments of $T(X)$ can be derived from the successive derivative of $\Psi(\theta)$, provided $\theta$ is within the interior of the natural parameter space$$\Theta=\{\theta;\ |A(\theta)|<\infty\}$$
However, if one is interested in the moments of $X$ itself, with density$$f(x|\theta)=\exp\{\theta\cdot T(x)-\Psi(\theta)\}$$there is no reason those moments are always well-defined. The generic reason is that the density of an arbitrary one-to-one transform $Y=\Xi(X)$ is then $$g(y|\theta)=\exp\{\theta\cdot (T\circ\Xi^{-1})(y)-\Psi(\theta)\}$$again the measure
$$\text{d}\xi(y) = \left| \frac{\text{d}\Xi{-1}}{\text{d}y}\right|\text{d}\mu(\Xi^{-1}(y)$$ Both $Y$ and $X$ thus share the same sufficient statistic in that $$(T\circ\Xi^{-1})(Y)=T(X)$$ as a random variable. The properties of this exponential family are thus characteristic of and characterised by the sufficient statistic, not $X$ or $Y$.

As exemplified by jbowman in a comment below, for the
  $X\sim\text{Ga}(\alpha,\beta)$ distribution, the intrinsic
  representation & sufficient statistic is $T(X)=\log X$. While $X$ has
  all (positive) moments finites, $Y=\exp\{X\}$ does not. And as pointed
  out by Glen_b, for the $X\sim\text{Pa}(\alpha,\beta)$
  distribution [which is indeed an exponential family when the lower
  bound $\beta$ is fixed], the moments are only defined up to the
  $\alpha-1$ order.
Comment: I like the answer; it's clean and to the point, but perhaps this distinction being discussed in comment could be more explicitly mentioned in the post. [One potential example -- for the Pareto, where $T(X)=\log(X)$; we'd have that $\log(X)$ has all finite moments (which is true), but $X$ may not.]
Comment: It's not totally clear to me that just because the sufficient statistics all have finite moments of all orders that $X$ itself does too.  It certainly seems plausible, but... think of the Gamma with known scale parameter.  The SS is $\Sigma \log x$.  Although in the case of the Gamma we know that $x$ has finite moments of all order, so this isn't a counterexample, the fact that $\log x$ does doesn't imply that $x$ itself does.  I could imagine some exponential family distribution with a similar result, but for which $X$ doesn't have finite moments of all orders.
Comment: Which is why my reply is only for $T(X)$. The question is meaningless without specifying which transform of $X$ has or has not a finite first moment, because there are transforms with infinite moments, at least for continuous families. Just consider that any bijective transform of $X$ has the same sufficient statistic $T(X)$.
Comment: So, for example, if I will show, that distribution(in the original form) doesn't have finite expectation, then this distribution cannot belong to the exponential family?
Comment: What do you mean by "original form"? Did you read the answer till the very end?


How to calculate a linear transformation given its effect on some vectors

Question: Im not sure if my question is worded very well, but I'm having trouble understanding how to tackle this problem.

Let $T\colon\mathbb{R}^3\to\mathbb{R}^2$ be the linear transformation such that $T(1,-1,2)=(-3,1)$ and $T(3,-1,1) = (-1,2)$. Find $T(9,-1,10)$.

Thanks
Comment: Linear transformations are linear. So try to express $(9, -1, 10)$ as a linear combination of $(1, -1, 2)$ and $(3, -1, 1)$.
Answer: Recall that a linear transformation is, well, linear. If you know the value at vectors $\mathbf{v}_1$ and $\mathbf{v}_2$, then you can compute the value at any linear combination of those two vectors, by using linearlity:
$$T(\alpha\mathbf{v}_1+\beta\mathbf{v}_2) = \alpha T(\mathbf{v}_1) + \beta T(\mathbf{v}_2).$$
Here, for example, you know the value of $T$ at $(1,-1,2)$ and at $(3,-1,1)$. So, for instance, you can easily calculate the value of $T$ at $(5,-3,5) = 2(1,-1,2)+(3,-1,1)$:
$$\begin{align*}
T(5,-3,5) &= T\Bigl( 2(1,-1,2) + (3,-1,1)\Bigr)\\
&= 2T(1,-1,2) + T(3,-1,1)\\
 &= 2(-3,1) + (-1,2)\\
&= (-7,4).\end{align*}$$
So... if you can find a way of writing $(9,-1,10)$ as a linear combination of $(1,-1,2)$ and $(3,-1,1)$, then you'll be set.
Added. Unfortunately, this cannot be done here. Namely, there are no scalars $a$ and $b$ such that $(9,-1,10) = a(1,-1,2) + b(3,-1,1)$. Note that you would need $a+3b=9$ and $-a-b=-1$. Adding these two you get $2b = 8$, so $b=4$; then $a=-3$, but then the last coordinate does not work out:
$$-3(1,-1,2) + 4(3,-1,1) = (-3+12, 3-4, -6+4) = (9,-1,-2).$$
So the information you have does not determine the value of $T$ at $(9,-1,10)$. Given any vector $(r,s)$ in $\mathbb{R}^2$, you can find a linear transformation $U$ that agrees with $T$ on $(1,-1,2)$, on $(3,-1,1)$, and that sends $(9,-1,10)$ to $(r,s)$.
That suggests to me that you have either miscopied the problem, or else that whoever assigned the problem made a mistake.  One possibility is that the first vector should have been $(1,-1,-2)$, as then you do get $(9,-1,10)$.
Comment: @user979616: The information you have been provided only determines $T$ uniquely in the span of the two given vectors. Given any one vector $\mathbf{w}$ *outside* the span, if you tell me your favorite vector $\mathbf{z}$ of $\mathbb{R}^2$ I can find a linear transformation that agrees with $T$ on $(1,-1,3)$ and $(3,-1,1)$, but sends $\mathbf{w}$ to $\mathbf{z}$. Change your opinion on what your favorite vector of $\mathbb{R}^2$ is, I can give you a new linear transformation that sends $\mathbf{w}$ to your new favorite vector. So... no. You need the values at a basis to uniquely determine $T$.
Comment: Ok. Is it possible to find T for a vector that can't be represented by the other 2? Or does this not work?


Default Priors for Intercept and Standard Deviations in R package brms

Question: The only resource I found explaining the default priors in brms is its manual (newest version, updated 03/14/2021) for function set_prior().
For the intercept, the manual does not specify how the default prior is selected. When I fit a generalized linear mixed-effects model (GLMM), it appeared to be Normal(0, scale), but I am not sure how the scale was determined.
For standard deviations, such as the ones for group-level random effects and for the Gaussian auxiliary parameter (residual standard deviation), the default prior is a half student-t distribution t(3, 0, scale). The manual describes that the scale "depends on the standard deviation of the response after applying the link function. Minimally, the scale parameter is 2.5". However I cannot find any details on this dependency.
In comparison, the default priors implemented by another package rstanarm has clear descriptions on their default prior choices especially on how the scales are determined.
I wonder if anyone knows more about
(1) the default prior distribution for the intercept,
(2) how the scale is determined for the half student-t for the standard deviations in brms.
Answer: brms seems to use a combination of uniform priors and weakly informative priors based on the data you give it. You can run brms::prior_summary(your_model_fit_object) to see what it has chosen. If the prior is blank, that means it has chosen a uniform prior.


Zabbix Agent unable to read /var/log/messages

Question: So I am trying to monitor the logs of a VM running Centos 7. Specifically the one giving problems is /var/log/messages. I have changed both the group ownership of the file ( made the pertaining change in logrotate.conf ) and manually on the already created file. Below you can see the permissions of it :
[matias@Centos_7_VM ~]$ sudo ls -lh /var/log/messages
-rw-rwx---+ 1 root zabbix 889K jul 25 10:53 /var/log/messages
[matias@Centos_7_VM ~]$ getfacl /var/log/messages
getfacl: Removing leading '/' from absolute path names
# file: var/log/messages
# owner: root
# group: zabbix
user::rw-
user:zabbix:rwx
group::---
mask::rwx
other::---

But even with all of those changes, the zabbix agent is getting permission denied to read that log. Is there something else blocking that process from reading the file?
Agent log
993:20180725:062459.211 Starting Zabbix Agent [Centos_7_VM]. Zabbix 3.2.11 (revision 76339).
   993:20180725:062459.256 **** Enabled features ****
   993:20180725:062459.257 IPv6 support:          YES
   993:20180725:062459.257 TLS support:           YES
   993:20180725:062459.257 **************************
   993:20180725:062459.257 using configuration file: /etc/zabbix/zabbix_agentd.conf
   993:20180725:062459.303 agent #0 started [main process]
   999:20180725:062459.359 agent #1 started [collector]
  1003:20180725:062459.396 agent #2 started [listener #1]
  1004:20180725:062459.406 agent #3 started [listener #2]
  1005:20180725:062459.413 agent #4 started [listener #3]
  1007:20180725:062459.472 agent #5 started [active checks #1]
  1007:20180725:105103.700 active check "log[/var/log/messages,(?i)error]" is not supported: Cannot open file "/var/log/messages": [13] Permission denied

Answer: It's called SELinux.
Unfortunately the SELinux policy for the Zabbix agent is not well developed (yet) and almost anything you might want to monitor is going to be denied. I personally set the Zabbix agent type to permissive to work around this. This lets the Zabbix agent essentially bypass SELinux while it still applies to everything else on the system.
semanage permissive -a zabbix_agent_t

Comment: Because the name of the SELinux type is `zabbix_agent_t`.
Comment: It worked flawlessly Micheal. Just one question, why the "_t" at the end of the command?
Comment: @MatiasBarrios To be overly clear, the `_t` suffix in SELinux means type. You'll find that there are three suffixes like this: `_u` for User, `_r` for Role and `_t` for type.
Answer: If you prefer not to disable SELinux in any way:
You could check if it's SELinux by running audit2allow -a and check if there is any output which includes Zabbix. Also you could simply set permissive mode temporarily to verify the blockage:

sudo setenforce 0
Check if zabbix agent can do its thing
sudo setenforce 1

If it really is SELinux denying the agent, try the following:
Create a policy to allow whatever is denying Zabbix (as root or sudo):
grep zabbix /var/log/audit/audit.log | audit2allow -M myzabbix

This will pipe any Zabbix denials into audit2allow which creates a policy file and compiled binary in the directory that you are in. I usually do this in /root/selinux for cleanliness.
Then run semodule -i myzabbix.pp
This loads the policy into SELinux and it is permanent so no need to worry about reboots reversing policy.


Is there a convention for Win32 message parameters use?

Question: I read that each message has its own way of using lparam and wparam. I couldn't find any convention about when we pass pointers, who is responsible for memory handling. Should the caller keep track or the message handler should take care of it? I sense that in messaging model it would be hard for caller to manage the memory. Because it won't know when the resource is no longer needed for the message handler. On the other hand that is known as a bad practice in C++ programming. Would you please help me on this?
Comment: If you need pointers, then lParam is usually the one because it used to be of "long" type. You can use WM_GETTEXT or WM_GETMINMAXINFO  as example when callee must write into lParam (provided by caller) and WM_NOTIFY when callee reads from caller (and does not deallocate). In general, details are added for specifics, for ex: WM_COPYDATA. This is for SendMessage calls. For PostMessage calls this is another story. Some APIS handle all that in an opaque way with wrapper methods: https://docs.microsoft.com/en-us/windows/win32/wintouch/sendmessage--postmessage--and-related-functions and warn you.
Comment: It depends. If the message is delivered asynchronously, then the caller has to take on responsibility. Otherwise, there is a choice to be made. No one size fits all solution. You need to define the usage before you can decide.
Comment: If you are trying to solve a specific problem, do let us know, what problem that is. If you are just curious, then [What do the letters W and L stand for in WPARAM and LPARAM?](https://devblogs.microsoft.com/oldnewthing/20031125-00/?p=41713) might be for you.
Comment: I am thinking about the design of my application. I want to choose the correct way to implement messaging.
Comment: It's *your* application. You can make the rules. If you want to transfer ownership/responsibility of resources, then there's nothing stopping you.
Answer: I conclude it is completely by code designer on how message parameters are managed. I also note that if a message is posted aysnc either the resource should be freed by message handler or somehow sender must be signaled by message handler that the resource passed in lparam or wparam is no longer needed.


Tuning up to get All Fourths Tuning

Question: I use a set of 10 gauge steel strings on my electric guitar and for the past few days I have been thinking of testing out the All Fourths Tuning. I was wondering if this poses a risk of breaking the strings either while tuning or heavy picking (which I tend to do).
I started learning the guitar almost a year ago, and I genuinely see no benefit from the standard tuning. In fact the semitone down tuning on string 2 always tripped me up in the beginning.
P.S. I'm not sure if I should post this in a physics forum. But the question felt like it belonged here.
Comment: The way I look at it is that by tuning the first and second string to C and F respectively gives you a bit more variety as to choices in open chords and notes, it makes scales seem a bit more simpler, finding notes on the guitar becomes simpler. Basically I am advocating uniformity. But maybe this is because I am a beginner, I may change my mind later.
Answer: Tightening up the top two by a semitone won't make much difference. You could, of course, go the opposite way, and tune the bottom four down a semitone - making the strings Eb Ab Db Gb B(Cb) E.
Comment: Can't really down tune the bass strings. I have a really shoddy guitar with the most glorious fret buzz that competes with the music for dominance. I'm afraid tuning it down would just exacerbate the problem. But I think I'm going to go ahead and tune 1 and 2 up, let's see if there is any noticeable ease in playing.
Comment: It would work for a lot of guitars - it does work as a lot of players already tune down at least the bottom string, if not all.

Tuning up to get All Fourths Tuning


gcc compiling invalid C code

Question: Some of my C programs are not working as expected. For example, pass by reference is not possible in C, but when I write a C program which uses that and compile it with gcc it works fine.
Is gcc a C++ compiler? How do I make it behave like a C compiler?
Comment: You can't say something like that (re PBR) without posting some code!
Comment: I agree with Joe: you need to post your code--and file names.  If your source file has and extension which is one of .cpp, .cc, .C or .c++ (and some others) it will compile it as C++.  If it is compiling a .c file with gcc (or g++), call by reference will *not* compile.  Note, too, that if you try to link your c++ objects with gcc, it will probably not link successfully, because gcc will not link the C++ library by default.
Comment: gcc looks at the file extension. if the file is *.c it is compiled as C. If the file is *.cpp it is compiled as C++.
Comment: @Roger I meant 'pass by reference'
Answer: gcc, g++, and the other frontends use filenames to determine language.  For example, the only major difference between gcc and g++ is one that bites new C++ programmers: different link settings (for the C++ stdlib).
Use the -x option (and maybe -std) to specify explicitly, if your files get mis-detected.  Or follow the common naming conventions that gcc uses for filenames.  For C this means *.c.
Double-check that you didn't use a capital/uppercase *.C to name your file; that's detected as C++.
Answer: If I compile this:
int f( int & r ) {
    return r + 1;
}

int main() {
    int x = 3;
    return f( x );
}

with:
 gcc e.c

I get:
 e.c:1: error: expected ';', ',' or ')' before '&' token

Have you perhaps given the file you are compiling a .cpp extension? If you have, the gcc driver will compile it as a C++ file.
Answer: The program gcc is a driver which can dispatch to a C, a C++, an Ada, a Fortran, a Java and probably other compilers depending on what is installed and the extension of the file.
If those are wisely chosen, you shouldn't have to do anything to get C files compiled as C and C++ files compiled as C++.  To force compiling as C, use -x c as an option before the compiled file.
My guess is that you have named your file with an uppercase C instead of an lowercase one, and the uppercase C is considered as C++.
Answer: Try defining the command-line option -pedantic, and specify the C standard you wish to comply to, e.g. --std=c99 for C99, --std=c89 for C89; this should make it reject anything not part of the specified standard.
Edit: Note that -ansi can stand for either C89 or C++98, and might not work to force the compiler into "C-mode".
Comment: Actually, if it thinks the file is a C++ source, it ignores flags like --std=c89. It does warn you it is doing so, however.
Comment: True, if the file already has the extension .cpp then specifying a C standard causes a warning. Then again, trying to do that is a sign that something else is broken. =)
Comment: So it appears this solution is only valid for this specific problem with -Werror (to stop make, etc.). Whether that option should always be used or not is a different question.  (Hint: yes :P)
Answer: gcc is the driver. It will invoke the actual different front-end according to the file extension or forcibly -x.
But for g++, it'll force to treat source files as C++ by default, even your file is (*.c) (lowercase).
Why not have a simple trial to convience yourself:
echo "int main() { } " > test.c

gcc -v -c test.c

[Please not the /usr/libexec/gcc/i386-redhat-linux/4.1.2/cc1plus line, which is the actual front-end compiler.]
========================
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --enable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-126.96.36.199/jre --with-cpu=generic --host=i386-redhat-linux
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
 /usr/libexec/gcc/i386-redhat-linux/4.1.2/cc1 -quiet -v test.c -quiet -dumpbase test.c -mtune=generic -auxbase test -version -o /tmp/ccUiF4Qr.s
ignoring nonexistent directory "/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../i386-redhat-linux/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i386-redhat-linux/4.1.2/include
 /usr/include
End of search list.
GNU C version 4.1.2 20080704 (Red Hat 4.1.2-46) (i386-redhat-linux)
    compiled by GNU C version 4.1.2 20080704 (Red Hat 4.1.2-46).
GGC heuristics: --param ggc-min-expand=59 --param ggc-min-heapsize=55455
Compiler executable checksum: 435964263b657ac05d988fae7b6714b1
 as -V -Qy -o test.o /tmp/ccUiF4Qr.s
GNU assembler version 18.104.22.168.6-12.el5 (i386-redhat-linux) using BFD version 220.127.116.11.6-12.el5 20061020

=============================
mv test.c test.cpp
gcc -v -c test.cpp

=============================
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --enable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-188.8.131.52/jre --with-cpu=generic --host=i386-redhat-linux
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
 /usr/libexec/gcc/i386-redhat-linux/4.1.2/cc1plus -quiet -v -D_GNU_SOURCE test.cpp -quiet -dumpbase test.cpp -mtune=generic -auxbase test -version -o /tmp/ccUgae0u.s
ignoring nonexistent directory "/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../i386-redhat-linux/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2
 /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/i386-redhat-linux
 /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/backward
 /usr/local/include
 /usr/lib/gcc/i386-redhat-linux/4.1.2/include
 /usr/include
End of search list.
GNU C++ version 4.1.2 20080704 (Red Hat 4.1.2-46) (i386-redhat-linux)
    compiled by GNU C version 4.1.2 20080704 (Red Hat 4.1.2-46).
GGC heuristics: --param ggc-min-expand=59 --param ggc-min-heapsize=55455
Compiler executable checksum: 2c84476b74368e297382b43d14e53b01
 as -V -Qy -o test.o /tmp/ccUgae0u.s
GNU assembler version 184.108.40.206.6-12.el5 (i386-redhat-linux) using BFD version 188.8.131.52.6-12.el5 20061020

================================
mv test.cpp test.c
g++ -v -c test.c

You'll get the same result as gcc + test.cpp, which means compiled as C++.
cc is the C front end cc1plus is the C++ front end. That's it.
Answer: g++ should be the front-end for C++ and cc for C, but both point to gcc.
If you want to compile standard compliant C code, use gcc -ansi
Comment: -1: `-ansi` specifies either C90 or C++98, depending on whether it's in C or C++ mode. The `-std` option is far more explicit.

gcc compiling invalid C code


Isolar domínio da camada de apresentação

Question: A boa prática de arquitetura de software diz que a camada de apresentação não
deve conhecer a camada de domínio.
Estou tentando fazer esse isolamento entre essas camadas, porém o
que está dificultando essa separação é o framework de mapeamento
de objetos, o AutoMapper.
Estou com o seguinte cenário:
Camada Presentation > Camada Application > Camada Domain
Na camada Domain tenho a entidade Cliente.
Na camada Presentation tenho o ClienteViewModel.
Para fazer o mapeamento dessas classes, utilizo o
AutoMapper. O problema é que sua configuração é feita
na camada Presentation, e dessa forma acaba que essa camada tenha
que conhecer o domínio.
<code>//Método da classe DomainToViewModelMappingProfile que está na Presentation
protected override void Configure()
{
    // Faz referência ao Cliente do domínio.
    Mapper.CreateMap<Cliente, ClienteViewModel>();
}

// Métodos da classe ClienteMapper
public static ClienteViewModel MapearClienteParaClienteViewModel(Cliente cliente)
{
    return Mapper.Map<Cliente, ClienteViewModel>(cliente);
}

public static Cliente MapearClienteViewModelParaCliente(ClienteViewModel clienteView)
{
    return Mapper.Map<ClienteViewModel, Cliente>(clienteView);
}
</code>
Tentei jogar o AutoMapper na camada Application, mas como
ela referencia o domínio não da para referenciar a Presentation,
pois ocorre problema de depedência circular.
Qual seria o melhor caminho para fazer esse isolamento?
Answer: Eu usaria interfaces para injeção de dependência, e mais uma camada de crosscutting para mapear através dos projetos as classes necessárias com suas interfaces.
Nesse projeto no github do Eduardo Pires contem um projeto desenvolvido com boas praticas e Design Patterns entre outros padrões de projeto. Inclusive ele usa o automapper...

Equinox
O objetivo deste projeto é implementar as tecnologias usadas mais
  comuns e compartilhar com a comunidade técnica a melhor maneira de
  desenvolver ótimos aplicativos com o .NET.
Comment: Então cara esse projeto se mantem em Dot.Net Core, que possui o SDK no visual studio 2017, então se tentar carregar com visual studio 2015 para baixo eles não possuem o compatibilidade. uma opção e carregar com o visual code. [Visual Code](https://code.visualstudio.com/download)
Comment: Obrigado Nicolas! Mas ao fazer o download alguns projetos não carregam.
Comment: Os projetos Equinox.UI.Site e o Equinox.WebApi apresentam a falha de carregamento: o SDK 'Microsoft.NET.Sdk.Web' especificado não pôde ser encontrado.


Simple blog post function

Question: How would I create a simple blog posting function in PHP? I have a mySQL database with the following...
Table bloggers:
id, name
Table posts:
blogger id, post, timestamp
In plain English I want to display all posts with the blogger's name (by matching the id with blogger id) and a timestamp, and the posts ordered by the timestamp to have the most recent ones first.
My current endeavours of selecting each one nested within the other isn't working and I think I need to rethink the whole approach.
Comment: you do seem to be missing a post_id, and possibly a parent_post_id for the indenting of replys
Comment: Seems like a trivial task, what have you done until now, may be you are thinking too complicated
Comment: The task is not really a blog post, I've simplified it because what I'm working on uses the same principle. Think of it as a sort of simple feed.
Comment: Sorry, I do have a post id too.
Answer: I'd suggest you read up on the basics of SQL as this seems pretty straightforward:
SELECT
   b.name, p.post, p.timestamp
FROM
   posts p
INNER JOIN
   bloggers b
ON
   p.blogger_id = b.id
WHERE
   b.blogger_id = :id
ORDER BY
   p.timestamp DESC

Note that the :id part above is for use in a prepared statement, described below.
As for the PHP function, you should use PDO for this.
Answer: try sql:
select * from bloggers A, posts B WHERE A.bloggerid = B.bloggerid

Answer: I may not quite understand how you're organizing things but...
Assuming you can get the author's id by selecting the bloggers table and getting the id you want you could do something like this:
$result = mysql_query("SELECT * FROM posts WHERE blogger_id='" . $author_id . "' ORDER BY timestamp DESC") or die(mysql_error());

while($row = mysql_fetch_array( $result )) {
 echo '

' . $row['timestamp'] . '

'. $row['post'] .'

';
}

Simple blog post function


WCF 4.0: IAuthorizationPolicy Evaluate() called after ServiceAuthorizationManager CheckAccessCore(): why?

Question: I'm working on a WCF service that is hosted through a Windows Service. I have added my Custom Authorization Manager and Authorization Policy and I've seen that the Evaluate() method of Authorization Policy is actually called AFTER the CheckAccessCore() of the Authorization Manager: shouldn't be the opposite?
I've been searching on google and found some tips, but did not work for me
(e.g.: link )
Here is a snip of the app.config:
<code> <userNameAuthentication userNamePasswordValidationMode="Custom"

      customUserNamePasswordValidatorType="Reply.Platform.IoTAccessControlLibrary.IoTPwdValidator, Reply.Platform.IoTAccessControlLibrary" />

      </serviceCredentials>

      <serviceAuthorization serviceAuthorizationManagerType="Reply.Platform.IoTAccessControlLibrary.IoTServiceAuthorizationManager, Reply.Platform.IoTAccessControlLibrary">

        <authorizationPolicies>

          <add policyType="Reply.Platform.IoTAccessControlLibrary.IoTAuthorizationPolicy, Reply.Platform.IoTAccessControlLibrary" />

        </authorizationPolicies>

      </serviceAuthorization>
</code>
Can someone help me?
Regards,
Gianpaolo
Answer: It is working exactly as intended. It comes down to this simple equation - If access should not be granted then there should be no need to check to see if the access being should be authorized. In the case of the example you are providing here, you would first validate the correct combination of a username/password pair and then you would check to see if they had access to the system. After you check to see if they have access to the system, you then evaluate whether or not they are authorized per the policies defined.
Consider this basic example:
1) Does the username and password match with a known user? Yes. (Service Credentials)
2) Is that known user enabled on the system? Yes. (Service Authorization)
3) Does that known user have the role of 'X'? Yes. (IAuthorizationPolicy)
Hence the workflow defined by WCF.


How to expand relative paths in shell script

Question: I am writing a script to set environment variables on linux 2.6 using bash.
So the script contains commands like:
export SRC_DIR=..
export LIBPATH=${SRC_DIR}/lib

the problem is that when i try to do echo $LIBPATH, it shows "../lib" as opposed to expanding the SRC_DIR to full path. I would really like the script to print something like /home/x/lib as opposed to ../lib.
UPDATE
The script should evaluate SRC_DIR to be one directory upwards from the script's location and not the current directory from where the script is invoked
Answer: Change Directory in Subshell
There's a little trick you can use to get the absolute path from a relative path without changing the present working directory. The trick is to move to the relative path in a subshell, and then expand the working directory. For example:
export SRC_DIR=$(cd ..; pwd)

Relative Paths from Script Instead of Invocation Directory
To change to a relative path from a script's location, rather than the current working directory, you can use a parameter expansion or the dirname utility. I prefer dirname, since it's a little more explicit. Here are both examples.
# Using /usr/bin/dirname.
export SRC_DIR=$(cd "$(dirname "$0")/.."; pwd)

# Using the "remove matching suffix pattern" parameter expansion.
export SRC_DIR=$(cd "${0%/*}/.."; pwd)

Comment: Sorry i spoke early. This has same issue that the script needs to be executed from the folder where it is located. But if i run the above script from /tmp, the SRC_DIR would evaluate to root folder such as /
Comment: @Jimm PEBKAC. If you place your script in /tmp and then provide a relative path of ".." from the script's dirname, then of course you get /. You probably want "../src" or some other similar construction.
Answer: The readlink command is capable of not only resolving symlinks, but also canonicalizing relative paths. Be careful, since you may not want the behaviour of resolving symlinks in all your scripts. If you don't want to resolve symlinks, pwd would be the best; note the use of a subshell, so the cd command does not affect the working directory in the main shell.
# The path you want to get information on... (for readability)
your_path=..

# Using /bin/readlink (resolves symlinks)
export SRC_DIR=$(readlink --canonicalize $your_path)

# Using /usr/bin/dirname (keeps symlinks)
export SRC_DIR=$(cd $your_path ; pwd)

Answer: I usually use
SCRIPT_DIR=$(readlink -f ${0%/*})

It should return the full path to the script, and even resolves all the links along the way.
Comment: This has same issue where $0 evaluates to word bash. My first line in script is #!/usr/bin/env bash. When i echo $SCRIPT_DIR, it does path expansion, but it also adds the word bash. I am executing the file directly by ./env.sh
Answer: Digging up this old thread to add what i've found to work nicely:
export SRC_DIR = `realpath ..`
see more information here:
http://man7.org/linux/man-pages/man3/realpath.3.html
Comment: For most systems it's a better solution
Comment: However, when `realpath` is available, it's the absoutely simplest and best possible solution.
Comment: I'm downvoting this because it gets posted over-and-over again while not being a solution, because `realpath` is not part of the POSIX standard and therefore can't be relied upon on every system.
Comment: @Bachsau Many systems are not POSIX compliant either.
Answer: When I do this I use echo like so:
export SRC_DIR=`echo $HOME/bin/`

Answer: With zsh, it's quite simple using the :P modifier:
export SRC_DIR=..
export LIBPATH=${SRC_DIR:P}/lib

https://zsh.sourceforge.io/Doc/Release/Expansion.html#Modifiers
Answer: Do this instead:
export SRC_DIR=`pwd`;

Update:
Since you want path relative to the script's location on the filesystem, use this instead:
export SRC_DIR=`dirname $0`

Update2:
Your script must be invoked directly and not as bash /path/to/script.sh or source foo.sh. Add a shebang line, add execute permissions and invoke the script directly.
Comment: The problem in pwd is that it would take the current directory from where you execute scripts. so i could be in /tmp and execute the above script in /home/x/scripts, it would take pwd as /tmp. But i would really like ../ to resolve to relative to script file location. Hence correct answer for ../ should be /home/x/
Comment: Oh if you wanted a path relative to script file location, you should specify that in the question! See updated answer.
Comment: dirname $0 gives error, because $0 evaluates to the word -bash
Comment: Are you invoking the script as `bash /path/to/script.sh`? If so, add `#!/usr/bin/env bash` as the first line of your script and invoke the script directly as `/path/to/script.sh`
Comment: i am executing as source env.sh, where env.sh contains the variables
Comment: This has different issue, where i need to supply the full path name to the script. Suppose i am in the same directory as the script and execute this command. The echo $LIBPATH would now show as ./lib. is there anyway to force . to expand to full file path?
Comment: YOu get the error with `dirname $0` because you're invoking it as `source foo.sh`. You may want to try what I mentioned in Update2.
Answer: For keeping error code:
function getPwd() {
    $(cd $1; [[ $? -ne 0 ]] && exit 1 || echo echo $PWD;)
    return $?
}

Comment: Please expand your answer: why does it work? What is the notation doing? Is there any documentation to this?
Answer: None of the solutions here worked for me (for zsh). I came up with this:
#!/usr/bin/env bash

your_path="/Users/usr/Documents/Folder/Another/../../../Documents/SomeFile.dmg"

resolved=$(readlink -f "$your_path")
echo "$resolved"

Gives me:
/Users/usr/Documents/SomeFile.dmg

Note that the path in $your_path must exist.


Form element title is not displaying translation

Question: I have got my own module providing a form and there is one element called "Estimated time" defined like this:
$form['informacie_o_incidente']['field_incident_doba'] = array(
  '#title' => t('Estimated time'),
  '#markup' => '
Estimated time:
'.$doba.'

',
);

I have translated the text "Estimated field" via translation interface, cleared cache several times (both GUI and with drush cc all command). However, when I run this drush command:
drush ev "print t('Estimated time');"

I am getting correctly translated string. So why not on the form?
Answer: I think you need  add t() in #markup and translate the string 'Estimated time:'
$form['informacie_o_incidente']['field_incident_doba'] = array(
  '#title' => t('Estimated time'),
  '#markup' => '
'.t('Estimated time:').'
'.$doba.'

',
);


Modify local list in parallel stream java

Question: I have a method like below:
  public void method ()
  {
        List<String> list1 = someOperation();
        List<List2Class> list2;
        long failedCount = 0;
        for (String element : list1) {
            try {
                list2 = someclass.method1(element);
                list2 = someclass.method2(element);
                someclass.saveToDB(list2);

            } catch (Exception e) {
                failedCount++;

            }
        }
       //some checks on failedCount
    }

I want to convert the for loop into parallel stream, can someone tell me what should be the code changes in the above method for the same?
PS - method1 and method2 are returning modified version of list2.
Comment: It looks like `list2` is simply `someclass.method2(/* last element of list1 */)` there. Do you really need to process all the others?
Comment: @AndyTurner that would be true if there was no `try ... catch`. With `try catch` it could be anything. To be more specific last that didn't fail. I doubt that it is possible to use Streams here in any meaningful way.
Comment: The result of `someclass.method1(element)` is never used. It's overwritten with the result of `someclass.method2(element)` right in the next line.
Comment: I have updated the question to be more specific, each method is returning a modified version of list2 which is getting saved to db for each element in the for loop
Answer: The logic here is basically "the result of the last successful operation".
Assuming you don't need the failedCount (you don't show it being used), you can do that like this: map successful operations to a present Optional, failed operations to an absent Optional; and just take the last present optional:
Optional<List<List2Class>> opt = list1.stream()
    .flatMap(element -> Stream.of(runOperation(someclass::method1, element), runOperation(someclass::method2, element))
    .reduce((a, b) -> !b.isPresent() ? a : b);

where runOperation is something like:
Optional<List<List2Class>> runOperation(Function<String, List<List2Class>> operation, String parameter) {
  try {
    return Optional.of(operation.apply(parameter));
  } catch (Exception e) {
    return Optional.absent();
  }
}

You then need to decide what value list2 should have if no operations succeed.
If you actually do need the failedCount, you can break this up a bit:
Stream<Optional<List<List2Class>>> intermediate =
    list1.stream()
        .flatMap(element -> Stream.of(runOperation(someclass::method1, element), runOperation(someclass::method2, element));

Map<Boolean, List<Optional<List<List2Class>>>> partitioned =
    intermediate.collect(Collectors.partitioningBy(Optional::isPresent));

Now partitioned.get(true) has all the successful results, while partitioned.get(false) has all the failed results. So:
Optional<List<List2Class>> opt = partitioned.get(true).stream().reduce((a, b) -> !b.isPresent() ? a : b);
long failedCount = partitioned.get(false).size();


What is the meaning of volume of dynamical system

Question: https://en.wikipedia.org/wiki/Dynamical_system  explains that the volume of state space or phase space is invariant. The lecture note titled "11 Strange attractors and Lyapunov dim." taken from the book of Strogatz shows in eq(2) a coordinate transformation of the volume. I want to understand if the proof shown in the note means that the volume of systems with strange attractor is invariant under some kind of transformation such as the coordinate transformation. By coordinate transformation, we can generate the phase space reconstruction and using that we can get a strange attractor. Upon proper choice of parameter setting for the chaotic dynamical system  we can see the  strange. But I am unable to understand the proof.
Question: Can somebody please show how to prove that the volume for systems having strange attractors is invariant to transformation and what this means.
Does the volume of strange attractors shrink or expand?

UPDATE: 18 Aug
Based on the discussion under the comments, this is what I could write from whatever I could understand. Shall appreciate help in finishing the proof writing in an elegant way.
Proof: volume of strange attractor shown by systems in chaotic dynamics is invariant under some transformation and is a measure or a metric.
My idea is that, let $n_a$ be the attractor dimension and $d$ be the embedding dimension and the attractor has a volume $v$ with an attractor dimension $n_a$. If scalar valued time series are available, then we can reconstruct the attractor in $d$ dimensional phase space by Takens' delay embedding method,  $d \ge 2n+1$ where $n$ is the dimension of the observed system. We don't hae knowledge of the actual value of $n_a$. Since, for dissipative systems volume $v \le 0$, if and only if $n \le n_a$, and is equal to zero since its dimension is less than $n_a$. Therefore any dissipative system preserves the volume of the attractor, which is zero. As for the change of coordinates, since the attractor is a measure zero set, the image of the attractor under any smooth map will also be measure zero.
Now how do I prove that the attractor is a measure set zero and is a metric like the Lebesgue measure? Can somebody please help in formally writing this proof? Thank you.
Comment: "Volume" appears only in the "Ergodic systems" section of the cited page.  That section also has "For systems where the volume is preserved by the flow", which indicates state space volume need not be invariant.  (Most dissipative systems violate volume invariance.)  That section references "[Ergodic theory](https://en.wikipedia.org/wiki/Ergodic_theory)", which has the early sentence "Let $T : X \rightarrow$ X be a measure-preserving transformation on [the state space]", which immediately forces volume invariance.  Do you intend to restrict to ergodic dynamics or discuss general dynamics?
Comment: I am interested in the volume of systems which give rise to strange attractors like chaotic systems. In this case, the volume will shrink or change. So is this kind of volume invariant?
Answer: A couple things:

Notice the note under equation 2:

Dissipative systems have attractors, while volume conserving systems cannot have attractors nor repellers.

This is true in the sense where "volume" means the Lebesgue measure, i.e., the normal definition of volume on $\mathbb{R}^n$. Attractors are necessarily of a lower dimension than the phase space itself, so its volume (in the Lebesgue sense) must be 0; e.g., the volume of a surface in $\mathbb{R}^3$ is 0 since the surface is 2-dimensional. Maybe this preservation of volume is trivial because the attractor necessarily has Lebesgue volume zero.
So this seems to answer your question on the face of it. However, dynamics on strange attractors are typically ergodic, which is the section you are reading in the first Wikipedia article. Ergodic dynamics typically have something called an invariant measure, which means that there is some notion of volume (the measure) which is preserved by the dynamics (invariant). Therefore, if one can parameterize the attractor, i.e, find a change of coordinates from $\mathbb{R}^n$ to the attractor, then "volume" in the sense of the invariant measure of the attractor and dynamics will indeed be preserved.
Comment: Thank you for answering. Can you please clarify 3 things? (1) based on my understanding, if $d$ is the embedding dimension (using Takens' Embedding) then $d>=2n+1$. So the attractor is constructed in $n$ space but can be constructed in the embedded phase space$d$ if the embedding dimension is properly selected. Is my understanding right? (2) does the strange attractor volume remain constant? (3) Does the lecture give the proof that the volume of strange attractor is invariant for a coordinate change? Could you please provide it, if it is not there in the note. This will be immensely helpful.
Comment: 1. Yes 2. Yes (either zero Lebesgue volume remains zero or the invariant measure on the attractor is preserved, depending on what volume you care about) 3. No, but since the Lebesgue volume of an attractor is zero, it will remain zero under any change of coordinates from the change of variables formula form calc 3
Comment: Thank you once again. If it is dissipative then shouldn't the strange attractor's volume change, based on the fact that it will loose energy?  some confusion here. Could you please provide the proof that the volume is invariant under coordinate change for the strange attractor? I will be grateful for that or a link to the proof.
Comment: The system must be dissipative for an attractor to exist, so the volume of any set must be nonincreasing under the flow map. However, recall that volume $\geq 0$ and, the critical part, *the volume of an attractor is equal to zero* since its dimension is less than $n$. Therefore any dissipative system preserves the volume of the attractor, which is zero. As for the change of coordinates, since the attractor is a measure zero set, the image of the attractor under any smooth map will also be measure zero.
Comment: I have updated the question by trying to convert your answer in the comment to a proof. But it is still vague and incomplete. Can you please help in finishing the proof-writing?
Answer: When they say volume, they really mean `measure.' A measure on a space $X$ is a function $\mu$ that assigns lengths (or areas, or volumes, or probabilities--the specific space $X$ or the context usually dictates how you think of what the measure is, well, measuring) to "nice" subjects of $X,$ where "nice" means beforehand someone selected some subsets of $X$ that we can measure. These are called the measureable sets.
A map $T : X\rightarrow X$ is said to be $\mu$-invariant if (a) whenever $S$ is measureable, so is $T^{-1}(S)$, and (b) $\mu(T^{-1}S) = \mu(S)$ whenever $S$ is measureable.
As to how to check it, this depends a lot on the particulars. One incredibly common, helpful trick is that you don't need to check that conditions (a) or (b) holds for every measureable subset--if you check (a) and (b) on a family of sets that `generates' the collection of measureable sets, then you can conclude it holds everywhere. For instance, if your space was $X = [0, 1]$ with the usual "Lebesgue measure" assigning a subset of $X$ it's length, it'd suffice to check that $T$ preserves measures of intervals.
Comment: please correct me where wrong. I want to understand that the strange attractors of chaotic systems have a volume in phase space. Is that volume invariant to some kind of transformation?


Dependency inversion in EJB based application

Question: I want to make some of parts my JEE application independent from others ones using dependency inversion and dependency injection. Below is some code of main core part, that uses MyService, but is independent from other module that should provide implementation of MyService.
public interface MyService {
    public void send(MyObject myObject);
}

.
@Stateless
@LocalBean
public class MyServiceWrapper implements MyService {

    @Inject
    private MyService myService;

    @Override
    public void send(MyObject myObject) {
        myService.send(myObject);
    }
}

To clarify:
Module A contains classes:

MyObject,
MyService,
MyServiceWrapper,

Module B contains implementation of MyService.
I want MyServiceWrapper to have injected implementation of MyService provided by module B, so module A can call implementation of MyService by using MyServiceWrapper, but in te same time module A is independent from module B.
The problem with above code, is that container do not know which implementation of MyService should be injected.
How it should be written so MyServiceWrapper, so it won't be injected to itself, but proper implementation (provided in other module) will be injected instead?
Comment: May i ask why are you injecting an object to it self ? Are there any other implementations of MyService besides MyServiceWrapper ?
Comment: I have edited question to clarify what I meant.
Comment: Owkay, i think i might know. I have edited my answer below.
Answer: The correct way would be to use what is known as a Qualifier , one example from CDI would be the annotation @Named, this would get rid of ambiguity for the container.
public interface MyService {
void send(MyObject myObject);
}

and the implementation of MyService :
@Named("fromModuleA")
@ApplicationScoped
public class MyServiceWrapper implements MyService {

    @Inject
    @Named("fromModuleB")
    private MyService someOtherBean;

    @Override
    public void send(MyObject myObject) {
        this.someOtherBean.send(myObject);
    }
}

@Named("fromModuleB")
@ApplicationScoped
public class SomeOtherBeanFromModuleB implements MyService{
  @Override
    public void send(MyObject myObject) {
        // implementation
    }
}

The @Inject comes from a Java specification called CDI (Context and Dependency Injection), with this annotation it doesn't matter whether you use it on EJBs or CDI beans, but @EJB will only work with the EJB Container. Also note you don't really need the Interface MyService at least not anymore but it's a good practice to code to the interface.


How do I "Create an  element and give it an ID, but don't put any text inside In JavaScript, select your  element and give it some text'

Question: create an
 element and give it an ID, but don't put any text inside
In JavaScript, select your
 element and give it some text
Answer: To modify an existing element:

let h1Node = document.querySelector('#myId');
h1Node.textContent = 'This is the text content!';

Or, to create a new node and append it to the document:

let h1Node = document.createElement('h1');
h1Node.id = 'myId';
h1Node.textContent = 'This is the text content!';
document.body.appendChild(h1Node);

Hope this helps,
Answer: In your HTML file, you're going to create

You want to create a JS file add it as a script to your html file.

and then in your Javascript file, you're going to
let element = document.getElementById('idName');

element.innerHTML += 'text goes here';

Answer:

Javascript:
function addText (text){
  document.getElementById('example').innerHTML = "hi";
}

call function wherever you want
Comment: When you answer a question, try to explain your question a little bit, even if right. In your case, there are additional answers so expose the Pros and Cons of your P.O.V.


Issue with php mysql login $_POST['username'] = $result['username']

Question: I'm kinda' beginner and I've coded my own PHP login from Zero, but I still got some errors, here's the code:
        <?php
    include 'connection.php';
    $query = " SELECT * FROM admin";
    $result = mysql_query($query) or die(mysql_error());

    ?>
    <form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
        Username : <input type="text" name="usernameInput" value="" />
        Password : <input type="password" name="passwordInput" value="" />
                    <input type="submit" value="Login" />
    </form>

    <?php
    $username = $_POST['usernameInput'];
    $password = $_POST['passwordInput'];
    if ($username = $result['username']) {
        if ($password = $result['password']){
            header('Location: admin.php');
        } else {
            echo "PASSWORD IS INCORRECT";
        }
    } else {
        echo "USERNAME IS INCORRECT";
    }
    ?>

So if you can fix this or got an easier way from PHP login from please tell me. :)
Comment: Several comments:if ($username = $result['username']) { should be if ($username == $result['username']) { Same for if ($password = $result['password']){. So use == in stead of = if you want to know something is equal. Second: don't use mysql. Use mysqli or prepared statements.
Comment: you need mysql_fetch_* functions!
Comment: what errors you got ?
Answer: A few things...

Don't use mysql functions
You need to use == to compare strings, not =
You need to actually fetch the results of your query
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result); /* add this */

?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
    Username : <input type="text" name="usernameInput" value="" />
    Password : <input type="password" name="passwordInput" value="" />
                <input type="submit" value="Login" />
</form>

<?php
if(isset($_POST['usernameInput']) && isset($_POST['passwordInput'])){
    $username = $_POST['usernameInput'];
    $password = $_POST['passwordInput'];
}
else{
   echo 'some error ...';
}

if($username == $row ['username'] && $password == $row ['password']){
    header('Location: admin.php');
}
else{
    echo ' username or password is wrong';
}

?>

Comment: I can't see any potential SQL injection attack despide the `mysql_` functions being used;  only a static query is being made.
Comment: No escaping is needed for comparison
Comment: only when interpolated into a query
Comment: Fair enough, the mysql functions still should not be used -but he's right, if you're not inserting then you're not at risk. I assume though he uses these methods everywhere, so just a heads up.
Answer: I have to point out that you are sending the same form over and over without first checking the post. And when you send the form, you will not be able to send the header to redirect, because html is started and headers are sent already.
Mysql functions are deprecated, please use mysqli interface.
Among other several bugs like assignment = instead of is equal ==
Try it this way:
If no post exists send the form else check and if ok redirect or not ok. resend the form
<?php
if($_POST){
    include 'connection.php';
    $query = " SELECT * FROM admin";
    $r = mysql_query($query) or die(mysql_error());
    // get an associated array from query result resource.
    $result = mysql_fetch_assoc($r);
    $username = $_POST['usernameInput'];
    $password = $_POST['passwordInput'];
    if (  ($username == $result['username'])
       && ($password == $result['password'])){
        header('Location: admin.php');
        exit(0);
    } else {
        echo "PASSWORD IS INCORRECT";
    }
}
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
    Username : <input type="text" name="usernameInput" value="" />
    Password : <input type="password" name="passwordInput" value="" />
                <input type="submit" value="Login" />
</form>

<?php

?>

Comment: I believe your curly brackets are unmatched


Manipular um iframe através de outro iframe

Question: Olá, eu estou com uma dúvida e gostaria de pedir a ajuda de vocês. Bom, eu vou tentar explicar mais ou menos o problema (os nomes que eu vou citar é só para exemplo).
Imagina que eu tenho um arquivo chamado "principal.php", daí dentro deste arquivo tem dois Iframes:
O primeiro iframe contém o arquivo "iframe1.php"
O segundo iframe contém o arquivo "iframe2.php".
Agora vamos imaginar que eu estou com o primeiro iframe aberto em formato de modal(ou fancyBox), e eu quero que através deste primeiro iframe, eu consiga recarregar o outro iframe que também está referenciado no arquivo "principal.php".
Eu tinha tentado dessa forma, mas infelizmente não funcionou:

window.parent.$('#iframe-sistema').location.reload(true);

Só para esclarecer. O "iframe1.php" seria um iframe de listagem de dados que vem do banco de dados, que ao clicar em excluir, ele vai abrir o "iframe2.php" em formato de modal (ou fancyBox,popup,etc) que vai perguntar se eu desejo realmente excluir aquele registro. Após confirmar a exclusão, este mesmo iframe (o "iframe2.php") vai exibir uma mensagem se ocorreu tudo certo e depois que apertar o botão "ok", ele vai se auto fechar e recarregar o "iframe1.php" para mostrar os registros que restaram após a exclusão de um registro.
Eu sei que para alguns isso pode parecer um uso excessivo de iframe, mas a questão é que isso é um sistema que vai ser bem modular, onde o uso de código tem que ser reaproveitável para que não haja repetição de código e consequentemente acabar gerando um sistema pesado e de difícil manutenção. Se alguém também souber uma solução alternativa para o uso de iframes, eu agradeço. =D Obs: (Eu utilizo a função load() do Jquery em algumas partes deste sistema, mas não sei se nessa situação pode dar certo).
Comment: Os dois iFrames estão no mesmo domínio? porque não fazes isso sem iFrame?
Comment: Sim. Inclusive as referências dos dois iframes estão no mesmo arquivo. Eu não gosto muito de usar iframes, mas neste caso eu ainda não encontrei uma alternativa o uso de iframes.
Comment: Se descreveres o que queres fazer nós percebemos melhor o problema e pode ser que aprendas uma maneira melhor de fazer isso...
Comment: Ok. Vou tentar melhorar a descrição do problema.
Comment: Lucas: esquece a ideia de iFrame! Faz isso com o `.load()`. Uma div que exibe o que queres com conteúdo dinamico e o dialog para interagir (pedir confirmações) ao usuário. Se colocares mais código que tens na página posso dar uma sugestão durante o fds. Se ninguem ajudar antes.
Comment: Obrigado pela ajuda, eu vou tentar da forma como você disse. Qualquer coisa eu volto aqui para falar o resultado.
Comment: @LucasCavalcanti, já que você mesmo resolveu seu problema, poderia, talvez remover a solução da pergunta e criar um resposta para sua própria pergunta, explicando a sua solução. Ficaria mais fácil de identificar a solução ao seu problema (eu li a pergunta toda para depois descobrir que estava resolvido, =D), e ainda é possível receber votos em sua resposta.
Comment: Obrigado. Vou fazer isso ;)
Answer: Solução:
Eu tentei seguir a ideia do Sergio de usar o "load()", porém no meu caso isso é meio complicado de utilizar. Eu particularmente prefiro o load, pois o código pode carregar mais rápido, porém eu teria que misturar muitos arquivos JS, CSS no mesmo arquivo, então eu optei por utilizar o iframe mesmo. Dessa forma, eu consegui atualizar um iframe através de outro iframe:

window.parent.document.getElementById(iframe).contentDocument.location.reload(true);


When did the NBA establish the first collective bargaining agreement ? What were the reasons leading up to this?

Question: Always been curious of when the first CBA came about.
Answer: From this FAQ:

Bob Cousy began to organize the NBA players in 1954, although the
  league refused to recognize the union until 1957. A near strike at the
  1964 All-Star game forced the league to adopt a pension plan. The
  first CBA was established in 1970, and new agreements followed in
  1973, 1976 and 1980. The 1976 CBA coincided with the settlement of the
  "Oscar Robertson" suit, which was filed by the players association in
  1970 to block the NBA-ABA merger. The 1976 agreement also provided
  limited free agency through the elimination of "option" clauses that
  bound players to teams in perpetuity.

From another account:

COUSY ORGANIZES THE PLAYERS
Economic conditions continued unchanged
  through 1954, at which point Bob Cousy, the league's top player, began
  to organize the NBPA, which would become the first team sports
  player's union. Cousy began by writing to an established player from
  each of the league's teams (Paul Arizin of Philadelphia, Carl Braun of
  New York, Bob Davies of Rochester, Paul Hoffman of Baltimore, Andy
  Phillip of Fort Wayne, Pollard, Dolph Schayes of Syracuse and Don
  Sunderlage of Milwaukee) in hopes of encouraging solidarity among the
  players. All but Phillip responded positively (of all the owners, Fort
  Wayne's Fred Zollner, who owned a machine works plant, was the
  staunchest union opponent and this prevented the Pistons players from
  participating), and Cousy next went to NBA President Maurice Podoloff
  at the January, 1955 NBA All-Star Game with a list of concerns:
  payment of back salaries to the members of the defunct Baltimore
  Bullets club; establishment of a twenty-game limit on exhibition
  games, after which the players should share in the profits; abolition
  of the $15 "whispering fine" which referees could impose on a player
  during a game; payment of $25 expenses for public appearances other
  than radio, television or certain charitable functions; establishment
  of an impartial board of arbitration to settle player-owner disputes;
  moving expenses for traded players; and payment of player salaries in
  ten installments rather that twelve, to provide more money to players
  cut during the season. Podoloff agreed to the payment of two weeks'
  salary to six players who had played for Baltimore before the
  franchise folded and committed to meeting with the player
  representatives within two weeks over their concerns.

As the excerpts above show, players were unhappy with the financial arrangements that they had with the NBA. The players wanted a better pension, some control over the "whisper" fines that referees could impose, payment of back salaries to certain players, and to settle other working conditions and payments.
Comment: What was the "whispering fine"? It sounds shady :)


Logarithmic integral and natural numbers.

Question: Prove these two relations:
$$\text{li}(k+1)+k-\log (k)-\gamma  = \int_0^k \left(\int_1^2 \frac{(s+1)^{n-1}+s-1}{s} \, dn\right) \, ds,$$
$$n = \lim_{s\to 0} \, \frac{(s+1)^{n-1}+s-1}{s},$$
where $\text{li}(n)$ is the logarithmic integral and $\gamma$ is the Euler-Mascheroni constant.
Comment: For the logarithmic integral I have not tried anything. The natural numbers I know as an interpolation of row sums of certain recursively defined tables.
Comment: This is what I have investigated about the natural numbers limit: http://math.stackexchange.com/questions/873899/successive-ratios-of-a-sequence-is-this-limit-true
Comment: L'Hopital's rule.
Answer: Using the identity
$$\int_0^{1} \left[\frac{1}{\log(s)}+\frac1{1-s}\right] \, ds= \gamma,$$
we have
$$\int_0^k \left(\int_1^2 \frac{(s+1)^{n-1}+s-1}{s} \, dn\right) \, ds \\ = \int_0^k \left(\int_1^2 \frac{(s+1)^{n-1}}{s} \, dn\right) \, ds +\int_0^k \left( 1- \frac1{s}\right) \, ds\\=\int_0^k \frac{1}{\log(s+1)} \, ds  +\int_0^k \left( 1- \frac1{s}\right) \, ds\\=\int_1^{k+1} \frac{1}{\log(s)} \, ds  +k-\int_1^{k} \frac1{s} \, ds-\int_0^{1} \frac1{s} \, ds\\=\int_1^{k+1} \frac{1}{\log(s)} \, ds  +k-\log(k)-\int_0^{1} \frac1{s} \, ds\\=\int_0^{k+1} \frac{1}{\log(s)} \, ds  -\int_0^{1} \left[\frac{1}{\log(s)}+\frac1{1-s}\right] \, ds +k-\log(k)\\= \text{li}(k+1) +k - \log(k) - \gamma$$