How can i store ajax data on a php variable and reuse it?

Question: After sending data using ajax how to store those on PHP variable? I created a dump file where I can see that variable is sent but can't see them when I echo them? how can I see them? I send get data through URL and post data through XMLHttpRequest();  The data return nicely but why it's not storing on PHP variable?

<?php
//dumping code to see received data
$output = "Post Variables\n";
$output .= print_r($_POST, true);

$output .= "\nGet Variables\n";
$output .= print_r($_GET, true);

$output .= "\nBody Content\n";
$output .= print_r(file_get_contents('php://input') ?: "empty", true);

file_put_contents("dump.txt", $output);
// End

if(isset($_GET['a'])) {
    die('This is post data: ' . htmlspecialchars($_GET['a']));

}
if(isset($_POST['b'])) {
    die('This is post data: ' . htmlspecialchars($_POST['b']));

}
    echo "This is get variable: " .$a;
    echo "This is post variable: " .$b;

?>

Ajax Post to PHP and Get Return Data

<button id="btn1" value="saturday"  onclick="clickMe(1)">btn1</button>
<button id="btn2" value="sunday"  onclick="clickMe(2)">btn2</button>

Comment: It looks like you'd need to define the `$a` and `$b` variables, for example: `$a = $_GET['a'];` and `$b = $_POST['b'];`. Also see [PHP Automatically "GET" Variables](https://stackoverflow.com/questions/258397/php-automatically-get-variables). Is that what you mean?
Comment: Let's learn the correct use of ajax here : https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest
Comment: It sounds to me like you are getting the desired values in `$_POST`, is that right?
Answer: The way you use XMLHttpRequest is not right. You should use 2 differents pages : the caller (index.php) and the asynchrone script (tempo.php)
To correct your current caller page : index.php :
• Use an url without any parameter :
 url="tempo.php"

• Send your two parameters together :
 req.send("a="+dayName+"&b="+dayName);

To debug the asynchrone page : tempo.php, just add a fake get_parameter at the top of tempo.php:
 a = a_possible_value_for_a

and then call tempo.php in your browser directly (without your ajax-page)
Answer: Request sent from HTML File.
Sending process one :
  $(document).on("click","#btn1",function(){
   var data = $(this).val();

   /* ajax request sent start */
   $.ajax({
       method:"post",
       url:"phpFileName.php",
       data:{backendPostName:data},
       dataType:"json",
       success:function(response){
           /* Logic implemented here */
       }
   });
  /* ajax request sent end*/
});

Sending process two according to your html structure :
function clickMe(data){
   var data = $(this).val();

  /* ajax request sent start */
   $.ajax({
       method:"post",
       url:"phpFileName.php",
       data:{backendPostName:data},
       dataType:"json",
       success:function(response) {
           /* Logic Implementation here */
       }
   });
  /* ajax request sent end*/

}

When you want to receive this sending data inside php file.
First check this name found or not through php "isset()" function
Example below :
php file :
<?php
   if(isset($_POST['backendPostName'])){
     $customName = $_POST['backendPostName'];

     /*
        store or other logic implement here .
        if you wants to echo html then echo "success"; or your choice
        if you wants to return json data then return json_encode(["result"=>1]);
      */

     /* For HTML Return */

    echo "
Success
1]);
 }

?>


Is it possible to keep 'owner' on file-copy?

Question: When doing a "Operation: Copy file" using a "File System Task", is it possible to preserve the "Owner" attribute on the file?
What happens: The destination file gets the "Owner" as the user running the SSIS-package.
What I want: Keep the original owner as the owner of the copied file.
Answer: As I understand it, a copied file is considered to be a new entity, and therefore its owner will be the user or process that created it.  Interestingly, a moved file will retain all of its attributes.
If moving (rather than copying) is an option, that should work for you.  If not, you'll have to find a way to change the attributes on the newly copied file.  Some copy utilities (such as Robocopy) have switches that allow you to retain some or all of the attributes.  I'm not that familiar with SSIS, but maybe there's a way to call a batch file rather than use the native copy command?
Comment: I have only spent like 5 hrs in SSIS but I think that running a batch file will be no problems, but it introduces external dependencies and increases complexity, therefore I hoped to be able to do it "natively" in SSIS.


O que é assembler?

Question: Sempre leio coisas relacionadas à assembler e fico confuso. No início, eu pensava que isso era uma confusão e que assembler era a mesma coisa que assembly. Mas parece que não é isso.
O que é assembler? E qual a sua relação com assembly?
Comment: [Aqui](http://pt.stackoverflow.com/questions/156521/a-primeira-linguagem-de-programa%c3%a7%c3%a3o) tem algo relacionado.
Answer: Assembler
Assembler, como o próprio nome diz é um montador, e não um compilador, ainda que ele funcione de forma muito semelhante. Ele pega um texto que é um código de programação e transforma em código binário (código de máquina). O que difere de um compilador é justamente que as instruções na linguagem possuem uma relação um para um no código binário. A análise e transformação do código em um montador é muito mais simples que um compilador (o lexer é mais ou menos igual, o parser é mais simples, e a análise semântica em geral não existe).
Assembly
A linguagem de programação de baixo nível é o Assembly (linguagem de montagem), que é assemblada por um assembler (o sufixo er em inglês é igual ao nosso dor e indica um agente de uma ação). Usamos em maiúsculo por ser nome próprio.
Existem dialetos diversos para cada arquitetura física (processador x86, ARM, MIPS, etc.), ou virtual (JVM, CIL, e muitas linguagens dinâmicas possuem seu próprio Assembly). A semântica depende da arquitetura, mas a sintaxe não, e o montador específico pode adotar a que preferir.
Há quem confunda código de máquina e Assembly. O primeiro é binário, o Assembly está em um nível que humanos (normais, embora alguns dirão que esses não são tão normais assim :P) entendem. São mnemônicos que definem as instruções que o processador deve executar.
Assembly é toda imperativa e cada mnemônico é uma instrução muito simples manipulando um valor em registradores, movendo os dados entre os registradores e memória e controlando o fluxo de execução da forma mais simples possível, sem abstrações, sem syntax sugar, sem padrões de projeto prontos.
Quando a pessoa diz que vai programar em assembler ela comete o mesmo erro que a pessoa que diz que vai programar em Visual Studio.
assembly
Mas assembly em minúsculo é aquele arquivo com código binário do CLR (vulgo .NET).
Exemplos
Exemplo de código Assembly x86-64 sintaxe Intel:
; Assembler (x86) version of 99 Bottles of beer
;
; This version is for NASM compiler but doesn't use any
; macros, just all basic instructions for x86 assembler.
; Also only putchar() function is used to print character
; onto screen, and the whole rest is in code.
;
; nasm -fwin32 99.asm
; gcc -o 99.exe 99.obj

        global  _main
        extern  _putchar

        segment .data

_line_1_1        db ' bottles of beer on the wall, ', 0
_line_1_2        db ' bottles of beer.', 13, 10, 0
_line_2_1        db 'Take one down and pass it around, ', 0
_line_2_2        db ' bottles of beer on the wall.', 13, 10, 13, 10, 0
_line_2_2_one    db ' bottle of beer on the wall.', 13, 10, 13, 10, 0
_ending_lines    db '1 bottle of beer on the wall, 1 bottle of beer.', 13, 10
                 db 'Take one down and pass it around, no more bottles of beer on the wall.', 13,
10, 13, 10
                 db 'No more bottles of beer on the wall, no more bottles of beer. ', 13, 10
                 db 'Go to the store and buy some more, 99 bottles of beer on the wall.', 13, 10, 0

        segment .text

; this function converts integer in range 0-99 to string
_integer_to_string:
        mov     eax, dword [esp + 08h]    ; get the vavlue
        mov     ecx, 10                   ;
        sub     edx, edx
        div     ecx                       ; divide it by 10
        mov     ecx, dword [esp + 04h]    ; get the output offset
        test    eax, eax                  ; is greater than 9
        jz      .skip_first_digit         ; skip saving 0 char if no
        add     al, 030h                  ; convert number to ascii char
        mov     byte [ecx], al            ; save
        inc     ecx                       ; increase pointer
        jmp     .dont_test_second_digit   ;
     .skip_first_digit:                   ; only if less then 10
        test    edx, edx
        jz      .skip_second_digit
     .dont_test_second_digit:             ; if it was greater than 10
        add     dl, 030h                  ; than second digit must by
        mov     byte [ecx], dl            ; written at no condition
        inc     ecx
     .skip_second_digit:                  ; only skip if value was 0
        mov     byte [ecx], ah            ; save the null ending char
        retn    4                         ; ret and restore stack
; function prints null-terminated line to stdout
_show_line:
        push    edi                       ; function save registers
        push    esi
        mov     edi, dword [esp + 0Ch]    ; get the pointer to string
        sub     eax, eax                  ; look for zeros
        sub     ecx, ecx
        dec     ecx                       ; set ecx to -1
        repnz   scasb                     ; search for 0 in string
        neg     ecx
        sub     ecx, 2                    ; get the string length w/o zero
        mov     esi, dword [esp + 0Ch]    ; get pointer once again
     .putchar_loop:
        push    ecx                       ; keep the counter
        lodsb                             ; get the char
        push    eax
        call    _putchar                  ; print char to stdout
        add     esp, 4                    ; correct stack
        pop     ecx                       ; get back the counter
        dec     ecx
        jnz     .putchar_loop             ; if not last char then get next
        pop     esi                       ; restore registers
        pop     edi
        retn    4
; prints string for only one number
_bottles:
        push    ebp                       ; keep the offset to call params
        mov     ebp, esp
        sub     esp, 4                    ; reserve one local variable
        mov     eax, dword [ebp + 08h]    ; get number of bottles
        dec     eax                       ; is it 1?
        jnz     .more_than_one            ; nope, it's not
        push    _ending_lines             ; print the last lines
        call    _show_line
        jmp     .end                      ; exit function
     .more_than_one:
        inc     eax                       ; get the original value
        push    eax                       ; convert it to string
        lea     eax, [ebp - 04h]
        push    eax                       ; string will be stored here
        call    _integer_to_string
        lea     eax, [ebp - 04h]
        push    eax
        call    _show_line                ; 'xx'
        push    _line_1_1
        call    _show_line                ; ' bottles of beer on the wall, '
        lea     eax, [ebp - 04h]
        push    eax
        call    _show_line                ; 'xx'
        push    _line_1_2
        call    _show_line                ; ' bottles of beer.'
        mov     eax, dword [ebp + 08h]
        dec     eax                       ; in second line the value is one less
        push    eax
        lea     eax, [ebp - 04h]
        push    eax
        call    _integer_to_string        ; convert it to string
        push    _line_2_1
        call    _show_line                ; 'Take one down and pass it around, '
        lea     eax, [ebp - 04h]
        push    eax
        call    _show_line                ; 'xx'
        cmp     dword [ebp + 08h], 2
        jnz     .second_line_for_more_than_one
        push    _line_2_2_one             ; ' bottle of beer on the wall.'
        jmp     .show_line
     .second_line_for_more_than_one:
        push    _line_2_2                 ; ' bottles of beer on the wall.'
     .show_line:
        call    _show_line
     .end:
        leave
        retn    4
; main function, the command line arguments are not important
_main:
        pushad
        mov     ecx, 99                   ; printf from 99
     .main_loop:
        push    ecx
        push    ecx
        call    _bottles                  ; print lines for this value
        pop     ecx
        loop    .main_loop                ; if still greater than zero
        popad
        sub     eax, eax                  ; That's all folks!
        retn

Coloquei no GitHub para referência futura.
No ARM:
;99 Bottles of Beer generator
;For ARM processors running RISCOS
;Using built in BASIC assembler
;

MOV R7, #99              ;bottle count kept in R7
MOV R12, R14             ;store caller return address

.beginverse              ;(_prints verses then returns to caller_)
BL  bottlesofbeer
ADR R0, onthewall
SWI "OS_Write0"          ;prints string at address in R0
BL  bottlesofbeer
SWI "OS_NewLine"
ADR R0, take
SWI "OS_Write0"
SUBS R7,R7,#1
BLNE bottlesofbeer       ;beer left
BLEQ nobeer              ;no beer left
ADR R0, onthewall
SWI "OS_Write0"
SWI "OS_NewLine"
SWI "OS_NewLine"
BNE beginverse           ;go again if there's beer left
BL buymorebeer           ;print last verse
MOV PC, R12              ;exit to caller

.bottlesofbeer           ;(_prints "x bottle(s) of beer"_)
MOV R0, R7               ;arg1- number of bottles
ADR R1, bottlenum        ;arg2- buffer address
MOV R2, #3               ;arg3- buffer length
SWI "OS_ConvertInteger3" ;convert number of beers to string
SWI "OS_Write0"          ;and print it
CMP R7, #1
ADR R0, bottles          ;
ADREQ R0, bottle         ;bottles is replaced with bottle if 1 bottle left
SWI "OS_Write0"
ADR R0, ofbeer
SWI "OS_Write0"
CMP R1, #0               ;unset zero flag so "nobeer" doesnt execute after return
MOV PC, R14              ;return

.buymorebeer             ;(_prints final verse_)
MOV R11, R14             ;save return address
BL nobeer
ADR R0, onthewall
SWI "OS_Write0"
ADR R0, comma
SWI "OS_Write0"
BL nobeer
SWI "OS_NewLine"
ADR R0, gotostore
SWI "OS_Write0"
MOV PC, R11              ;return to saved address

.nobeer                  ;(_prints "no more bottles of beer"_)
ADR R0, nomore
SWI "OS_Write0"
ADR R0, bottles
SWI "OS_Write0"
ADR R0, ofbeer
SWI "OS_Write0"
MOV PC, R14

;string components

.ofbeer
EQUS "of beer"           ;string contents
EQUB 0                   ;zero terminator

.onthewall
EQUS " on the wall "
EQUB 0

.bottle
EQUS " bottle "
EQUB 0

.bottles
EQUS " bottles "
EQUB 0

.take
EQUS "Take one down and pass it around, "
EQUB 0

.nomore
EQUS "no more"
EQUB 0

.bottlenum
EQUS "  "
EQUB 0

.comma
EQUS ","
EQUB 0

.gotostore
EQUS "Go to the store and buy some more...99 bottles of beer."
EQUB 0

Coloquei no GitHub para referência futura.
Fonte.
Percebeu porque falam que deve comentar seu código? Era aí que deveria.
Perguntas relacionadas:

Como é feito um compilador?
O que é linguagem de programação, IDE e compilador?
A primeira linguagem de programação
Comment: @gato sim, é isso, em geral o montador já cria um executável com as partes que o sistema operacional precisa para entender esse código e carregar adequadamente na memória. Tem compilador que gera um Assembly e o Assembler é o responsável por gerar o binário.
Comment: Este [código](https://gist.github.com/drmcarvalho/af8f44049c751622e7b7f174028f990e) assembly gerado pelo GCC é traduzido pelo Assembler em código de maquina, e este mesmo código de maquina já esta ponto para ser executado, estou certo?
Comment: Não estou questionando a resposta, estou tentando entender, então o assembler não segue isso http://pt.stackoverflow.com/a/104818/3635 ? Ele é mais simples, então é um montador? Quero dizer, seria interessante linkar esta sua resposta dizendo algo "diferença entre compilador e montador"
Comment: @GuilhermeNascimento Não exatamente. O processo é parecido, mas as regras são muito mais simples. O que difere mesmo é a geração de código. Não há uma transformação complexa, ele não analisa o código de forma mais ampla. Ele lê uma instrução e gera o código binário dele, sem maiores preocupações se a semântica está correta. Não faz otimizações. É quase um conversor. Compiladores fazem análises e transformações mais complexas.
Comment: Sim, foi o que eu entendi (eu já havia lido a sua outra resposta), eu apenas comentei no sentido de que uma hora alguém iria perguntar. Quero dizer a outra resposta esta muito bem explicada e seria realmente legal linkar aqui, o que acha?
Comment: Opa, está ótima ;D
Answer:
O que é assembler? E qual a sua relação com assembly?

Assembler é um compilador. Ele converte código escrito na linguagem Assembly para código nativo.
Comment: Código nativo seria o código binário ou seja código de maquina correto?
Comment: @gato exatamente, código de máquina. Existem códigos binários que não são nativos, por exemplo MSIL ou bytecodes.
Comment: Vários OSes já vem com um Assembler instalado e pronto para uso, porém não existe nenhuma dependência específica.
Comment: Este compilador Assembler faz parte do Sistema Operacional, ou é algo que já esta no Hardware?
Answer: Assembly é uma linguagem de programação. Mas não é uma linguagem típica. Ela é caracterizada por ser uma linguagem de programação de baixo nível composta por instruções de formato rígido e simples que não permitem subestruturas e por alguns labels (rótulos que são alvos para instruções de desvio). Ela normalmente (quase sempre, mas há alguns casos que não) é mapeada de um para um em instruções a serem executadas pelo processador (uma instrução do processador = uma instrução em assembly).
Cada instrução é definida por um mnemônico. Por exemplo, em uma instrução MOV eax, 1 ou JN algum_label, o MOV e o JN são os mnemônicos, que são os que definem também o nome da instrução em questão.
Já o assembler é o programa que converte o código em assembly para as instruções propriamente ditas (codificadas como uma sequência de bytes). Ou seja, o assembler é o compilador. Apesar disso, a confusão entre os termos assembly e assembler é comum, e muita gente fala de "programar em assembler" quando na verdade deveria ser "programar em assembly".
Uma vez que há diversos tipos de processadores, cada qual com o seu conjunto de instruções, isso significa que para cada processador temos ao menos um dialeto de assembly. Diferentes desenvolvedores de assemblers podem usar notações diferentes ou mnemônicos diferentes para as instruções, e portanto, mesmo numa mesma arquitetura, podem haver vários distintos dialetos de assembly.
Comment: @gato Não é bem declaração não. Isso são instruções mesmo. Por exemplo ao invés de dizer `a = b`, em assembly seria `MOV b, a`. Ao invés de `c = c + d`, em assembly seria `ADD c, d`. Obviamente, isso depende ainda do dialeto de assembly específico.
Comment: Conheço muita gente que diz que programa em Dreamweaver, Netbeans, Eclipse, etc
Comment: Ótima resposta Victor ;D, só fiquei confuso em relação ao mnemônicos, eu não sei o que ele é, poderia esclarecer?
Comment: @gato Está melhor agora?
Comment: @VictorStafusa claro! Eh bem diferente das linguagens de programação tradicionais esses mnemônicos, neste caso seria sinônimo de "declaração ou statement" que é usada em linguagens de alto nível.
Answer: Achei está definição bem relevante:
Código de máquina:
É o a saída compilada por um compilador assembler.
Assembly
É a forma legível do código de máquina.
Assembly Language
Se refere a uma específica linguagem de código de máquina com x86 assembly.
Assembler
É a ferramenta usada para compilar código fonte em código de máquina.
Assembler Linguagem
É a linguagem usada por qualquer montador assembler.
Eu traduzi dessa resposta SO-en, achei boa, mas meu inglês não é o "the best"...

O que é assembler?


Prove an inequality for a specific Ordinary Differential Equation

Question: Let $a \in \mathbb R$
Consider the differential equation
$$\frac{d^9y}{dt^9}-\dfrac{dy}{dt}+ay=0 \tag 1$$
suppose $\varphi : \mathbb R \rightarrow \mathbb R$ is a solution of $(1)$ on $\mathbb R$.
Prove that there exists some $N\in \mathbb N$, $K \in (0,\infty)$ such that
$$\left[\sum_{j=0}^N\left(\frac{d^j\varphi(0)}{dt^j}\right)\right]^2\exp(-K|x|)
\le\sum_{j=0}^N \left(\frac{d^j\varphi(x)}{dt^j}\right)^2
\le \left[\sum_{j=0}^N \left(\frac{d^j\varphi(0)}{dt^j}\right)\right]^2 \exp(K|x|)$$
for any $x \in \mathbb R$.
Answer: Hint. Write $$Z=\begin{pmatrix}
y^{8}(x) \\
y^{7}(x) \\
\vdots \\
y(x)
\end{pmatrix}$$ The differential equation can be rewritten as $Z^\prime=AZ$ where $$A=\begin{pmatrix}
0 & 0 & \dots &  1 &-a \\
1 & 0 & 0 &  \dots &  0 \\
0 & 1 &  0 &  \dots & 0 \\
\vdots & \ddots &  \ddots & \ddots & \vdots \\
0 & \dots &  0  &  1 & 0 \\
\end{pmatrix}$$ Now you can apply techniques on order one linear differential equations of several of variables to find lower and upper bounds of the solutions.
Comment: Do you mean solve the system of ODE?


Are there any software to build and 3D simulate an entire audio visual live show?

Question: I know you can mix visuals with: resolume
I know you can create and perform electronic music with: Ableton
And I know you can design and perform light shows with: Sunlite Suite.
I also know softwares like quartz composer, max and touch designer that let you create and perform generative visuals; also interfacing with hardware like arduino.
But...
Is there a software where you can design and simulate and entire Audio, Light and Visual and then perform it before getting on the real stage ?
A show like this:

Otherwise; how big companies like Ultra or Immersive do ?
The should have a system to preproduce the live show in some way before getting into the venue and assembling it
any suggestions ?
Comment: Ableton offers [support for video](https://www.ableton.com/en/manual/working-with-video/) editing alongside audio production. Not sure if it's exactly what you are looking for, but it's probably worth a look.
Comment: Nope for video editing I use premiere and after effects.  I'm looking for an all in one solution to build and simulate in 3D a live show like the one above
Answer: There is no solution that does audio and video and light.
It's very, very expensive and time-consuming to pre-produce an entire show. Aside from preparation cost, you also have to factor in that all the needed equipment should be brought on tour as well. Most touring DJs cannot afford this and also cannot permit to lock down their playlist. There are a few exceptions ( Daft Punk, Amon Tobin and Deadmaus come to mind ), but festivals like Ultra are for the most part improvised using traditional audio, video and light equipment and software.
The DJ will mix records on Traktor or Pioneer CDJs. The light, video, laser, pyro and CO2 operators will then improvise along to this, each using their own hardware and software. They will have a wide range of material and presets prepared, some of it just for that show, and use these at the right time.
Some DJs ( the top of the DJ Mag top 100 ) travel with a LD and / or VJ, that bring custom material for that DJ and know the DJ's playlist particularly well.
On such tours, occasionally SMPTE is used to sync the visual and light show exactly to a track, but for the most part the big festivals like Ultra and Tomorrowland are improvised on the spot by the operators.


Setting the size of a button and action listener

Question: Problem 1:
I'm trying to set the size of my button, but doesn't seem to change and instead always fills the entire screen which isn't what I want.
Problem 2:
When I add the  public void actionPerformed1(ActionEvent e) with my message, it doesn't seem to show up. Maybe it's because of the button filling the entire space up, but I don't really know.
Here is the code for the buttons:
import java.awt.event.*;

import javax.swing.*;
import java.awt.*;
   public class HockeyGame extends JFrame implements
      ActionListener, KeyListener, Runnable, WindowListener  //, ActionListener
        {
        Thread t;
        int xpuck, ypuck,xspeed,yspeed,gx,gy,redx2,redy2,lg,rg, redscore, bluescore,
            redx,redy, gx2, gy2, bluex, bluey,bluex2,bluey2,rg2,lg2;
        //int SQUARE_SIZE=10;
        public HockeyGame ( ) {

            }

        public static void main ( String [ ] commandLine ) {
            HockeyGame hg=new HockeyGame();
            hg.init();
        }

        public void actionPerformed1(ActionEvent e) {
            JOptionPane.showMessageDialog(null,"testing");
        }
        public void init() {
            Button b;
            b = new Button("Click me");
            b.addActionListener(this);
            b.setSize(40, 40);
            add(b);
            t=new Thread(this);
            this.addKeyListener(this);
            this.setFocusable(true);
            setSize(700,700);
            setVisible ( true );

Any help is appreciatedasd
Comment: 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) Please use common Java nomenclature (i.e. `ypuck` -> `yPuck`) 3) **Don't set the size of buttons.**  Instead, use layouts, padding and layout spacing to put the button where it is needed at the size needed. 4) Use Key Bindings rather than `KeyListener`. 5) Create and alter GUIs on the EDT. 6) `JOptionPane.showMessageDialog(null,"testing");` should be `JOptionPane.showMessageDialog(this,"testing");` 7) The default layout of a `JFrame` content pane is `BorderLayout`, a component with no constraint is added to `CENTER`
Comment: I agree with all that Andrew posted and will add: read the [layout manager tutorials](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html) because your problems are due to a lack of understanding as to how they work.
Comment: Also, if you have two different issues, post them as separated questions
Answer: Start with simple exercises to make you strong in the basics.
1) Your Button fills up the space because the default layout of your content pane is Border Layout. Set the layout to Flow Layout or any other.
2) The function name should be exactly the same as that defined in Action Listener.

public void actionPerformed(ActionEvent e)
{}

None of what I said will make sense until you are strong with the basics.


Echarts bar graph - Is there a possibility of side scrolling?

Question: Is there a way to side scroll (I mean, on x axis) eCharts graph bar? I have a huge amount of data that needs to be displayed, so it cannot "fit" only browsers width, because the whole graph will be very hard to read (Every column loses on width).
My echarts version: <code>^4.0.4</code>
My chart
Comment: We can't transform images to code.
Comment: Can you tell me how much amount of data you have?
Comment: @IslamElshobokshy Was my code needed? I was looking just for specific echarts option.
Answer: You can add the attribute called dataZoom inside the object called options then pass this obj to the .setOption.
<code>    dataZoom: [
        {
            show: true,
            start: 94,
            end: 100
        },
        {
            type: 'inside',
            start: 94,
            end: 100
        },
        {
            show: true,
            yAxisIndex: 0,
            filterMode: 'empty',
            width: 30,
            height: '80%',
            showDataShadow: false,
            left: '93%'
        }
    ],
</code>
I saw this example but i don't know what you want precisely.
https://ecomfe.github.io/echarts-examples/public/editor.html?c=mix-zoom-on-value
Comment: That's what I was looking for. Didn't know I can solve this using value zoom.
Answer: I found this example that can help you:
Bar Chart with scrolling options
Answer: Here I have referred the open source javascript graph library for your slider chart requirement.
Plotly.js


If $a_n\ge0$ and $\sum a_n$ converges then $\sum\sqrt{a_na_{n-1}}$ converges, what about the converse?

Question:
Suppose the series $\sum_{n=1}^{\infty}{a_n}$ is convergent ($a_n \geq0$), Is it true that  $\sum_{n=1}^{\infty}\sqrt{a_na_{n-1}}$ is convergent ?
Is the converse true?

My attempt:
The first part I was able to do using AM-GM inequality and comparison test for series.
But I am not able to prove or generate a counter example for the second part.
Comment: Another example: fix $b_n$ to be any divergent series you like and define $a_{2n} = b_n$ and $a_{2n+1} = 0$. Then $a_na_{n-1} = 0$ so $\sum \sqrt{a_na_{n-1}} = 0$ is convergent but $\sum a_n = \sum b_n$ is divergent.
Comment: The title does a poor job at reflecting the question the OP asked.
Comment: Maybe if $a_n$ is decreasing.
Answer: No, it is not true. Define $a_n = n^2$ for $n$ even and $a_n = n^{-100}$ for $n$ odd. Then clearly $\sum a_n$ is divergent, but each term
$$\sqrt{a_n a_{n - 1}} \sim n^{-49}$$
gives a convergent series.
Answer: The converse is not ture. For example consider the following sequense $\{a_n\}$.
$$a_n =
\begin{cases}
\dfrac{1}{2^nn}   & \text{if $n$ is even} \\[2ex]
n & \text{if $n$ is odd .}
\end{cases}$$
Then $\sum\limits_{n=1}^{\infty}\sqrt{a_na_{n-1}}$ is convergent. But $\sum\limits_{n=1}^{\infty}{a_n}$ is divergent.


INSERT em duas Tabelas com base em SELECT

Question: Imagine o seguinte cenário:

Em determinado momento é necessário duplicar as pessoas e seus respectivos itens.
Se tenho os seguinte dados:
Tabela Pessoa

+----+------------+
| Id | Nome       |
+----+------------+
| 1  | Joãozinho  |
| 2  | Mariazinha |
+----+------------+

Tabela PessoaItem

+----+------------+--------+
| Id | PessoaId   | ItemId |
+----+------------+--------+
| 1  | 1          | 1      |
| 2  | 1          | 2      |
| 3  | 2          | 1      |
+----+------------+--------+

Tabela Item

+----+------------+
| Id | Descricao  |
+----+------------+
| 1  | Item1      |
| 2  | Item2      |
+----+------------+

Pode-se concluir com isso que Joãozinho possui o Item1 e Item2, e Mariazinha possui apenas o Item1.
Duplicando os dados, teríamos:
Tabela Pessoa

+----+------------+
| Id | Nome       |
+----+------------+
| 1  | Joãozinho  |
| 2  | Mariazinha |
| 3  | Joãozinho  |
| 4  | Mariazinha |
+----+------------+

Tabela PessoaItem

+----+------------+--------+
| Id | PessoaId   | ItemId |
+----+------------+--------+
| 1  | 1          | 1      |
| 2  | 1          | 2      |
| 3  | 2          | 1      |
| 4  | 3          | 1      |
| 5  | 3          | 2      |
| 6  | 4          | 1      |
+----+------------+--------+

Tabela Item
Permanece como anteriormente.
Para duplicar apenas uma tabela é fácil, basta rodar o seguinte script:
INSERT INTO Pessoa
(Nome)
SELECT Nome
FROM Pessoa

Mas e neste caso, que envolve mais de uma tabela? Qual a melhor forma de fazer isso?

Estou usando SQL Server.
Comment: Você tem de duplicar uma a uma, verificar que os ids são válidos, desabilitar triggers, em alguns casos constraints, etc.
Comment: Acho que o mais apropriado realmente seria criar um laço dentro de uma Transaction e fazer um a um.
Comment: Ok. Mesmo porque, em qualquer dos casos, no frigir dos ovos, será feito de um a um.
Comment: entendo, estou vasculhando a internet, mas não encontro nada que possa me ajudar a criar esse loop para trabalhar um a um dentro dele.
Comment: Vou postar um exemplo.
Comment: Por que você quer desnormalizar teu banco de dados?
Comment: Eu não quero não, mas o cliente tem meu WhatsApp, hahaha...
Answer: DECLARE @campo VARCHAR(30)
    , @campo2 VARCHAR(30)
    , @campo3 VARCHAR(60)

-- Cursor para percorrer os nomes dos objetos
DECLARE itens CURSOR FOR
    SELECT campo, campo2, campo3
    FROM
        tabela_origem

-- Abrindo Cursor para leitura
OPEN itens

-- Lendo a próxima linha
FETCH NEXT FROM itens INTO @campo, @campo2, @campo3

-- Percorrendo linhas do cursor (enquanto houverem)
WHILE @@FETCH_STATUS = 0
BEGIN

    INSERT INTO TABELA2 VALUES( @campo, @campo2, @campo3 )

    -- Lendo a próxima linha
  FETCH NEXT FROM itens INTO @campo, @campo2, @campo3
END

-- Fechando Cursor para leitura
CLOSE itens

-- Desalocando o cursor
DEALLOCATE itens

Comment: Muito obrigado @reginaldo-rigo fiz as adaptações e funcionou perfeito aqui.


How to determine the behavior of a function by analyzing it's Laplace transform?

Question: In an exercise, I'm given the Laplace transform of a function $f(t):$ $$\mathcal{L}\{y\}(s)=\frac{9}{s(s^2 + 3s + 1)}$$
and then the teacher asks the following question:

What is the behavior of the function $y$?

The function oscillates but doesn't converge
The function oscillates and converges to 3
The function oscillates and converges to 9
The function converges to 3 without any oscillations
The function converges to 9 without any oscillations

I tried to find an explicit formula for $y$ by trying to reverse the laplace transform but I wasn't able to do so. That got me thinking that maybe there is a way to solve this just by analyzing the laplace transform itself. I tried to look on my class notes for something that might help but I couldn't find anything, and on the internet I only found the following result:
$$\lim_{s\to\infty} s \ \mathcal{L}\{y\}(s) = y(0^+)$$
Is there a way to determine the behavior of $y$ just by analyzing its laplace transform? If so, are there any more important results like the one above (that relate the laplcae transform to the original function) that I should be aware of?
Comment: Your answer was perfect. Thank you @MarkViola
Comment: You're welcome.  My pleasure.
Answer: There is a property known as the "Final Value Theorem," that states
$$\lim_{t\to \infty}f(t)=\lim_{s\to 0}sF(s)$$
And the roots of the denominator are all real.
Can you finish now?


Solving an equation applying the IVT

Question: Suppose that $f: [0, 1] \to \mathbb{R}$ is a continuous function such that $f(0) = f(1)$. Prove that the equation $f(x) = f(x+(1/n))$ has solution for every $n \in \mathbb{N}$.
My guess is that defining $g: [0, 1-\frac{1}{n}] \to \mathbb{R}$ by $g(x) = f(x+\frac{1}{n}) - f(x)$ and seeing how its sign varies will do the job, hopefully by deriving a contradiction from the assumption that $f(0) = f(1)$, but I don´t know if there is some trick that I´m missing. Am I on the right track?
Answer: Hint :
$$g(0) + g\left(\frac{1}{n} \right)+...++ g\left(\frac{n-1}{n} \right) = f(1)- f(0)=0$$
And the $n$ values cannot be all strictly negative or strictly positive.
Comment: Thanks, now I can see how to argue. There has to some points where $g$ takes positive an negative values, and from there is an straight application of the IVT
Comment: @MrGran Exactly. You can also argue that: suppose $g(p/n) = \max_{i=0,...,n-1} g(i/n)$ and $g(q/n) = \min_{i=0,...,n-1} g(i/n)$ then $g(p/n) \ge 0$ and $g(q/n) \le 0$. It suffices to apply the IVT on the 2 points $p/n$ and $q/n$.
Comment: Oh I can see that argument too, because g is continuos and defined on a compact set the range is also compact and so g attains it's maximum and minimum value at some point in that set.

Solving an equation applying the IVT


Cannot upload file

Question: I have problems to upload a file:
Here is my html:
<%= form_tag import_test_path, multipart: true do %>
 <%= file_field_tag :file, :style => 'display:inline; margin-top:-10px' %>
 <%= submit_tag 'Hochladen', :class => 'btn btn-sm btn-info' %>
<% end %>

First i tried to simply upload it and to handle it in my controller like this:
  def import
    widgets = DBF::Table.new(params[:file], nil, 'cp1252')
    w = widgets.find(6)
    p = Patient.new
    p.vorname = w.vorname
    p.name = w.name
    p.geburtsdatum = w.geburt
    p.save
    respond_to do |format|
     format.html {redirect_to :back }
    end
  end

But this provoced an error:
 no implicit conversion of ActionDispatch::Http::UploadedFile into String
 in line: DBF::Table.new(params[:file], nil, 'cp1252')

Next i tried to generate first an Tempfile:
def import
    file = Tempfile.new(params[:file])
    widgets = DBF::Table.new(file, nil, 'cp1252')
    w = widgets.find(6)
    p = Patient.new
    p.vorname = w.vorname
    p.name = w.name
    p.geburtsdatum = w.geburt
    p.save
    respond_to do |format|
     format.html {redirect_to :back }
    end
  end

But this also proved an error:
 unexpected prefix_suffix: #<ActionDispatch::Http::UploadedFile:0x6793d10 @tempfile=#  <Tempfile:C:/Users/EMMANU~1/AppData/Local/Temp/RackMultipart20131110-6816-ogkd3i>, @original_filename="patient.DBF", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"patient.DBF\"\r\nContent-Type: application/octet-stream\r\n">
 in line: file = Tempfile.new(params[:file])

What do i wrong? Thanks and have a nice day!
Answer: Accessing params[:file] is a ActionDispatch::Http::UploadedFile which is just a wrapper for the TmpFile that is used to store the uploaded content.
You need to read from that IO like object to get the contents.
Comment: Can you describe me how i should read from the tempfile? The strange thing is that when i run `DBF::Table.new("filename.dbf", nil, 'cp1252')` locally i also only pass a `filename.dbf` file
Comment: I'm getting the string contains null byte issue as well. Did you ever figure it out @JohnSmith ?
Comment: @pav no sorry! At the end i found other solution that i cannot remember!
Answer: Try DBF::Table.new(params[:file].path, nil, 'cp1252')

Cannot upload file


Gitlab pipeline with Vault authentification

Question: I'm using a Gitlab 13.11.1 enterprise edition with free subscription.
I'm trying (into my pipeline) to authenticate to a Hashicorp Vault.
To achieve that I need the CI_JOB_JWT predefined variable.
According to that page the variable is available since version 12.10 and all tiers (free)
But that guide tells it is only for premium.
When I'm trying it seems the variable is empty (or not available).  I have a missing token error when trying the vault write ...
How can I be sure the CI_JOB_JWT is (or not) available with the free subscription ?
Comment: I understand your point of view.  But perhaps someone knows a gitlab link where it is writen that the variable in only available for premium (or not).  For the `why not ask` the response is simple.  I know how to do.  Lot of guides are explaining it.  But none is telling something about the CI_JOB_JWT availability according to the subscription.
Comment: `How can I be sure` Asking random people on some forum unrelated to gitlab is definitely not the way to be sure - you can't trust those people (well, unless you can). Ask gitlab employes or inspect the source code of gitlab server or runner. This is also not a programming problem. Are you sure you want to ask "how can I be sure" question? Why not ask "how to connect to hashicorp vault from gitlab-ci/cd?" ?
Answer: I know it's late but as I was testing a Vault config with a free tier "license" (on gitlab.com however, not with a dedicated instance), I can confirm the CI_JOB_JWT token is there and it works.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


using count in if statement and comparing with its returned value doesn't work

Question: if(count($arr1) === count($arr2) === 26)

In the above line it is throwing error
syntax error, unexpected '==='

Why can't i compare the value returned by count() with 26
Comment: That's just invalid PHP syntax. You'll have to split up the comparisons and use `&&`
Comment: @hek2mgl it's not low quality, many guys stucked with this http://stackoverflow.com/questions/1075534/cant-use-method-return-value-in-write-context?rq=1
Comment: It's **really** low quality and a duplicate as you have shown. Sorry, please don't take it personal. Just try to fix your errors for yourself. If it not works try harder, investigate! but don't ask such questions on SO
Comment: @Voitcus see the accepted answer
Comment: @MarkEvans Yes I have, but no syntax error would be if second comparison is in brackets: `if($a == ($b == $c))` has no syntax error (doesn't matter if use `==` or `===`), but in `if($a == $b == $c)` there is one. So the accepted answer is not 100% correct.
Comment: @MarkEvans I don't wanted to be offensive or something like that. I just wanted to say, if you want to get a programmer you'll have to learn to fix such problems for yourself. (Again, not offensive): Use the [manual](http://php.net/docs.php) it is **really** helpful.
Comment: @hek2mgl I think I really didn't made any efforts to investigate the problem and made some silly mistakes.
Comment: @MarkEvans Ok. :) However it is not so important anyway. it's just a question on SO (one out of 5 million :) .. You'll learn to fix such problems for yourself, I'm sure.. cu
Comment: -1 because really low quality
Comment: Well, I think this should have worked. At first, `count($arr2) === 26` should be evaluated to boolean `true` or `false`. Then `count($arr1)` should be (strictly) compared to boolean, giving `false` in any case. So why does this produce error? (I don't mean this makes something different than OP wants, but it should be valid -- I vote up).
Answer: You can but you have to do it separately:
if(count($arr1) === 26 && count($arr2) === 26)

Answer: If count($arr2) is 26
if(count($arr1) === count($arr2) === 26)

evaluates to
if(count($arr1) === True)

which would then fail.
You need to perform two logic checks and check they both evaluate to true
Comment: does it checks it backwards
Comment: Yes, from right to left
Comment: I've written the same in [my comment](http://stackoverflow.com/questions/17168889/using-count-in-if-statement-and-comparing-with-its-returned-value-doesnt-work#comment24857263_17168889), but there is a syntax error here.


Dropdown field listing all roles

Question: Is there a way to populate a content type field with the custom roles registered in Drupal (minus authenticated and anonymous)???
I have googled and found only quick hacks using custom modules, etc. Any ideas?
Answer: If your looking for a module then there is Role Field that creates a new field type that allows you to choose from the list of roles.

Dropdown field listing all roles


How can I detect the from state in UI-Router

Question: I am using UI-Router to develop a web application. I have a piece of code looking something like this:
$transitions.onStart({}, function(transition){
    let toState = transition._targetState._identifier;
    let fromState = transition._fromState._identifier;//this doesn't work
})

As you can see, the transition object contains a property called _targetState, but doesn't seem to contain a property indicating the from state. So how can I detect the from state.
Comment: the use of the from() method is correct.
Comment: I think the hook that you are using is wrong instead use onSuccess. $transitions.onSuccess({}, function(transition) {
  console.log(
      "Successful Transition from " + transition.from().name +
      " to " + transition.to().name
  );
});                                                                                Refer this: https://ui-router.github.io/guide/transitionhooks
Comment: Great that it works!
Answer: The methods to() and from() of the transition object are needed.
$transitions.onStart({}, function(transition){
    let toState = transition.to().name;
    let fromState = transition.from().name;
})


Can a set be unbounded under discrete metric?

Question: Suppose $(X,m)$ is a metric space and $A$ is a subset of $X$. Given that $m(x,y)$ is the discrete metric, can there possibly be a set that is unbounded wrt. $m$?
Answer: If by "the discrete metric" you mean that $m(x,y)=1$, then the answer is of course not. Since the entire space is bounded by $1$.
If by "the discrete metric" you mean any metric which induces the discrete topology, then $\Bbb N=X=A$ is an example.


Spring Boot with 2 database configs - lazy loading with second config does not work

Question: I have Spring Boot project with 2 database configs.
Primary DB config:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(transactionManagerRef = "primaryTransactionManager", entityManagerFactoryRef = "primaryEntityManagerFactory", basePackages = { "com.example.repository.primary" })
public class PrimaryDbConfig {

    @Primary
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.primary.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "primaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,         @Qualifier("primaryDataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.example.domain.primary").persistenceUnit("primary-persistence-unit").build();
    }

    @Primary
    @Bean(name = "primaryTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

And secondary:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "secondaryEntityManagerFactory", transactionManagerRef = "secondaryTransactionManager", basePackages = { "com.example.repository.secondary" })
public class SecondaryDbConfig {

    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.secondary.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,         @Qualifier("secondaryDataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.example.domain.secondary").persistenceUnit("secondary-persistence-unit").build();
    }

    @Bean(name = "secondaryTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

There is entity which is loaded with second DB:
@Entity
@Table(name = "users")
public class User {

    @OneToMany(mappedBy = "user")
    private List<Company> companies;

Using:
public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
}

When I use UserRepository, User is retrieved but when I hit to load companies, I get com.sun.jdi.InvocationException occurred invoking method. - com.sun.jdi.InvocationException occurred invoking method. If I change SecondaryDbConfig to @Primary or add fetch = FetchType.EAGER then companies are retrieved as expected. I have tried adding @Transactional(transactionManager="secondaryTransactionManager") but it didn't help.
What did I miss? What's the proper approach to lazy load entity properties when using not primary database config?
Comment: Do you add fetch eager to primary ? Does it work properly then. In the repository how do you tell it to use the secondary db config?
Comment: Lazy loading works well when I change secondary DB config to @Primary. In repository I don't specify anything except query methods. Config should specify which DB, transaction manager, entity manager should be used in specific package.
Comment: @JustinasJakavonis May I know, how did you fix this issue, we are facing same issue
Comment: @Premraj - don't remember
Answer: I have resolved this issue by adding @Transactional over @Service class.
Comment: Did you need to specify transactionManager?
Comment: no.. transactionManager we specified package level..
Answer: I was facing a similar issue. To enable lazy loading of JPA entity with multiple databases, you need to create seperate OpenEntityManagerInViewFilter beans for each database in your DBConfig classes.
I found the solution here:
spring-boot-jpa-multiple-data-sources
Search for the term "Lazy" in the article above.
Answer: Try to add @Transactional to your @Service method(s) or controller which retrieved list of company.
Good luck!


Variable selection with groups of predictors that are highly correlated

Question: What variable selection approach should I consider if I have thousands of predictors with clusters that are extremely correlated?
For example I might have a predictor set $X:= \{A_1,A_2,A_3,A_4,...,A_{39},B_1,B_2,...,B_{44},C_1,C_2,...\}$ with cardinality $|X| > 2000$. Consider the case where all $\rho(A_i,A_j)$ are very high, and similarly for $B$, $C$, ....
Correlated predictors aren't correlated "naturally"; it's a result of the feature engineering process. This is because all $A_i$ are hand engineered from the same underlying data with small variations in hand-engineering methodology, e.g. I use a thinner pass band on $A_2$ than I did for $A_1$ in my denoising approach but everything else is the same.
My goal is to improve out of sample accuracy in my classification model.
One approach would just be to try everything:  non-negative garotte, ridge, lasso, elastic nets, random subspace learning, PCA/manifold learning, least angle regression and pick the one that's best in my out of sample dataset. But specific methods that are good at dealing with the above would be appreciated.
Note that my out of sample data is extensive in terms of sample size.
Comment: I am also working with correalted data and i am getting quite good results with lasso.
Answer: I would do the forward stepwise selection, adding predictors as long as the correlation with residuals is significant, and then do some regularization (ridge, lasso, elastic nets).  There are 2-3 metaparameters: forward stepwise termination constraint, and 1 or 2 regularization parameters. These metaparameters are determined via cross-validation.
If you want to take into account non-linearity, you could try random forest, which produces good results when there are many predictors.  But it is slow.
Comment: My data is not of the form to trust a test on the Pearson correlation. In fact it would violate almost every assumption of such a test. Is this still the approach you would take?
Comment: How did you produce the data?  Why you cannot trust a test on the Pearson correlation?  Please elaborate.
Comment: Heteroscedasticity, non-normality, autocorrelation, non stationarity. Pearson correlation test unbiasedness is known to be extremely susceptible to violations of its assumptions.
Comment: What do you mean by autocorrelation and non-stationarity? Your dependent variable and predictors are time series?
Comment: Yes these are time series which display autocorrelation and non-stationarity. e.g. in the post I talk about pass bands and denoising.
Comment: Then I would still use the same approach, each time adding the most correlative predictor, but instead of the statistical significance, I would use the number of predictors as a metavariable.  Note however that the autocorrelation makes predictors more, not less, significant, so you never want to add insignificant predictors. To determine metaparameters, I'd use a validation by rolling.
Answer: Features extracted from image/signal processing tend to get correlated a lot! This is not a very bad thing if you have enough samples.
From my experience, a classifier with small variance tend to work well (ex. logistic regression). They have less chances of overfitting the train data.
Another idea that I employed is the Additive logistic regression here and here some references. They are already implemented in Weka. They are slower than the logistic models. In the same time they have the great advantage that they perform a feature selection while learning. Moreover, the model is human friendly so you can see what features are more relevant.
Hope it helps
Comment: I think the question is about _regression_, not _classification_.
Comment: Different faces of the same coin.


How do you save progress during a Keras Tuner run?

Question: I am currently shifting through a larger search space with Keras Tuner on a free Google Colab instance. Because of usage limits, my search run will be interrupted before completion. I would like to save the progress of my search periodically in anticipation of those interruptions, and simply resume from the last checkpoint when the Colab resources become available to me again.
I found documentation on how to save specific models from a run, but I want to save the entire state of the search, including what was already tried and the results of those experiments.
Can I just call Tuner.get_state(), save the result, and then resume from where I left off with Tuner.set_state()? Or is there another way?
Answer: You don't need to call tuner.get_state() and tuner.set_state(). While instantiating a Tuner, say a RandomSearch, as mentioned in the example,
# While creating the tuner for the first time
tuner = RandomSearch(
    build_model,
    objective="val_accuracy",
    max_trials=3,
    executions_per_trial=2,
    directory="my_dir",
    project_name="helloworld",
)

You need to set the arguments directory and project_name. The checkpoints are saved in this directory. You may save this directory as a ZIP file and download using  files.download().
When you get a new Colab instance, unzip that archive and restore the my_dir directory. Instantiate a Tuner again using,
# While loading the Tuner
tuner = RandomSearch(
    build_model,
    objective="val_accuracy",
    max_trials=3,
    executions_per_trial=2,
    directory="my_dir", # <----- Use the directory as you did earlier
    overwrite=False, # <-------
    project_name="helloworld",
)

Now start the search and you'll notice that the best params so far hasn't changed. Also, tuner.results_summary() returns all search results.
See the documentation for the Tuner class here.
Comment: Thank you! Reading the documentation a week earlier the description "directory: A string, the relative path to the working directory." did not provide enough information on what to do with it. With your answer at hand it now seems obvious.


inter-rater reliability for numeric variables

Question: I've seen some questions on inter-rater reliability here for categorical variables. I'm wondering what would be an adequate approach to test inter-rater reliability between two raters for a numeric variable ?

Suppose, for example, that I have two teachers assessing students on a test and I need to check the teachers (aka, raters) reliability. Both teachers will provide numerical scores/grades for the tests.

As far as I'm concerned, both Cohen's Kappa and Weighted kappa are for categorical and ordinal variables (respectively, right?). I've seen approaches to use Cronbach's Alpha or intraclass correlation - ICC or even Pearson's correlation , would any of these  be adequate or any other test?
This is more of a theorical question, but tips on calculating this in R Studio would be much appreciated as well. Thanks in advance.
Comment: Your question reminded me of [this paper](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6430129/), which had human raters rate facial expressions using a joystick, so continuous movement equated with facial intensity. The authors used several strategies, including Krippendorf's a, Fleiss' k, ICC, and simple coefficient matching, so at the very least there is precedence for ICC on continuous data.
Answer: As per literature (Analyzing Rater Agreement p.115-122), ICC is indeed the solution for the case where we can't relate the data as categorical. This comes alongside Cronbach's $\alpha$ (which is used for test-retest cases) and of course Spearman's correlation $\rho$.
This question provides a similar answer.
Comment: @LarissaCury There are different formulations of the ICC that answer different questions. One of these formulations, often called ICC(C,k), is equivalent to Cronbach's alpha. But the other formulations will differ.
Comment: thank you, @Spatzle, I've just read the chapter of the material you've recommended. Things are clearer now. Authors mention that Cronbach's α is a special case of ICC, but this is not clear to me yet, I've seen elsewhere that they'd be the same thing, I'm a bit confused. Any thoughts? Concerning correlation, as far as I'm concerned, the 'consistent' approach would equal Pearson's rho, right?


Lyapunov Theorem for beginners

Question: I study the subject of fair division (cake-cutting), and many papers contain a reference to a theorem by Lyapunov, which states that the range of any real-valued, non-atomic vector measure is compact and convex.
Can you recommend an online resource that can help me understand this theorem in an intuitive fashion, without having to read an entire book or take an entire course?
Note: I am not looking to become an expert in this field; I just want to get some intuition about this theorem, so that I can understand the papers that rely on it.
Answer: The most famous and most elegant proof of Lyapunov's vector measure theorem is to be found in

Joram Lindenstrauss, A short proof of Liapounoff's convexity theorem.
  J. Math. Mech., 15:971–972, 1966.

The proof requires, however, some knowledge of functional analysis and the paper is not that easy to get your hands on. An elementary proof of the result can be found in:

David A. Ross, An Elementary Proof of Lyapunov's Theorem. The American
  Mathematical Monthly , Vol. 112,7:651-653, 2005

That paper gives also references to some other proofs.
Most proofs of Lyapunov's theorem I know are highly nonconstructive. For a relatively constructive proof, see

Alan Hoffman, Uriel G. Rothblum, A proof of the convexity of the
  range of a nonatomic vector measure using linear inequalities,
  Linear Algebra and its Applications, Volume 199, Supplement 1, 1 March
  1994, Pages 373-379

For an alternative proof of the one-dimensional case used in that paper, see here.

Lyapunov Theorem for beginners


How to create a custom validation attribute with parameters consisting of model properties

Question: I am currently trying to make a site on asp.net core. When i press the submit button, i want all the validation messages to come up if there is incorrect input.

For now, i have the name and the phone number validation messages working using 'asp-validation-for=Client.Name' and Client.ContactNumber. Now i want to be able to validate from the server side if the user has checked at least one of the boxes off, or filled in the 'Other' field. So i tried to see if i can make a custom attribute which would validate it but havent gotten any luck. I have tried sending in the properties of the Client class but it throws an error saying "An object reference is required for the non-static field, method, or property 'Client.'". I have also tried the top solution here CS0120: An object reference is required for the nonstatic field, method, or property 'foo' , but I think in my case those solutions are not possible.
My code for the files that i am working with are below
Code for Client.cs (model class)
public class Client
{
    //some attributes

    [Required]
    public string Name { get; set; }

    [Required]
    [DisplayName("Bookkeeping")]
    public bool Bookkeeping { get; set; }

    [Required]
    [DisplayName("Personal Income Taxation")]
    public bool Personal_Income_Taxation { get; set; }

    [Required]
    [DisplayName("Self-Employed Business Taxes")]
    public bool Self_Employed_Business_Taxes { get; set; }

    [Required]
    [DisplayName("GST/PST/WCB Returns")]
    public bool GST_PST_WCB_Returns { get; set; }

    [Required]
    [DisplayName("Tax Returns")]
    public bool Tax_Returns { get; set; }

    [Required]
    [DisplayName("Payroll Services")]
    public bool Payroll_Services { get; set; }

    [Required]
    [DisplayName("Previous Year Filings")]
    public bool Previous_Year_Filings { get; set; }

    [Required]
    [DisplayName("Govt. Requisite Form Applicaitons")]
    public bool Government_Requisite_Form_Applications { get; set; }

    public string Other { get; set; }

    [CheckboxAndOtherValidation(bookkeeping: Bookkeeping,
        personal_Income_Taxation: Personal_Income_Taxation,
        self_Employed_Business_Taxes: Self_Employed_Business_Taxes,
        gST_PST_WCB_Returns: GST_PST_WCB_Returns,
        tax_Returns: Tax_Returns,
        payroll_Services: Payroll_Services,
        previous_Year_Filings: Previous_Year_Filings,
        government_Requisite_Form_Applications: Government_Requisite_Form_Applications,
        other: Other)]
    public bool AreCheckboxesAndOtherValid { get; set; }

FreeConsultation.cshtml (view page)

Create New Client

    <form method="post">

                <input type="text" asp-for="Client.Name" class="form-control" />

My utility class i created for custom validation attribute - CheckboxAndOtherValidation.cs
    public class CheckboxAndOtherValidation : ValidationAttribute
{
    private readonly bool Bookkeeping;
    private readonly bool Personal_Income_Taxation;
    private readonly bool Self_Employed_Business_Taxes;
    private readonly bool GST_PST_WCB_Returns;
    private readonly bool Tax_Returns;
    private readonly bool Payroll_Services;
    private readonly bool Previous_Year_Filings;
    private readonly bool Government_Requisite_Form_Applications;
    private readonly string Other;

    public CheckboxAndOtherValidation(bool bookkeeping,
        bool personal_Income_Taxation,
        bool self_Employed_Business_Taxes,
        bool gST_PST_WCB_Returns,
        bool tax_Returns,
        bool payroll_Services,
        bool previous_Year_Filings,
        bool government_Requisite_Form_Applications,
        string other)
    {
        this.Bookkeeping = bookkeeping;
        this.Personal_Income_Taxation = personal_Income_Taxation;
        this.Self_Employed_Business_Taxes = self_Employed_Business_Taxes;
        this.GST_PST_WCB_Returns= gST_PST_WCB_Returns;
        this.Tax_Returns = tax_Returns;
        this.Payroll_Services = payroll_Services;
        this.Previous_Year_Filings = previous_Year_Filings;
        this.Government_Requisite_Form_Applications = government_Requisite_Form_Applications;
        this.Other = other;

    }

    public override bool IsValid(object value)
    {
        return base.IsValid(value);
    }
}

Is there any other way to tackle this? (Preferably with custom attribute). First time posting a question so pardon me if there is anything missing. Thanks
EDIT
I was able to make the checkbox error come from the server side with the help of a solution, but i still have the issue that when i press the submit button, the checkbox error doesn't come at the same time as the other two. By following a tutorial, i was able to show the other two errors from the client side by including this piece of code in my view which comes with the creation of an asp.net core project

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

_ValidationScriptsPartial.cshtml

<environment include="Development">

</environment>
<environment exclude="Development">

</environment>
Answer: Some references are here

Article custom-data-annotation-validation-in-mvc
Source code of CompareAttribute.cs and ComparePropertyAttribute.cs
3rd-party ExpressiveAnnotations

So in a similar way, a custom ValidationAttribute can use reflection to get runtime value by its property name (the name from declaration or argument) to see if the property have the required value or format you need.
public class CheckboxAndOtherValidation : ValidationAttribute
{
    readonly object TRUE = true;
    string[] _alltheOtherProperty;

    public CheckboxAndOtherValidation(params string[] alltheOthersProperty)
    {
        _alltheOtherProperty = alltheOthersProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (_alltheOtherProperty?.Count() > 0 != true)
        {
            return ValidationResult.Success;
        }

        var otherPropertyInfo = validationContext.ObjectType.GetProperty(nameof(Client.Other));
        if (otherPropertyInfo != null)
        {
            object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (otherPropertyValue != null && !string.IsNullOrEmpty(otherPropertyValue.ToString()))
            {
                return ValidationResult.Success;
            }
        }

        for (var i = 0; i < _alltheOtherProperty.Length; ++i)
        {
            var prop = _alltheOtherProperty[i];
            var propertyInfo = validationContext.ObjectType.GetProperty(prop);
            if (propertyInfo == null)
            {
                continue;
            }

            object propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (Equals(TRUE, propertyValue))
            {
                return ValidationResult.Success;
            }
        }

        return new ValidationResult("Must exist at least one field is true", _alltheOtherProperty);
    }
}

Cus I choose passing property name array list as argument, now class Client could have a simplified and clearer usage like this,
public class Client
{
    [CheckboxAndOtherValidation(nameof(Bookkeeping),
        nameof(Personal_Income_Taxation),
        nameof(Self_Employed_Business_Taxes),
        nameof(GST_PST_WCB_Returns),
        nameof(Tax_Returns),
        nameof(Payroll_Services),
        nameof(Previous_Year_Filings),
        nameof(Government_Requisite_Form_Applications))]
    public bool AreCheckboxesAndOtherValid { get; set; }
}

Comment: correct me if im wrong, but in the first if statement, you're checking if _alltheOtherProperty has more than 0 values, the second if statement you're checking if the "Other" field is not null, and the for loop in the end checks if all of them are not false?
Comment: @gupta_28 I think you've read my example very well. Feel free to modify to meet your needs. For instance, you can return errors if `_alltheOtherProperty` is NullOrEmpty array.
Comment: also, what is "ClientAddressInfo"?
Comment: @gupta_28 Sorry it's typo. I've replaced with your class **Client**. Please check again.
Comment: okay i thought so. So i tried using your solution, and what im getting is that when i hit the submit button, i still don't get the checkbox error that i am looking for. I tried adding the "ErrorMessage = 'blah'" to my client class as part of the attribute but it is still not working. I put a debugger in the IsValid method but it only gets hit if i input a valid name and contact number. Is there a way to get the message along with the other two error messages that i display?
Comment: @gupta_28 You can double check and follow this article [custom-data-annotation-validation-in-mvc](https://www.c-sharpcorner.com/article/custom-data-annotation-validation-in-mvc/) to test smaller pieces of your model. Since I've tested 3 scenarios which are all hit the correct results, `1) $.Others is not empty -> valid, 2) $.Others is null, one of the flags is true -> valid, 3) $.Others is null, all of the flags are false -> invalid`. So the logic parts should work fine, the problem you occurred might be property name dismatch or data type issues.
Comment: ok thanks that helped. Do you have any idea about how to show the errors from the client side? (i updated the question)
Comment: You are welcome. Have you tried `@Html.ValidationMessageFor(model => model.AreCheckboxesAndOtherValid, "", new { @class = "text-danger" })`  ? See [custom-data-annotation-validation-in-mvc](https://www.c-sharpcorner.com/article/custom-data-annotation-validation-in-mvc/) for more detail please.
Comment: @gupta_28 Don't have any clue yet. Try simplify your question and create a new post . You might get new answers.


MANOVA with variables from different datasets

Question: I conducted several experiments where I have one underlying independent variable (tree species, IV). Each of these experiments gave me one dependent variable (DV), like bark pH, rugosity or the water-holding capacity. Now I want to conduct a MANOVA to see if the tree species differ in the various dependent variables. My analysis is conducted in R.
My model therefore looks like:
pH + rugosity + water-holding capacity + [...] ~ tree species
where I have per tree species...

3 measurements of the bark pH.
9 measurements of the bark rugosity.
4 measurements of the bark thickness,
5 measurements of the water-holding capacity,
5 measurements of the water retention.

However, unlike most examples I've found on how to do a MANOVA (i.e. here, here, here), my data stems from different measurements and from different individuals. Now, I've found only this thread discussing unequal sample sizes, but this targets only sample sizes within the explaining factor.
My Question:
My dependent variables all have different sample sizes. Would a MANOVA be appropriate for such kind of data? Can I just ignore the different variable sizes? Is there an alternative way to do this or rather an alternative statistic test? Does my small sample size matter?
EDIT: What I really want to find out
I really just want to conduct a statistical test telling me, if I have an underlying pattern. So are the tree species different in regards to the dependent variables? In the end I want to be able to tell, if some species have a certain set of traits different from other species.
Example Data:
My data looks like this:
> manova_df
    # A tibble: 45 x 6
   tree_species rugosity bark_mm    pH   whc   ret
   <fct>           <dbl>   <int> <dbl> <dbl> <dbl>
 1 AS              2.36        8  6.49  295. 119.
 2 AS              1.45        8  6.83  222. 105.
 3 AS              3.13        9  5.8   291. 181.
 4 AS              2.38        8 NA     314. 214.
 5 AS              4.39        7 NA     613. 317.
 6 AS              2.21       NA NA      NA   NA
 7 AS              0.810      NA NA      NA   NA
 8 AS              1.58       NA NA      NA   NA
 9 AS              0.934      NA NA      NA   NA
10 BU              3.34        6  7.22  189.  74.9
# ... with 35 more rows

The NAs stem from the fact that I have different sample sizes but had to get all the variables into one data.frame. So I just binded all the columns of the different observations together. This means, that the single observations of the various DVs are not tight together and the order within the tree species levels is totally arbitrary!
My analysis is pretty straightforward:
mano_mod = manova(cbind(pH, bark_mm, rugosity, whc, ret) ~ tree_species, data = manova_df)
> summary(mano_mod)
             Df Pillai approx F num Df den Df    Pr(>F)
tree_species  4 2.4207    3.372     20     44 0.0003836 ***
Residuals    12
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Full Data Set:
structure(list(tree_species = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("AS", "BU", "CL",
"MB", "PR"), class = "factor"), rugosity = c(2.36, 1.45, 3.13,
2.38, 4.39, 2.21, 0.81, 1.58, 0.93, 3.34, 5.06, 0, 0.77, 12.64,
4.1, 0.8, 1.03, 0.84, 6.49, 9.09, 5.96, 5.32, 8.41, 15.29, 9.91,
7.65, 2.13, 9.43, 10.14, 13.24, 10.26, 9.81, 12.34, 17.23, 16.63,
8.82, 1.68, 0.7, 0.82, 2.43, 0, 0.76, 0.77, 0, 1), bark_mm = c(8L,
8L, 9L, 8L, 7L, NA, NA, NA, NA, 6L, 8L, 8L, 7L, 9L, NA, NA, NA,
NA, 9L, 9L, 8L, 10L, 9L, NA, NA, NA, NA, 5L, 9L, 9L, 8L, 4L,
NA, NA, NA, NA, 5L, 5L, 5L, 6L, NA, NA, NA, NA, NA), pH = c(6.49,
6.83, 5.8, NA, NA, NA, NA, NA, NA, 7.22, 7.11, 7.72, 7.29, NA,
NA, NA, NA, NA, 7.39, 7.18, 7.3, 7.3, NA, NA, NA, NA, NA, 6.76,
6.55, 6.24, NA, NA, NA, NA, NA, NA, 5.76, 6.59, 5.44, NA, NA,
NA, NA, NA, NA), whc = c(295.2, 222.4, 290.6, 314.3, 613.4, NA,
NA, NA, NA, 189.4, 248.2, 336.8, 330.1, 427.8, NA, NA, NA, NA,
236, 492.6, 549.3, 330.1, 370.7, NA, NA, NA, NA, 430, 142.2,
372.4, 260, 176.1, 680, 215, NA, NA, 333.8, 320.6, 282.4, 322.9,
576.7, NA, NA, NA, NA), ret = c(118.9, 104.9, 180.6, 214.5, 317.3,
NA, NA, NA, NA, 74.9, 95.7, 127.3, 150.1, 327.3, NA, NA, NA,
NA, 80.8, 176.7, 255.7, 142.6, 236.6, NA, NA, NA, NA, 148.4,
32.4, 244.2, 66.8, 76.4, 246.1, 73.6, NA, NA, 111.2, 151.3, 102.1,
200.6, 258.1, NA, NA, NA, NA)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -45L))

(If anything is unclear, please ask.)
Comment: imo you've removed too much relevant information ....
Comment: @Jaap hm, what do you miss? I tried to focus only on my problem...
Comment: [Here](https://stats.stackexchange.com/questions/77812/manova-with-unequal-sample-sizes) is a discussion about MANOVA with different sample size.
Comment: @pockeystar As stated above in my question, the mentioned question only targets different sample sizes in the independent variable, i.e. if I had sample 1000 trees of one species and only 10 of another. However, in my case the number of sampled individuals per tree species are the same but different for each dependent variable.
Comment: Among others, you had a five-item-list describing the type of data you have. I think that is quite informative and maybe even essential to the question.
Comment: If you can put the whole data set up there that would certainly help me walk through one option for dealing with these data.
Comment: Why do you stick on the MANOVA? What MANOVA can do, the Linear mixed model also can do, and there are several advantages over MANOVA. One of advantages is incorporating the missing value. In addition, why you cannot analysis the dependent variables one by one? What do you want to get beyond the univariate (one by one) analysis?
Comment: @user158565 Good point to think of linear mixed models, I didn't know they work with multiple DVs as well. Why I want to conduct a MANOVA: I basically just want to conduct one test to see an underlying pattern that I would probably miss if I just did individual ANOVAs (see my Edit). Does this make sense?
Comment: Then linear mixed model can be used to fit your data.
Answer: One option here is to think of this as a missing data problem. You have varying amounts of information for each case (different tree species) that you have classified as one of five different species. If you can meet the assumption that the data are missing at random, you could impute.
Before going any further though, I you should let you know that I am going to argue against a MANOVA for these data. This is a small data set to be missing as many scores as I can already see in the first 10 rows. In fact if you look at your degrees of freedom you only had a total of 17 cases with complete data. MANOVA is going to listwise delete - so you lose all non-complete cases. Right now your inferential test is based on less than half your data and that seems suboptimal to me.
My guess is that you would prefer to make inferences using as much information as is possible, which is going to be limited if you are using a MANOVA without some sort of imputation. Even if you did impute, Finch (2016) found that missing rates over 40%, even under the condition that they were missing at random (i.e., MAR), may cause an undesirable inflation of Type I error. His simulation study was based on two groups with 50 observations per group (i.e., $N = 100$). Your model can likely tolerate even less missing data given both a smaller total sample ($N_{max} = 45)$ and a larger number of groups ($k=5$).
If it is not possible to include the observed scores for the cases that are missing values on your different measures, I would recommend considering an approach in which you impute your data using as much information as you have about your cases (i.e., if there are additional variables you have access to that are completely observed across all cases), and then perform a series of one-way ANOVAs. Check out the mice and Amelia packages in R for imputation options.
Another reason to drop the whole MANOVA model other than your missing data is that it may not be all that good of a conceptual fit. Unless you have a strong hypothesis about group differences on the location of the mutlivariate distributions (i.e., their centroids), you gain little by performing a MANOVA in the first place. There is a myth out there still floating around that running a MANOVA is somehow going to protect you against Type I inflation that results from multiple comparisons, which is something it doesn't really do all that well.
My guess is that you are most likely interested in which dimensions your different species differ on. You were going to have to conduct follow-up one-way ANOVAs to find out anyway, so why not cut out the MANOVA middle man, which does nothing to control type I error of these separate one-way ANOVAs?
UPDATE:
I think the gls option from Heteroskedastic Jim is a clever solution if you want to keep this in one model. But it does require a complex model for a simple problem, and without more complex random effects being specified in the model, I am not sure what the approach "buys" over and above the simpler ANOVA approach with multiple comparisons. For clarity (using the data you provided), here is what you would get with an ANOVA workflow for rugosity. Note for comparison purposes to the gls example above I am not imputing any values here.
fit.lm1<-lm(rugosity~tree_species, data=dat)
fit.lm1.aov<-aov(fit.lm1)

First, and importantly, the overall omnibus test is significant:
             Df Sum Sq Mean Sq F value   Pr(>F)
tree_species  4  763.1  190.77   23.49 4.78e-10 ***
Residuals    40  324.9    8.12
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

And now for the model coefficients:
Call:
lm(formula = rugosity ~ tree_species, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-5.6756 -1.8456 -0.1467  0.9244  9.4644

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)       2.138      0.950   2.250 0.029992 *
tree_speciesBU    1.038      1.343   0.772 0.444374
tree_speciesCL    5.668      1.343   4.219 0.000137 ***
tree_speciesMB    9.851      1.343   7.333 6.48e-09 ***
tree_speciesPR   -1.231      1.343  -0.916 0.364958
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.85 on 40 degrees of freedom
Multiple R-squared:  0.7014,    Adjusted R-squared:  0.6715
F-statistic: 23.49 on 4 and 40 DF,  p-value: 4.775e-10

But to make a little more sense of the differences between your 5 species, a set of $p$ values based on multiple comparisons might help. I am using the more conservative Bonferonni correction here to reduce Type I error inflation, but alternatives exist.
pairwise.t.test(dat$rugosity, dat$tree_species, p.adj = "bonferroni")

Which returns:
Pairwise comparisons using t tests with pooled SD

data:  dat$rugosity and dat$tree_species

   AS      BU      CL      MB
BU 1.0000  -       -       -
CL 0.0014  0.0135  -       -
MB 6.5e-08 7.7e-07 0.0341  -
PR 1.0000  0.9903  7.7e-05 3.6e-09

P value adjustment method: bonferroni

That is your most complete variable. So what happens with a different DV? Well with bark_mm you'd get the following output:
fit.lm2<-lm(bark_mm~tree_species, data=dat)
fit.lm2.aov<-aov(fit.lm2)
summary(fit.lm2.aov)
             Df Sum Sq Mean Sq F value  Pr(>F)
tree_species  4  34.01   8.502   5.056 0.00603 **
Residuals    19  31.95   1.682
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
21 observations deleted due to missingness

summary(fit.lm2)

Call:
lm(formula = bark_mm ~ tree_species, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-3.0000 -0.3375  0.0000  0.8125  2.0000

Coefficients:
               Estimate Std. Error t value Pr(>|t|)
(Intercept)      8.0000     0.5799  13.795 2.38e-11 ***
tree_speciesBU  -0.4000     0.8201  -0.488  0.63133
tree_speciesCL   1.0000     0.8201   1.219  0.23765
tree_speciesMB  -1.0000     0.8201  -1.219  0.23765
tree_speciesPR  -2.7500     0.8699  -3.161  0.00514 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.297 on 19 degrees of freedom
  (21 observations deleted due to missingness)
Multiple R-squared:  0.5156,    Adjusted R-squared:  0.4136
F-statistic: 5.056 on 4 and 19 DF,  p-value: 0.006027

pairwise.t.test(dat$bark_mm, dat$tree_species, p.adj = "bonferroni")

    Pairwise comparisons using t tests with pooled SD

data:  dat$bark_mm and dat$tree_species

   AS     BU     CL     MB
BU 1.0000 -      -      -
CL 1.0000 1.0000 -      -
MB 1.0000 1.0000 0.2473 -
PR 0.0514 0.1414 0.0038 0.5865

P value adjustment method: bonferroni

Now compare this with the relevant gls model output:
Coefficients:
                                  Value Std.Error   t-value p-value
(Intercept)                      8.0000   0.57993 13.794673  0.0000
tree_speciesBU                  -0.4000   0.82015 -0.487715  0.6267
tree_speciesCL                   1.0000   0.82015  1.219288  0.2252
tree_speciesMB                  -1.0000   0.82015 -1.219288  0.2252
tree_speciesPR                  -2.7500   0.86990 -3.161279  0.0020
measurepH                       -1.6267   0.61771 -2.633383  0.0096
measureret                     179.2400  37.30808  4.804321  0.0000
measurerugosity                 -5.8622   1.11299 -5.267085  0.0000
measurewhc                     339.1800  64.50607  5.258110  0.0000
tree_speciesBU:measurepH         1.3617   0.86708  1.570412  0.1191
tree_speciesCL:measurepH        -0.0808   0.86708 -0.093225  0.9259
tree_speciesMB:measurepH         1.1433   0.87357  1.308800  0.1932
tree_speciesPR:measurepH         2.3067   0.92044  2.506045  0.0136
tree_speciesBU:measureret      -31.7800  52.76159 -0.602332  0.5481
tree_speciesCL:measureret       -9.7600  52.76159 -0.184983  0.8536
tree_speciesMB:measureret      -59.3971  48.84873 -1.215940  0.2265
tree_speciesPR:measureret      -19.8300  52.76239 -0.375836  0.7077
tree_speciesBU:measurerugosity   1.4378   1.57401  0.913450  0.3629
tree_speciesCL:measurerugosity   4.6678   1.57401  2.965536  0.0037
tree_speciesMB:measurerugosity  10.8511   1.57401  6.893937  0.0000
tree_speciesPR:measurerugosity   1.5189   1.60049  0.949012  0.3446
tree_speciesBU:measurewhc      -40.3200  91.22536 -0.441982  0.6593
tree_speciesCL:measurewhc       47.5600  91.22536  0.521346  0.6031
tree_speciesMB:measurewhc      -21.0800  84.45884 -0.249589  0.8034
tree_speciesPR:measurewhc       22.8500  91.22582  0.250477  0.8027

Where is your bark_mm variable in the model? Well, it may not be obvious initially, but bark_mm is actually your reference measure. So you'll have to tweak the reference value in your gls model to get the comparison you want. This is not a condemnation of the approach, just a minor annoyance, and a reason I think the ANOVA workflow is more straightforward in getting you want you want in the end. And if Type I error is a concern, ANOVAs can still be used responsibly without inflating Type I error, with appropriate corrections.
Also, don't forget that you need to get your different species pairwise comparisons out of the gls model if you stick with that approach (which is certainly doable - and as an aside the pairwise.t.test() function is far from the only option for post hoc mean comparisons).
Reference(s)
Finch, W. H. (2016). Missing data and multiple imputation in the context of multivariate analysis of variance. The Journal of Experimental Education, 84, 356-372. doi: 10.1080/00220973.2015.1011594
Comment: Thanks a lot for your very informative answer! I uploaded my data set, so if you want to play around with it... However, from your answer it is clear to me that a MANOVA cannot be the test I want to conduct. If it really just takes half my values than the result is meaningless to me. Will see, what I can do with the data instead. Maybe I stick to the single ANOVAs and compare them individually...
Answer: I think you can treat the problem as a multilevel regression instead of MANOVA. The first step will be to make the data even longer:
dat$ID <- 1:nrow(dat)
dat.l <- tidyr::gather(dat, measure, value, rugosity:ret)
dat.l <- na.omit(dat.l)
dat.l <- dat.l[order(dat.l$ID), ]
head(dat.l)
# # A tibble: 6 x 4
#   tree_species    ID measure   value
#   <fct>        <int> <chr>     <dbl>
# 1 AS               1 rugosity   2.36
# 2 AS               1 bark_mm    8
# 3 AS               1 pH         6.49
# 4 AS               1 whc      295.
# 5 AS               1 ret      119.
# 6 AS               2 rugosity   1.45

Now each row pertains to a specific measurement, we have an identifier for measurement type and tree species.
A reasonable baseline model would be where we allowed the value variable to differ by measure with regards to the mean and variance since the measures appear to be on very different scales:
library(nlme)

fit.0 <- gls(
  value ~ measure, dat.l, # ~ 1 | ID,
  weights = varIdent(form = ~ 1 | measure))

A second step would be to include the tree species as a predictor:
fit.1 <- gls(
  value ~ measure + tree_species, dat.l, # ~ 1 | ID,
  weights = varIdent(form = ~ 1 | measure))

We can then compare both models using standard model comparison techniques:
anova(fit.0, fit.1)
#       Model df      AIC      BIC    logLik   Test  L.Ratio p-value
# fit.0     1 10 1054.608 1083.660 -517.3037
# fit.1     2 14 1035.080 1075.333 -503.5402 1 vs 2 27.52702  <.0001

There is a warning that you can get rid of by using ML instead of REML, something like: anova(update(fit.0, method = "ML"), update(fit.1, method = "ML")). But focusing on the output we have, a likelihood ratio test suggests that the more complicated model has a better fit to the data. And AIC suggests that the more complicated model has better out of sample predictive performance. So including species type may help us better understand/predict the data beyond just understanding the specific measure we are looking at.
An even more complicated model would be permitting the interaction between species and measures:
fit.2 <- gls(
  value ~ tree_species * measure, dat.l, # ~ 1 | ID,
  weights = varIdent(form = ~ 1 | measure))

In this model, we fit 16 additional parameters since there are 5 measures and 5 species. We can again use the anova() to compare all three models. This model will have so many coefficients, it might be difficult to understand but if the comparison methods suggests this is a better model, it appears that the species differ in the ways they are different across the different measures. This is likely to happen since the measures are on very different scales, even if it's the same tree that is consistently different across measures. You will probably have to plot the model or break it up to better understand what is going on.
Comment: The range of the data applies to the heteroskedasticity assumption of regression models, so it is important. Also, the difference between AS and BU will be different on pH and whc simply because whc has a huge range. This affects the interaction term. If the data are not linked, then I would switch from the `lme()` function to `gls()` function and remove the `~ 1 | ID,` part of the syntax.
Comment: Works like a charm! Now I just have to figure out the whole meaning behind this ;)
Comment: @MattBarstead I think the only rationale for GLS is OP's desire for a single statistical test. So we'd need a way to model heteroskedasticity. I agree with you on a simpler model for interpretation. And from a simulation I conducted, I think GLS handles heteroskedasticity well under normal errors. Under non-normal errors, I'd go for OLS with heteroskedasticity-consistent SEs for inference.
Comment: Great answer! Still, I've got some questions. (1) Do I need to use the `ID` variable for my baseline model? Because the measurements are not linked to each other (i.e. `pH` of `ID` 3 could also be linked with `rugosity` of `ID` 4,7 or 9...). Is this a problem?
Comment: (2) Slowly I beginning to grasp what I really want. So what about the interaction between `tree_species` & `measure` (in the last model): if the interaction is significant, wouldn't that mean that my underlying idea that the tree species differ consistently with the parameters is wrong? In that case the tree species could differ but only for single parameters!?
Comment: Note that ID is a variable I created to identify the rows in your data. Are you saying the measurements on the same rows of your original data are not linked? If the interaction is significant, yes you are right, there is no consistent difference. But that is bound to happen in your data. Even if species AS is always the most different, since the measurements are on different scales, the gap can be huge on measure whc and smaller on measure pH, simply because whc has a much greater range than pH.
Comment: Exactly, they are not linked! OK, I thought that the range of the data would have little impact on the test...
Comment: Haha, see https://stats.stackexchange.com/questions/356080/how-to-test-for-difference-in-means-between-5-groups-the-variance-between-the-g/357142#357142 where I explained a `gls()` output in some detail.
Comment: Could I transform my data somehow to avoid the difference in variance? By, say, dividing the values by the respective standard deviation? Then my "Variance Function" output from the gls is quite nice (ranging between 1 - 1.6) for all parameters! ... Maybe I should read the linked answer first ;)
Comment: If inference on the original scales is not of concern, then yes, I might center then standardize each of the original outcome measures. And maybe that helps with clarifying your interactions.
Comment: Clever solution with the `gls` model. Makes me want to do a mini-simulation comparison to see what this buys over and above the simpler ANOVA workflow I propose in more detail in my answer.


Getting the auto summary from a node body

Question: I load an Article node with node_load() and I'd like to get the summary for the Body field. I know that I can access it with $node->body[$node->language][0]['summary'] but unless the user explicitly adds a Summary Body, then this field is empty.
I know that drupal will automatically generate a "trimmed body" if they don't add a Summary Body. How can I access that trimmed body?
EDIT:
I'm not interesting in render()ing the content, I just want the text. My module is generating a json feed for an external source.
Answer: node_view() is appropriate when you need to render whole node or many of it's fields.
But sometimes you have to render the only field you need. It can be done with field_view_field() or field_view_value():
$node = node_load($nid);
// Render array of body field.
$build_body = field_view_field('node', $node, 'body', 'teaser');
// Render it in common way.
echo render($build_body);

The interesting thing is that you can pass your own field formatter settings instead of view mode with the fourth parameter.
Please, read API docs for more info.
Comment: Thanks, I'll check these out! You may have answered another question I had as well.
Answer: A fairly detailed discussion on this topic is on Drupal 7 How to load a teaser programatically.
$teaser = render(node_view(node_load($nid), 'teaser'));
print $teaser['body'][0]['#markup'];

Answer: I wan't summary field always filled then I use something like this function (in custom module):
/**
 * Implements of hook_node_presave().
 */
function mymodule_node_presave($node) {
  // if is summary not empty we can continue
  if (isset($node->body[LANGUAGE_NONE][0]['summary']) && !empty($node->body[LANGUAGE_NONE][0]['summary'])) return;

  // we use module smart_trim to create smart trimmed variant of summary
  $build_body = field_view_field('node', $node, 'body', array(
    'type' => 'smart_trim_format',
    'settings' => array(
      'trim_length' => 8,
      'trim_type' => 'words',
      'trim_suffix' => '...',
      'more_link' => FALSE,
      'more_text' => 'Read more',
      'summary_handler' => 'full',
      'trim_options' => array(
        'text' => TRUE,
      ),
    ),
  ));

  // store created summary
  $node->body[LANGUAGE_NONE][0]['summary'] = $build_body[0]['#markup'];
}

Module smart_trim is used as renderer for summary.
Answer: For anyone interested, here is the most minimal solution. I will use db_select to execute the query rather than node_load.
//first build the query
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title', 'language'));
$query->join('field_data_body', 'body', 'body.entity_type=\'node\' && body.deleted=0 && body.entity_id=n.nid');
$query->addField('body', 'body_value', 'body_value');
$query->addField('body', 'body_summary', 'body_summary');
$query->addField('body', 'body_format', 'body_format');

//fetch a single item as an associative array
$item = $query->execute()->fetchAssoc();

//If an explicit summary has not been provided, we generate it here
if (empty($item['body_summary'])) {
    $summary = check_markup($item['body_value'], $item['body_format'], $item['language']);
    $item['body_summary'] = text_summary($summary, $item['body_format']);
}


C - Array is not working when copying files from text file

Question: For some reason when I copy words from a file to an array, the last element is replacing all the contents from the previous indexes; however, I tested that the array is working fine before going throught the 'file loop' by adding text to index 0 and 1. Please take a look:
FILE *file = fopen("words.txt", "r");
 if (file == NULL){
    printf("...\n");
    return false;
 }

char *words[172805];

//Array test
words[0] = "abc";
words[1] = "bcde";
printf("%s, %s\n", words[0], words[1]);

// Copy words in text document to 'words' array.
while (!feof(file)) {
    if (fgets(arraywordindic, 15, file) != NULL) {
        //Remove \n from word in arraywordindic
        arraywordindic[strcspn(arraywordindic, "\n")] = '\0';
        words[i] = arraywordindic;
        printf("%s\n", words[i]);
        i++;
        if (i == 4) {break;}
    }
}

for (i = 0; i < 4; i++) {
    printf("%s, ", words[i]);
}

fclose(file);

The output of above code is:
abc bcde
A
AA
AAH
AAHED
AAHED, AAHED, AAHED, AAHED,
Do you happen to know why this is happening? Thank you.
Comment: Oh, I got it now, thank you.
Comment: Why `172805`? That's an unusually specific number.
Comment: The number of words I need to store in the array is 172806.
Comment: That's the sort of assumption you don't want to make in C. You're also one short if that's the case. It's better to dynamically allocate more and more memory as necessary using something like `realloc` or a linked-list structure.
Comment: Thank you. Not for this exercise, that is all the amount of words we need. For dynamic arrays I use memory allocation functions instead as you are mentioning.
Comment: If you need *N* elements you need an array defined as size `[N]`, not `N-1`, that is an array like `int x[10]` holds 10 elements numbered 0 through 9.
Answer: It looks like you're setting pointers to exactly the same buffer over and over. You need to copy the strings, or in other words:
words[i] = strdup(arraywordindic);

In C when you say char* x = y this does not copy the contents of that string, it copies the pointer to the string.


Estou tentando criar uma conexão usando localhost porém está dando connection refused

Question: public static String getJsonSystem(String urlString){

    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;
    String retorno = "";

    try{
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        StringBuffer buffer = new StringBuffer();

        while ((line = reader.readLine()) != null){
            buffer.append(line);
        }

        retorno = buffer.toString();

    } catch (Exception e){
        e.printStackTrace();
    }

    return retorno;
}

Aqui como eu chamo a conexão:
String caminho = "http://192.168.0.11/system/pages/login";
HttpConnection conexão = new HttpConnection();
String resp = conexão.getJsonSystem(caminho);

AlertDialog.Builder alerta = new AlertDialog.Builder(this);
alerta.setMessage(resp);
alerta.show();

Comment: Confirme que o servidor que quer conectar está funcionando. Consegue conectar o servidor diretamente no browser usando este URL?
Comment: Verificou se está dando permissão de acesso a internet no seu AndroidManifest? Assim: ``
Comment: Eu testei a url está conectando.
Quanto a permissão ela já está no meu manifest.
Comment: Dente debugar sua aplicação e ver qual linha está parando.
Answer: Se estiver usando o emulador AVD você deve usar 10.0.2.2 para ter acesso ao localhost do seu computador.
Conforme está descrito na documentação oficial.
Para o emulador Genymotion você deve usar 10.0.3.2.
--Edit
Lembre-se de manter o protocolo http no link, no seu caso:

"http://10.0.2.2/system/pages/login"
Comment: Lucas realizei a troca para 10.0.2.2 como disse já que eu uso AVD;
Ele retornou o seguinte erro:
java.io.FileNotFoundException: http://10.0.2.2/system/pages/login
W/System.err:     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
Comment: @Felipe Você deve manter o `http://`, assim: `http://10.0.2.2/system/pages/login`, tenta e me diz se deu certo.
Comment: Mantive o http://10.0.2.2/system/pages/login
Porém quando tentei pegar o retorno da frase em Json não converti para String ai gerava um erro.
Sua resposta foi muito eficaz eu agradeço muito por essa ajuda e me proporcionar aumentar mais meu conhecimento.