Google Maps API: radarSeach with map bounds returning results outside

Question: I have the following code:
google.maps.event.addListener(map, 'idle', function() {
    var request = {
        bounds: map.getBounds(),
        keyword: selected_provider //some value
    };

    service.radarSearch(request, function(results, status) {

        for (var i = 0; i < results.length; i++) {
            var marker = new google.maps.Marker({
                position: results[i].geometry.location,
                map: map
            });
        });

    });

});

in some cases, results' array has some locations that which markers are printed outside the map bounds.
map.getBounds() return this:
oh {Da: mh, va: hh}
Da: A: -23.53883129305287 j: -23.53223111409202
va: A: -46.6811610542145 j: -46.686782964309714

A certain result:
A: -23.536062
F: -46.68732699999998

So, F (the longitude) is not inside the longitudes from southWest and NorthEast.
Anyone have ever seen this?
Answer: As explained here
https://code.google.com/p/gmaps-api-issues/issues/detail?id=8340
"Bounds used to bias results when searching for Places (optional). Both location and radius will be ignored if bounds is set. Results will not be restricted to those inside these bounds; but, results inside it will rank higher."
It doesn't make any sense for me to perform a search with bounds as parameters and the response comes with results outside the bounds. The only thing I think I can do is iterate the results array before showing them, and check if each item is inside bounds.


Why does this always find them to be all true?

Question: public class GameLauncher {

    public static void main(String[] args) {
        GuessGame game = new GuessGame();
        game.startGame();
    }
}

public class Player {
    int number = 0;

    public void guess() {
        number = (int) (Math.random() * 10);
        System.out.println("I'm guessing " + number);
    }
}

public class GuessGame {

    public void startGame() {
        Player p1 = new Player();
        Player p2 = new Player();
        Player p3 = new Player();

        int guessp1 = 0;
        int guessp2 = 0;
        int guessp3 = 0;

        boolean p1isRight = false;
        boolean p2isRight = false;
        boolean p3isRight = false;

        int targetNumber = (int) (Math.random() * 10);
        System.out.println("I'm Thinking of a number between 1 and 10");

        while (true) {
            System.out.println("Number to guess is " + targetNumber);

            p1.guess();
            p2.guess();
            p3.guess();

            guessp1 = p1.number;
            System.out.println("Player one guessed " + guessp1);

            guessp2 = p2.number;
            System.out.println("Player two guessed " + guessp2);

            guessp3 = p3.number;
            System.out.println("Player three guessed " + guessp3);

            if (guessp1 == targetNumber) {

                p1isRight = true;
            }

            if (guessp2 == targetNumber) {
                p2isRight = true;
            }

            if (guessp3 == targetNumber) {
                p3isRight = true;
            }

            if (p1isRight || p2isRight || p3isRight) {
                System.out.println("We have a winner!");
                System.out.println("Was player one correct? "
                + p1isRight);
                System.out.println("Was player two correct? "
                + p2isRight);
                System.out.println("Was player three correct? "
                    + p3isRight);
                } else {
                    System.out.println("None them players were correct man.");
                }

            }
        }
}

Ok I have gone over it so many times but whenever i run it, it display says that all of the players were correct? Even though just before it clearly prints the actual number the players guessed and they are not true.
Answer: You forgot to reset the three isRight variables to false after each go-round of the loop.
So they stay true from previous runs.
Answer: Change
if (guessp1 == targetNumber) {
    p1isRight = true;
}

if (guessp2 == targetNumber) {
    p2isRight = true;
}

if (guessp3 == targetNumber) {
    p3isRight = true;
}

to
p1isRight = guessp1 == targetNumber;
p2isRight = guessp2 == targetNumber;
p3isRight = guessp3 == targetNumber;

The way your current code is, you never overwrite the "true" value when you go through the loop again.
Comment: Thanks! I seriously had it copied straight from this book... can't believe i didn't notice that.


Hosoya Triangle in java

Question: Objective: Individually, create a recursive representation of Hosoya's triangle.
Your task:  Haru Hosoya, a famous mathematician described a triangle (seen below) which is a triangular arrangement of numbers based on the Fibonacci numbers.  Get a height from the user and use an array to store the values on each line.  Print out the appropriate number of levels of Hosoya's triangle using a recursive method.  Do NOT assume that the input will be good.  You should also implement try…catch blocks to catch erroneous input.
Here is the code I have so far:
public class HosoyaTri {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        boolean continueLoop = true;
        int num = s.nextInt();
        do {
            try {
                System.out.println("How many levels?");

                System.out.println(num + " levels");
                continueLoop = false;
            } catch (InputMismatchException im) {
                System.err.println("I said INTEGER, try again");
                s.nextLine();
            } catch (Exception e) {
                System.err.println("What did you do?");
            }
        } while (continueLoop);
        int triangle[][] = new int[num][num];
        for (int i = 0; i < num; i++) {
            for (int j = 0; j < num; j++) {
                triangle[i][j] = 0;
            }
        }
        for (int i = 0; i < num; i++) {
            triangle[i][0] = 1;
        }
        for (int i = 1; i < num; i++) {
            for (int j = 1; j < num; j++) {
                triangle[i][j] = triangle[i - 1][j - 1] * triangle[i - 1][j];
            }
        }
        for (int i = 0; i < num; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(triangle[i][j] + " ");
            }
            System.out.println();
        }
    }

}

Comment: What specific problem are you having? Is your program crashing? Producing incorrect output? Something else?
Comment: I can read in the amount of levels from the user, but cannot actually create the hosoya triangle. If i try to run this program nothing happens but there are no errors
Comment: Looks like homework...
Comment: Something happens on my computer - it prints a triangle, although the values are obviously not correct.. Take care: **Print out the appropriate number of levels of Hosoya's triangle using a recursive method** - There's no recursion yet.
Comment: im trying to figure where the actual recursion fits in
Answer: One problem is that you are reading the number of levels once, before the input loop. You are then prompting for a level and then printing num without giving the user any chance to provide input! You should fix that. You should also be testing against num <= 0.
As far as how to use recursion goes, the entries in Hosoya's triangle can be defined recursively:

H0, 0 = H1, 0 = H1, 1 = H2, 1 = 1
  Hn, j = Hn−1, j + Hn−2, j or
  Hn, j = Hn−1, j−1 + Hn−2, j−2

Another (equivalent) definition is:

Hn, i = Fi+1 × Fn−i+1

where Fn is the nth Fibonacci number, defined recursively as:

F0 = 0
  F1 = 1
  Fn = Fn-1 + Fn-2 (n > 1)

I would suggest using one of these definitions to write a (recursive) static method in your class that calculates the correct value for one entry in the triangle (given n and j as arguments). Then you can eliminate the triangle variable and all the code that initializes it. Simply run your output loop and substitute a call to the recursive method where you now access a specific element of triangle. (If for some reason you need to explicitly build the triangle, simply initialize each element by calling the recursive method. As an aside: there's no need to initialize the elements of triangle to 0; Java does that automatically when the matrix is allocated.)
Comment: I will work on it and get back to you, thank you for your help

Hosoya Triangle in java


jQuery form not submitting when no errors exist

Question: I have an html form and some jQuery that validates the form. If all of the validations pass I would like to submit the form. When I press submit, the errors messages are appearing (if there are errors), however, when there are no error messages, the submit button kind of stalls and I get an error

Unresponsive script error

I get the same results in both firefox and safari.
jQuery (the errors div is where all of the errors appear):
$("#joinForm").on("submit", function (e) {
        e.preventDefault();

        if (!$(':text').val() || !$(':password').val()){

            $('#fillIn').remove();
            $('#errors').append("
Please fill in all fields
");
        }
        else {
            $('#fillIn').remove();
        }

        if ($('#email').val()!= $('#reemail').val()){
            $('#noMatch').remove();
            $('#errors').append("
Emails do not match
");
        }
        else{
            $('#noMatch').remove();
        }

        if ($('#email').val() == $('#reemail').val() && $(':text').val() && $(':password').val()){
            $('#joinForm').submit();
        }
        else{
            $('#errorModal').modal('show');
        }

    });

});

HTML:
<form method='POST' action='join_action.php' id='joinForm'>

            Full Name: 	<input type='text' name='name'></input>

            Email: 	<input type='text' name='email' id='email'></input>

            Re-type Email: 	<input type='text' name='reemail' id='reemail'></input>

            New Password: 	<input type='password' name='password'></input>

            <input type='submit' value='Sign Up' name='signup' id='signup'>

</form>

Comment: It would be simplier to use `$('#signup').on('click'.....` and then call that submit on form
Comment: @arma but if the user has JS turned off i need the form to still submit
Comment: Well if no javascript it will still run native submit since you have that in your form. If you want your current example to work move `e.preventDefault();` to the end. After that modal call.
Comment: check my answer.. it may give you a clear view...
Answer: The e.preventDefault(); prevents the form from submission, and then you called submit() manually, this will fire another submit event, thus you got an infinite loop.
To fix it, call preventDefault only when the form is invalid.
$("#joinForm").on("submit", function (e) {
        var isValid = true;

        if (!$(':text').val() || !$(':password').val()){
            isValid = false;
            $('#fillIn').remove();
            $('#errors').append("
Please fill in all fields
");
        }
        else {
            $('#fillIn').remove();
        }

        if ($('#email').val()!= $('#reemail').val()){
            isValid = false;
            $('#noMatch').remove();
            $('#errors').append("
Emails do not match
");
        }
        else{
            $('#noMatch').remove();
        }

        if (isValid && $('#email').val() == $('#reemail').val() && $(':text').val() && $(':password').val()){
           // pass
        }
        else{
            $('#errorModal').modal('show');
            e.preventDefault();
        }

    });

});

Comment: thanks. how do i fix this?  i need preventDefault to stop form submission immediatly
Comment: where exactly should i place preventDefault?
Comment: i am still unsure where it goes. after the else statment? after the 2nd to last `});`?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/6437/discussion-between-qiao-and-user802370)
Answer: Switch your last if statement to this:
    if (!($('#email').val() == $('#reemail').val() && $(':text').val() && $(':password').val())){
        $('#errorModal').modal('show');
        e.preventDefault();
    }

Also remove the e.preventDefault() from the top of your code.
This just changes the logic to say "If we have errors, show the modal and stop the submit. Otherwise, carry on submitting"
Comment: how will this work?  the modal shows when there are errors. this if statement makes sure there are no errors
Comment: I wrapped your whole if statement in a !() to just give the opposite of whatever you were originally looking for. If it's not working, you'll need to modify the if statement to be whatever means "there are errors"
Answer: you should use e.preventDefault(); only when there is an error. the esiest way to do is, declare a flag and set it to true when there is an error and do something like ,
$("#joinForm").on("submit", function (e) {
   var isError = false; // set the flag to false initially

 // do whatever you want.

  if(error conditions)
   isError = true;  /// do this wherever you are expecting error

  // do something else

  if(isError)
      e.preventDefault();
});

Answer: try this:
$('#joinForm').submit(function(){

    if (!$(':text').val() || !$(':password').val()){

        $('#fillIn').remove();
        $('#errors').append("
Please fill in all fields
");
    }
    else {
        $('#fillIn').remove();
    }

    if ($('#email').val()!= $('#reemail').val()){
        $('#noMatch').remove();
        $('#errors').append("
Emails do not match
");
    }
    else{
        $('#noMatch').remove();
    }

    if ($('#email').val() == $('#reemail').val() && $(':text').val() && $(':password').val()){
        $('#joinForm').submit();
    }
    else{
        $('#errorModal').modal('show');
    }

    return false;
});

SEE in the end:

return false;

Bye!
Answer: Working code on 1.7.1 jQuery:
    $(function() {
        $("#joinForm").on("submit", function () {
            var validForm = true;
            if (!$(':text').val() || !$(':password').val()){

                $('#fillIn').remove();
                $('#errors').append("
Please fill in all fields
");
                validForm = false;
            }
            else {
                $('#fillIn').remove();
            }

            if ($('#email').val()!= $('#reemail').val()){
                $('#noMatch').remove();
                $('#errors').append("
Emails do not match
");
                validForm = false;
            }
            else{
                $('#noMatch').remove();
            }

            if (validForm){
                $(this).submit();
            }
            else{
                $('#errorModal').modal('show');
            }
        return false;
    });
  });

Comment: What version of jquery you are using? it works for me on 1.7.1
Comment: i still got the error.  im using 1.7.1 as well.  maybe there is another problem with my code?
Comment: If you look in jsfiddle example i posted there's all your code and it's working, with minor tweak.


Weyl's asympotic law for eigenvalue : $\lim_{\lambda \to \infty} \frac{M(\lambda)}{\lambda}=\sum_p \frac{A(D_p)}{4 \pi}$

Question: In the book Strauss W.A. Partial differential equations - An introduction (Wiley, $2008$, $1$nd Ed.) page $310 - 311$, it is probably a silly question, but is there anyone could give me a hint how to obtain $\lim_{\lambda \to \infty} \frac{M(\lambda)}{\lambda}=\sum_p \frac{A(D_p)}{4 \pi}$? I am stocked on the problem for a while and I don't know how to solve it.
Edit : I am able to know why $\lim_{\lambda \to \infty} \frac{M(\lambda)}{\lambda}= \frac{A(\text{rectangle})}{4 \pi}$ (example on the rectangle page $307$), but when we let $\lambda$ in an arbitrary planar domain, I dont know why $\lim_{\lambda \to \infty} \frac{M(\lambda)}{\lambda}=\sum_p \frac{A(D_p)}{4 \pi}$ become true.

Proof : Let $D$ be the union of a finite number of rectangle $D = D_1 \cup D_2 \cup \cdots $ in the plane. Each particular $\mu_n$
  corresponds to one of these rectangles, say $D_p$ (where $p$ depends
  on $n$). Let $A(D_p)$ denote the area of $D_p$. Let $M(\lambda)$ be
  the enumeration function for the sequence $\mu_1, \mu_2, \cdots$
  define above $$M(\lambda) \equiv \text{the number of } \mu_1, \mu_2,
 \cdots \text{that do not exceed } \lambda.$$
Then, adding up the integer lattice points which are located within
  $D$, we get $$\text{(1)} \lim_{\lambda \to \infty}
 \frac{M(\lambda)}{\lambda}=\sum_p \frac{A(D_p)}{4 \pi}$$ as for the
  case of a single rectangle. Since $M(\mu_n)=n$, the reciprocal of
  $(1)$ take the form $$\lim_{n \to \infty} \frac{\mu_n}{n}=\sum_p
 \frac{4 \pi}{A(D)}.$$ By the theorem $5$ it follows that $$\lim_{n \to
 \infty} \frac{\lambda_n}{n}=\sum_p \frac{4 \pi}{A(D)}.$$

Clarification : For the whole domain $D$, we regard the eigenvalues $\lambda_n$. When we regard the domain as $D = D_1 \cup D_2 \cup \cdots$, we know that each $D_i$ has its own set of eigenvalues. Therefore, we combine all the Dirichlet eigenvalues of all of the subdomains $D_1, D_2, \cdots$ into a single increasing sequence $\mu_1 \leq \mu_2 \leq \cdots$.
Comment: come on ... I'm not insulting you...  and why don't you try understanding the exercice so that you can write it here directly without copying the book ?
Comment: What have you tried and where are you stuck? It looks like it is explained in the text. Could you clarify?
Comment: Check out section 2.2.3 of this: http://www.math.harvard.edu/~canzani/math253/Lecture3.pdf
Comment: Hmmm... You are "J. Doe", the user who got kicked out of MSE a few days ago. Be careful this time, stop violating MSE rules. In particular, stop linking to pirated material.
Comment: @SpinningAtInfinity: Don't introduce links to illegal copies of copyrighted books in your posts, anymore; if the copyright owners find out, they could sue MSE and nobody wants this, right?
Comment: @AlexM. lol who the hell did reproach that there are links to pirated books ? every student in mathematics does that... that's just necessary for studying
Comment: @user1952009: Looking at your comments above, it seems that you have engaged in a conversation half of which got now deleted. Why don't you also delete them, because left alone they don't make any sense now, anymore?
Comment: @AlexM. : who cares ? anyway his question doesn't make any sense to me (I guess there are other implicit facts in his book, about those lattice points, that he didn't copy)
Comment: come on, you don't understand the question yourself, since you copied the book without changing any character
Comment: understanding the question yourself...
Comment: since my 1st comment, I'm saying that your question doesn't mean anything to me, that if we suppose $M(\lambda)/\lambda$ means something, then the rest becomes illogical, same for $\sum_p A(D_p)$ (and there are those "lattice points....")
Comment: @user1952009 I've edited the question, I don't know if it could help you.
Comment: @SpinningAtInfinity: Could you make the question self contained? What is $\mu_n$?
Comment: Just define everything: $\mu_n$ is not defined.
Comment: @AlexR. Is it better or you think there exists other things could be improved?
Answer: Denote by $N_{D_p}(\lambda)$ the number of eigenvalues for the Dirichlet Laplacian on the rectangle $D_p$ that are less than $\lambda$.
Then, and this is what you seem to be missing, since the sequence $\mu_1\leq\mu_2\leq\cdots$ enumerate all eigenvalues on the different rectangles, the quantity $M(\lambda)$ that you define in the question is just the sum of the numbers of eigenvalues less than $\lambda$ for each rectangle, i.e
$$
M(\lambda)=\sum_p N_{D_p}(\lambda).
$$
Once you see this, then the rest follows easily,
$$
\lim_{\lambda\to+\infty}\frac{M(\lambda)}{\lambda}=\lim_{\lambda\to+\infty}\sum_p\frac{N_{D_p}(\lambda)}{\lambda}=\sum_p\lim_{\lambda\to+\infty}\frac{N_{D_p}(\lambda)}{\lambda}=\sum_p\frac{A(D_p)}{4\pi}=\frac{A(D)}{4\pi}.
$$


(cmd) Como descompactar arquivos de um .zip pelo cmd do Windows

Question: Preciso de ajuda para descompactar arquivos .mdf e .ldf que fica em um único arquivo .zip, preciso fazer isso pelo cmd do Windows.
Comment: Se você usar o 7zip esse vídeo pode te ajudar https://www.youtube.com/watch?v=XLMJgnVKkFE.

O cara manda você baixar o arquivo desse link (http://www.7-zip.org/) e retirar o executável e a **.dll** para que funcione pelo CMD.
Comment: Boa noite, tem como fazer via bat híbrido c VBS, tens interesse na solução?  Basicamente eh um bat q gera um VBS para executar a descompactaçäo do arquivo.
Comment: Sim, eu tenho interesse
Answer: Acredito que você só possa extrair um arquivo dessa forma, pelo CMD, se tiver algum programa que faça isso.
No caso do WinRAR, por exemplo, você pode executar esse comando no seu CMD, para descompactar o arquivo e mandar para o local desejado para extração:
C:\Program Files\WinRAR>winrar x C:\temp\seu_arquivo.zip C:\seu_caminho\

Answer:

Update adicionado suporte para passagem argumento [%~1] argumento [%~2]

Un_Zipper.cmd %~1         %~2
Un_Zipper.cmd Arquivo.Zip Dive+\Pasta-DestinoX para descompactar Arquivo.Zip

Uso com "parâmetro/argumento" para apontar a pasta de destino para descompactação
 Un_Zipper.cmd "arquivo.zip" "c:\Pasta_de_destino"

Se o %~2 não for informado, ele descompacta na pasta
   "%temp%\Nome_do_Zip_Sem_Extensão"
Acredito que seja de boa pra vc editar de maneira que possa manusear os arquivos/pastas para seus respectivos destinos pós descompactação...

Un_Zipper.cmd

@echo off & setlocal enabledelayedexpansion & title

color 9F & cls & cd /d "%~dp0" & mode 60,7 & set "_pping=pathping 127.1 -q 1 -p 100" & title <nul

if /i ".%~1/"=="./" set "_msg_err_= Use: %~nx0 Arquivo.Zip "c:\Pasta-destino" # Arquivo.Zip nao Informado ou Invalido " && goto :_3rr0_msg_:
if /i not "%~x1"==".zip" set "_msg_err_= Arquivo: %~nx1 Nao eh Valido # Use: %~nx0 Arquivo.Zip "c:\Pasta de destino"" && goto :_3rr0_msg_:
if /i ".%~2/"=="./" (set "_target_dir=%temp%\%~n1") else (set "_target_dir=%~2" & if not exist "%~2\" mkdir "%~2" || goto :_3rr0_msg_:)

if /i "!_msg_err_!./"=="./" set "_vbs_Un_Zipper_=%temp%\Un_Zipper.vbs" & type nul>"!_vbs_Un_Zipper_!"
set "_zip_File_=%~nx1" & set "_Zip_Folder_=!_target_dir!" & if /i not "!_Zip_File_:~-3!"=="zip" goto :_3rr0_msg_:
set "_Run_wScript_=start "" /w "%Windir%\System32\wscript.exe" "!_vbs_Un_Zipper_!" //nologo"

(rmdir /q /s "!_Zip_Folder_!" & !_pping! && mkdir "!_Zip_Folder_!" || mkdir "!_Zip_Folder_!") 2>nul >nul
!_pping! >nul && copy /y "%~f1" "!_Zip_Folder_!\!_zip_File_!" >nul & set "_Zip_File_=!_Zip_Folder_!\!_zip_File_!"

set _Zip_File=!_Zip_Folder_!\!_zip_File_!" & dir "!_Zip_Folder_!\*.zip" /b >nul 2>nul || >nul (
set _msg_err_= ERRO: Nao Encontrado !_zip_File_! " & goto :_3rr0_msg_:)

call :_write_vbs_: & !_pping! >nul & echo/ & echo/ & echo/  Descompactando: %~nx1... & !_Run_wScript_!
if "!%errorlevel%!" == "!0!" goto :eof || set "_msg_err_=Erro: Verique !_Zip_Folder_!\%~nx1 " & goto :_3rr0_msg_:

:_write_vbs_:

>"!_vbs_Un_Zipper_!"^
   (
     echo/ ZipFile = "!_zip_File_!" : ExtractTo = "!_Zip_Folder_!\" : Set ObjShell = CreateObject^("Shell.Application"^)
     echo/ Set FilesInZip=ObjShell.NameSpace^(ZipFile^).items: Set FSO = CreateObject^("Scripting.FileSystemObject"^)
     echo/ ObjShell.NameSpace^(ExtractTo^).CopyHere^(FilesInZip^): Set FSO = Nothing: Set ObjShell = Nothing
   ) && exit /b || set "_msg_err_=Erro: Verifique: "!_Zip_File_!"

:_3rr0_msg_:

if "/!_msg_err_!" == "/" set "_msg_err_= Pasta informada de destino eh invalida^!!" & mode 099,007
color F4 & cls & echo/ & echo/ ERRO^^!! & for /f %%a in ('echo prompt $h ^| cmd')do set "_bs=%%a"
for /f delims^=^ eol^= %%a in ('"(cmd /u /c echo=!_msg_err_!) |find /v """')do !_pping! >nul & set/p "=-!_bs!%%a"<nul
!_pping! >nul & set /p "= ^! %_bs%"%_bs% <nul & timeout /t 5 >nul & echo/ & color 0a & exit /b

Código VBS sem os scaping:

ZipFile = "!_zip_File_!"
ExtractTo = "!_Zip_Folder_!\"
Set ObjShell = CreateObject("Shell.Application")
Set FilesInZip=ObjShell.NameSpace(ZipFile).items
Set FSO = CreateObject("Scripting.FileSystemObject")
ObjShell.NameSpace(ExtractTo).CopyHere(FilesInZip)
Set FSO = Nothing: Set ObjShell = Nothing

Comment: Que top! Ficou muito bom sua dica e o código. Desculpa minha ignorância referente o uso do bat, nuca fiz um arquivo `.bat`. Devo por o nome do arquivo `.zip` na linha do código `echo/ ZipFile = "!_zip_File_!"` substituindo pelo nome do meu arquivo sem o `.zip`? Onde eu aponto a caminho do meu arquivo zip?
Comment: Abre o cmd.exe e em seguida chame o Un_Zipper.cmd se não passar nenhum nome de arquivo zip. Você vai receber uma mensagem de ***ERRO*** simulando uma digitação, e contendo informações (pouca).
Comment: Deu certo exatamente como você mencionou! Muito Obrigado!
Comment: Entendi, obrigado!
Comment: @RonisonMatos pode ser passado via commando ou arrasta e solta. Un_Zipper.CMD arquivo.zip com o caminho entre aspas quando tiver espaço no nome do arquivo/pasta.


data-ng-click not responding

Question: This one stumps me..
I have a hyperlink that uses ng-click on a page that loads multiple custom directives, plus other code. I set up the hyperlink but it will not respond.
As a test on another page that calls a custom directive and it failed to respond.
I checked console and had zero errors..
This should work no problem. I've included just the call and the last directive element on the page.

Numbers denote the suggested steps to create a Career Path

....

  ....

                <user-security-questions userId="vm.userId"></user-security-questions>

$scope.showDetails = function(){
            //function showDetails() {
                var modal = $uibModal.open({
                    templateUrl: '/app/templates/modals/showDetails.html',
                    controller: 'showDetailsModalController as vm',
                    size: 'sm',
                    animation: true,
                    windowClass: 'pull-top',
                    windowTopClass: 'slide-from-top',
                    resolve: {

                    }
                });
                modal.result.then(function (result) {
                }, function () {

                });
            }

Everything else works, all the hyper links and directives.. using $scope instead of vm for this function was a last attempt to see what went wrong.
Thanks in advance
Answer: Are you saying that the showDetails function is not called?
If yes, try using :

I removed the "$scope" from the ng-click. Hope that helps
Comment: yah it did... was using:   var vm = this, vm.showDetails = showDetails; in the controller and  ng-click="vm.showDetails()" on the page but it would never fire. once i used $scope.showDetails = function() {.....} and removed $scope from the call it worked.... still not sure why vm.showDetails() didnt...if anyone can enlighten me on this i'd appreciate it. Thanks again Tilak
Comment: If the showDetails is inside a controller and you use vm.showDetails it wont fire. Remember controller is also a function. If you want to call functions inside a controller from outside you need to add them to scope.

data-ng-click not responding


Executing a method of a custom entity after all instances have been built

Question: I'm putting together a private message module. Conversations threads are a custom entity within the module. A thread can potentially appear twice on a page - once in the 'inbox' (a block), and once as the main content of the page. I'm wrapping the rendered threads with a div that I'm attaching in an override of EntityViewBUilder::view(). If the user has not viewed the thread, I'm adding a class of 'unread-thread' to the div wrapper.
Where I'm running into a problem, is finding a place to mark the thread as 'read'. If I do it at the end of EntityViewBuilder::view(), then the class is only applied to the first instance of the thread on the page, since it's already been marked read by the time it comes to the next instance of the thread on the page. I want the class to be part of the wrapper on all instances of the thread on the page.
So I need to find somewhere to mark a thread as read, but only after all instances on the page have passed through EntityViewBuilder::view(). I'm thinking a post-render hook may be good, but I'm not finding one. Does anyone have any suggestions?
Answer: You can use an event for this, a RESPONSE event with a low priority or a TERMINATE event. See for example UserRequestSubscriber::onKernelTerminate:
/**
   * Updates the current user's last access time.
   *
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
   *   The event to process.
   */
  public function onKernelTerminate(PostResponseEvent $event) {
    if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
      // Do that no more than once per 180 seconds.
      /** @var \Drupal\user\UserStorageInterface $storage */
      $storage = $this->entityManager->getStorage('user');
      $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME);
    }
  }

Comment: Thanks for your help - I got it working. Posting my solution below.
Comment: Thanks!  I've actually been working on that method right now! Glad to see I'm on the right track.
Comment: I'm having troubles figuring out how to pass an argument that can be used in the event subscriber. In the above example, $this->entityManager and $this->account are both services, so they are declared in the services.yml file. However, I need to pass an argument that is not a service, and is dynamic. I tried extending the FinishRequestEvent and dispatching my extension, but that throws an error. Any ideas how to do this?
Comment: First I would try to use the request `$event->getrequest()` and response `$event->getresponse()` for dynamic content. Or you can define a custom service to set and get dynamic arguments and inject this in the event subscriber class.
Answer: Here is my final solution. I've commented the code to track what is happening. Basically the steps are:
1) Register a handler to be executed on page request
2) In that handler, retrieve the data necessary to perform the action that needs to happen
3) Execute the action
namespace Drupal\private_message\Event;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\private_message\Entity\PrivateMessageThread;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;

class PrivateMessageEventSubscriber implements EventSubscriberInterface {

  /**
   * The current user
   *
   * @var \Drupal\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Construct a PrivateMessageEventSubscriber object
   *
   * @param \Drupal\Session\AccountProxyInterface $currentUser
   *   The current user
   */
  public function __construct(AccountProxyInterface $currentUser) {
    $this->currentUser = $currentUser;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Register an event listener for when the request finishes
    $events[KernelEvents::FINISH_REQUEST][] = ['onKernelTerminate'];

    return $events;
  }

  /**
   * Register the thread access for the user. This is called on the end
   * of the page request
   *
   * @param \Symfony\Component\HttpKernel\Event\FinishRequestEvent $event
   */
  public function onKernelTerminate(FinishRequestEvent $event) {
    // Retrieve the thread ID for the current page
    $private_message_thread_id = $event->getRequest()->get('private_message_thread_id');
    if ($private_message_thread_id) {
      // Load the thread
      $private_message_thread = PrivateMessageThread::load($private_message_thread_id);
      if ($private_message_thread) {
        // Perform the action at the end of the page load
        $private_message_thread->updateLastAccessTime();
      }
    }
  }
}


Xcode 4 restore file from earlier commit

Question: I have my project on a git repository and so far I'm not finding it terribly useful. I've used git before and think it's great, but this time I'm using a local repo. I figured that there would be some way of restoring files to a previous commit, or even the entire project but I can't find this option?
Is there a way of doing this? Or do I have to create a branch in advance. Because that seems like you have to know in advance that something us going to go wrong.
Also I can't find an option to discard all local changes across my project, effectively reverting to my last commit.
Answer:
I can't find an option to discard all local changes across my project, effectively reverting to my last commit

git reset --hard HEAD

See git reset: that will reset the working tree and the index to what HEAD is currently referring to.
See also the Git book "Undoing in Git - Reset, Checkout and Revert"
For the first part, see git checkout, but beware of detached HEAD.
Comment: @Jonathan: right, I am more a console guy ;) Tower is nice also (http://www.git-tower.com/)
Comment: the consoles great and tower is pretty awesome, but Tower costs quite a bit (compared to the terminal, free obviously, and xcode $5 for IDE as well). I was just hoping that there would be a convenient button in xcode.
Comment: @Jonathan: I understand and this is perfectly legitimate request. Other Git commands aren't yet fully integrated (as illustrated by this SO question http://stackoverflow.com/questions/5302367/xcode-4-git-integration). So in the meantime... http://stackoverflow.com/questions/456403/can-git-be-integrated-with-xcode/944636#944636 ;) `DTerm` can be a workaround, without having to leave `XCode`.
Answer: A bit late to this party.
If you can't hack the command line option (it is the best option IMHO) you could try using github:mac to revert / commit / stage code in conjunction with xcode.
It is a very nice and easy to use UI on top of git and it's FREE!!
Don't worry you're not required to push your repo's to github as it will naturally manage local repositories without any fuss.
I regularly use it to rollback projects. Care must be taken when doing this however.
Try not to place 'project.xcworkspace' under revision control. Shutdown Xcode before reverting & discard or stash uncommitted changes.
Comment: How do you stash in github:mac?
Comment: stashing happens automatically when you create branches in github:mac. see "why did my changes disappear' http://mac.github.com/help.html
Answer: I'm currently in the same boat. It looks like Xcode4 wants us to use the snapshot feature. That has the restore option we want, provided you hit the Create Snapshot when you did your commit. It's conveniently located right under Version Control in the File drop down. The Create Snapshot uses the  control + command + s shortcut, which is pretty handy seeing as how I hit command + s for the save hot key often. Or even better yet. Automatically
Comment: I tried creating and restoring from snapshots, but on clicking restore it asked me to open a folder that I wanted to restore, when I just wanted to simply restore the project, selecting a folder just created the correct directory tree but without any restored files.
Comment: I just found this (http://stackoverflow.com/questions/5302367/xcode-4-git-integration/5364900#5364900) and tried it out via terminal and then loaded my project in Xcode, and it was in the state it should of been at for the commit I selected. It's not 100% from inside Xcode, but it's a way to recover to a previous state with minimal headache.
Comment: xcode 4's version control is a total mess. You can not use it for serious source control b/c it's missing alot of critical features.  Avoid it completely.


How to summarize GAM model result from multiple imputation data in R

Question: I am very new to R and not very experienced in statistics. I have this general question regarding applying Generalized Additive Models (GAM) in multiple imputation dataset.
I used R package mice for multiple imputation and mgcv for GAM. But I have no idea how to combine the results from each imputed data set.
Does anyone have any good idea about this?
Thanks a lot!
Comment: I have never used mice but I used a lot the GAM package. If you decide to move to the gam package maybe I can help you
Comment: Yea, I'm actually trying both. I'm all ears!
Comment: Can you write in the question what did you try with the package GAM. Maybe I can help you
Comment: e.g. This is the model I wanna run fit=gam(y ~ s(x,5),data=df). I have imputed 5 data sets. I wanna run the same model in each of the data set. say the imputed dataset is stored in dat.imp. Then the code would be, with(dat.imp, gam(y~s(x,5)). When it returns, it shows you the results from each dataset. But I need to think of a way to combine them.
Comment: sorry no clear to me. you have different datasets df1,df2 ,.. ?  in each dataset you have an input value x and an ouput value y?
Comment: yes. It can be considered as I have 5 datasets- each dataset is filled with different imputed missing value. In general, these 5 datasets shouldn't be drastically different from each other. Then I wanna perform the GAM model in each dataset. After that, I wanna pool the results from these 5 datasets.
Comment: I am not really sure of how you can do that. Maybe you can just try to do plot the different obtained gam and see if there are significant differences
Comment: Yea.. it's straight forward for linear regression but not for GAM.. =/
Comment: in the end if you are using s(x,5) you should have only few coefficients to compare. you are working with only one input variables you can also just do a graphical comparison
Answer: First, GAM's are basically a combination of GLMs, splines, and ridge regression (loosely speaking).  You might be well advised to work on your understanding of these three things before attempting to work with their combination.
Second, I've done multiple imputation with GAMs, but not with mice.
In general, you're interested in fitting a model:
$$
y = f(\mathbf{X}) + \epsilon
$$
(in the gaussian, identity-linked case).  $\mathbf{X}$ has holes in it -- missing data.  Without going into the detail about how multiple imputation works (Gelman and Hill have a very good and less-technical chapter explaining missing data imputation), what it does is create many different $\mathbf{X}$'s, call them $\mathbf{X}_m$ where $m$ indexes imputed datasets from 1 to the number of imputations, with the missing values filled in with plausible guesses about what the missing values might be -- based on correlations in your dataset.  You then fit your model
$$
y = f(\mathbf{X}_m) + \epsilon
$$
to each of those $m$ partially-imputed datasets.  Since you're fitting $m$ models to $m$ different datasets, you're going to get $m$ different vectors of regression coefficients.  These are combined according to "Rubin's Rules" (after the statistician who invented MI).  Basically you average the coefficients;
$$\hat\beta = \frac{1}{M}\displaystyle\sum_{m=1}^M \hat\beta_m$$
The variance-covariance matrix $\hat V_\beta$ of the estimated parameters is calculated by first averaging variance-covariance matrices, and then adding a correction to account for variation between imputation models:
\begin{equation}
\hat V_{\hat\beta} = W + \left(1 + \frac{1}{M} \right)B
\end{equation}
where $W = \frac{1}{M}\displaystyle\sum_{m=1}^M \widehat{VCV}_m$, $\widehat{VCV}$ is the estimated variance-covariance matrix of the estimated parameters, and $B = \frac{1}{M-1}\displaystyle\sum_{m=1}^M \left(\hat\beta_m - \hat{\bar\beta}\right)\left(\hat\beta_m - \hat{\bar\beta}\right)^T$.  This procedure inflates the standard errors on coefficients about which the imputation model is relatively less certain, either due to a lot of missing data, or due to a poorly-informative imputation model.
You can then use the vector of coefficients and the VCV as if they were gotten from a single complete-case model.
OP's question in a comment makes me realize that the below isn't quite right!  Read EDIT2 below to see why
So what is different about doing this with a GAM?  Only a couple of things.  Your variables represented by smooth functions are associated with a number of coefficients (mgcv's default is 10).  During estimation they are subject to ridge penalties, which smooths the estimated function.  But otherwise they can be slotted into Rubin's rules just like the parametric coefficients.  Each of the different $m$ models will have different estimated smoothing parameters, as they are estimated from the data.  I don't think there is a problem with this, though I'd be interested to hear if someone has another perspective.  You do want to take care that you pre-specify the location of the knots of each spline so that they are uniform across the $m$ models -- otherwise your coefficients won't be comparable, and combining them won't be appropriate.
Once you have calculated the combined coefficients and VCV, you can simply stuff them into a GAM object (one of your $m$ models).  Functions that summarize data and make plots draw from those two objects, and will thereby use your imputation estimates rather than those from the $m$th model.  There is code online illustrating the whole process from this paper.
EDIT I just saw the comment about how you've got your models fitted to your imputed datasets already.  If you can coerce those into a list object with the 5 GAM models, then you can run something like the following to combine them:
bhat=results[[1]]$coeff
    for (i in 2:reps){
     bhat=bhat+results[[i]]$coeff
    }
bhat = bhat/reps

W=results[[1]]$Vp
    for (i in 2:reps){
     W = W+results[[i]]$Vp
     }
    W = W/reps
    B= (results[[1]]$coeff-bhat) %*% t(results[[1]]$coeff-bhat)
    for (i in 2:reps){
     B = B+(results[[i]]$coeff-bhat) %*% t(results[[i]]$coeff-bhat)
    }
B=B/(reps-1)

Vb = W+(1+1/reps)*B

dfr=results[[1]]$df.residual
    for (i in 2:reps){
     dfr=dfr+results[[i]]$df.residual
    }
dfr = dfr/reps

MI = results[[1]]

MI$coefficients=bhat
    MI$Vp = Vb
MI$df.residual = dfr

EDIT2 OP's question in a comment about p-values makes me realize that the above isn't quite right.  It should get you appropriate coefficient and VCV estimates.  But p-values are based on a reduced-rank Wald statistic that relies on the model matrix for its calculation.  Obviously the model matrix will differ between different imputations.  So if you take a single one of many gam objects (which will all have their own model frames) and stuff the VCV and coefficient vectors into it, you won't get the same result as you would if you chose a different one of your models fit to a different imputed dataset.  I'm not sure how Rubin's Rules would be generalized to combine imputations here!  Maybe a short-term hack would be to also average the model R matrices from each model?  This should be about as valid as averaging the effective degrees of freedom (which may also be a hack).
Comment: Good question!  I was about to post that you can simply rely on what `summary.gam` gives you after you replace the adjusted coefficient vector and VCV into the gam object.  That is what I have done previously.  But as I think about it, it's not right!  The details of p-values for smooth functions are in Simon Wood's 2013 Biometrika paper.  The reduced-rank wald statistic that `summary.gam` calculates needs the model R matrix (from a QR decomposition of the X matrix), as well as the VCV, the beta vector, and the residual degrees of freedom.  Obviously the X matrix will vary between imputations.
Comment: This is very helpful information! Thank you very much!
Comment: I have another question. In this case, how do you calculate the p-value for the smoothed term?
Answer: See https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/missing.data.html
Or enter help(mgcv::missing.data) in an R session.  An approach that can be effective, with sample code on the help page, is then to
   substitute a simple random effects model in which the by variable
   mechanism is used to set s(x) to zero for any missing x, while a
   Gaussian random effect is then substituted for the 'missing' s(x).

Factors are required, one for each variable that has missing values, for use as missing value indicators, in each case with as many levels as there are missing values.  The NAs are replaced in each case, by the mean for the relevant variable.


Is there an algebraic function $f:\mathbb{C}\rightarrow\mathbb{H}$?

Question: You can get a complex number when (for example) taking the root of a (negative) real number, but can you also do the same for quaternions? So my question is:
Is there an algebraic function $f$ that maps $\mathbb{C}$ (complex numbers) to $\mathbb{H}$ (quaternions)?
EDIT:
$f$ should map a number $v\in\mathbb{C}$ possibly $\in\mathbb{R}$ to a number $w\in\mathbb{H},\not\in\mathbb{C}$.
Also $f$ should not be trivial meaning the function shouldn't "contain" quaternions, example: $f(x)=x+a,a\in\mathbb{H}$ would be trivial. (Is there a better way to say what I mean?)
Comment: Maybe the answer here is that there's no "natural" map on $\Bbb C$ that produces quaternions since $\Bbb C$ is algebraically closed
Comment: These kinds of embeddings of $\Bbb C$ in $\Bbb H$ are missing a feature in the OP's post: in the example given, we're "forced" to leave $\Bbb R$ by our desire to take square roots of negatives. But since $\Bbb C$ is algebraically closed, we'll need a different sort of trick to be forced to leave $\Bbb C$. I'm wondering if we can force our exit by asking for non-commutativity; perhaps seeking nonzero solutions to $iz = -zi$.
Comment: The quaternions $\mathbb{H}$ can be viewed as a strict non-commutative extension of $\mathbb{C}$.  Indeed one may take $f(a+bi) = a+bi$, where $a$ is the real part and $b$ the imaginary part of any complex number.  But you could send $i$ to $j$ or to $k$ in the quaternions with the same effect.
Comment: I mean function $f$ "sends" $a+bi$ in the complex numbers to $a+bi$ in the quaternions, in the sense that a function assigns a value in the range to each value in its domain.  "sends" means "maps".  So in the obvious way the complex numbers can be viewed as a subalgebra of the quaternions.
Comment: @pjs36 I indeed saw a different [question](http://math.stackexchange.com/questions/789451/do-there-exist-equations-that-cannot-be-solved-in-mathbbc-but-can-be-solve?rq=1) about an equation having it's solutions in $\mathbb{H}$ due to commutativity.
Comment: Could you explain what you mean with "send", please?
Comment: You could send $a+bi$ to $x(a+bi)x^{-1}$ for any quaternion $x$ (generalizing hardmath's example).
Comment: Thanks, but this seems trivial because $\mathbb{R}\in\mathbb{C}\in\mathbb{H}$ will edit the question to make this more specific.
Comment: It did seem trivial, which is why I bypassed posting an Answer.  I look forward to your clarification of the Question.
Answer: As it turns out this isn't possible the way stated.


Is reverse proxy recommended in production environment?

Question: We have an Angular app and a Back-end web API on .NET core. Both sites should be served over HTTPS. I currently have one Linux server.
Currently I'm planning to host my Angular app on a domain (for example: https:// example.com) in nginx, all API calls are made using same domain with <code>/api</code> endpoint (for example: https:// example.com/api), and from nginx server I'm redirecting to .NET core Kestrel server.
Is this deployment good for a real production environment? If anyone has better ideas, please let me know. Thanks.
PS: obtaining another public IP isn't a problem.
Comment: ip 10.x.x.x - http://exampleangular.com - angular app   ip 11.x.x.x -http://examplewebapi.com . making two public ip and domains and listening. which option is better.
Answer: According to Krestel official documentation is a good practice to use a reverse proxy.
The implementation doc is good and it goes into more details about it:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-5.0
If only one frontend server is powerful enough to maintain your workload I don't see any problem with that.
Answer: It's most of the time a good idea to reverse proxy applications and it's default behaviour in the most setup.
It gives you flexibility, maintainability and security as well.


Notepad++ FTP plugin with Google Compute Engine

Question: I've been using the Google Compute Engine since the day I heard it came out--I've been primarily using a micro instance to hone my HTML/CSS/PHP skills, while I learn them at Codecademy. My problem is that editing the HTML &c files in nano via the terminal can get frustrating, and is definitely slower than using a GUI-based word processor.
When I did coding on Windows, I primarily relied on Notepad++, and I just recently learned about the FTP plugin. I have Notepad++ installed on my computer (Ubuntu 13.10, via PlayOnLinux/WINE) and have had no trouble with it...except with using the FTP plugin to my GCE instance.
I've configured the plugin properly (as far as I can tell):
Hostname -- <mydomain>.com
Connection type -- FTP
Port -- 21
Username -- <myusername>
Password --

...and then on the Authentication tab I have it set to use private key file authentication, and point to the appropriate private key, as well as the passphrase I set for it. (NB: I have set a firewall rule to allow TCP on port 21 to 0.0.0.0)
I get the following in the console when I try to connect:
-> TYPE I
Connecting
-> Quit
Unable to connect
Disconnected

Is there anything I need to do, or is it even possible to set up NPPFTP with GCE this way?
Answer: NPPFTP supports SCP and SFTP. FTP is generally insecure and tricky to configure firewall rules for. Have you tried SCP / SFTP instead?
Make sure that you are using the same SSH key that Google Compute Engine uses. On Mac OSX and other Unices, it is usually located at $HOME/.ssh/google_compute_engine.
Comment: I think it's worth noting that if you've used puttyGen to generate your keys, then you will need to export the key as an OpenSSH Key.


Gerar Input dinâmicamente - html , javascript e Jquery

Question: Amigos, preciso receber um valor numérico e a partir dessa entrada, gerar automaticamente os input.
Por exemplo, digito 5, e o programa gera 5 input para entrada numérico.
O que tenho de código é basicamente, um campo para inserir a entrada, tenho conhecimento somente em c# e Java, por isso a dificuldade com html e javascript e Jquery:
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <title> UpFlow.me </title>

  Adicionar Campos

        <input type="text" name="visor" />

            <input type="button" value="inserir" />

Answer: Para criar elementos com JQuery, você pode utilizar do método append, e para retornar o valor presente no input, você utiliza do método val.
Então no click do botão inserir, pegamos o valor, verificamos o mesmo, pois o input pode estar vazio, caso esteja válido, efetuamos um loop criando campo a campo.
Veja abaixo um exemplo:

$(function() {
  $("#inserir").click( () => {
    let quantidade = $("#quantidade").val();

    if (quantidade) {
      quantidade = parseInt(quantidade);

      for (let i=0; i < quantidade; i++) {
        $("body").append(`<input type="number">`);
      }
    }
  });
});
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <title> UpFlow.me </title>

  Adicionar Campos

        <input id="quantidade" type="text" name="visor" />

        <input id="inserir" type="button" value="inserir" />

Alterando um pouco mais seu HTML, podemos criar uma div ou um form que será onde os campos serão criados, dessa forma nós podemos limpar esse elemento sempre que o botão for clicado, evitando assim a constate soma de inputs:

$(function() {
  $("#inserir").click( () => {
    let quantidade = $("#quantidade").val();
    const campos = $("#campos");

    if (quantidade) {
      quantidade = parseInt(quantidade);
      campos.empty();

      for (let i=0; i < quantidade; i++) {
        campos.append(`<input type="number">`);
      }
    }
  });
});
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <title> UpFlow.me </title>

  Adicionar Campos

        <input id="quantidade" type="text" name="visor" />

        <input id="inserir" type="button" value="inserir" />

Para esse limpeza, utilizamos do método empty.

Para pegar os valores de todos os novos inputs e somar, existem algumas formas, vou colocar como exemplo uma em que os inputs são criados com uma classe específica, assim com JQuery eu busco todos esses inputs por essa classe e somo seus respectivos valores utilizando do método each do JQuery:

$(function() {
  $("#inserir").click( () => {
    let quantidade = $("#quantidade").val();
    const campos = $("#campos");

    if (quantidade) {
      quantidade = parseInt(quantidade);
      campos.empty();

      for (let i=0; i < quantidade; i++) {
        campos.append(`<input class="soma" type="number">`);
      }

      if (quantidade > 0) {
        campos.append(`<input type="button" id="somar" value="somar" onclick="Somar()">`);
      }
    }
  });
});

function Somar() {
  const inputs = $(".soma");
  let total = 0;

  inputs.each( (index, element) => {
    if ($(element).val()) {
      total += parseInt($(element).val());
    }
  });

  console.log(total);
}
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <title> UpFlow.me </title>

  Adicionar Campos

        <input id="quantidade" type="text" name="visor" />

        <input id="inserir" type="button" value="inserir" />

Referências:
https://api.jquery.com/append/
https://api.jquery.com/ready/
https://api.jquery.com/val/
https://api.jquery.com/empty/
https://api.jquery.com/each/
Comment: @galegoz     `const campos = Array.from(document.querySelector('#campos').children);
    const total = campos
        .map(input => Number(input.value))
        .reduce((acc, cur) => cur + acc);`
Comment: Perfeito, no caso para concluir eu precisaria somar as entradas nos novos inputs, por exemplo: temos 3 inputs, entro com o numero em 10 em cada um e retornaria 30.com oque tenho em mente, em c# pensaria em algo como  armazenar os numeros em um array e retornar o resultado, como seria a sintaxe com javascript e jquery?


Views Page Showing Root Title in Window (not views title + root title)

Question: My views page title is set to "The Title" but my window title shows as "Website" rather than "The Title | Website". This is only for my views. Any ideas what would cause this? I have a few other modules installed but not Page Title, that's disabled.
Answer: The title for a view does not show up in window title.   The Window's title is determined by the browser, independent of Drupal. The view title is used as the title before the body of your content in the content display area of the window provided you have configured the view to display the title.
Comment: Ok, thanks for that bit of information, I didn't know this. Do you know of a way to force this to display what I want?


Can a 2/3 training 1/3 test split be unrepresentative?

Question: We often fit a predictive model using 2/3 of the data and assess fit on the remaining 1/3. Can such a split be unusual? Is it best to average over many such splits? I realize that this would produce potentially many models. But, in the related approach of cross validation, such repeated splits are advised. In that case, we fit a final model and use the results of CV as a measure of predictive ability.
Comment: Of course such a split _can_ be unusual. It's just improbable if the data set is large and observations are IID.
Answer: Test set performance is an estimator for the learning algorithm's performance on future data. We'd like the estimate to be as close as possible to the 'true' value (i.e. what we'd see if we had access to the underlying distribution). The error of an estimator can be expressed in terms of its bias and variance. Bias measures the systematic difference between the estimate and the true value, and variance measures the extent to which the estimate fluctuates (across datasets drawn from the underlying distribution). One seeks to reduce the error by reducing the bias and variance, but there's typically a tradeoff between them.
Say we're using simple holdout (e.g. a single training/test set split). As the number of points in the test set shrinks, the variance of the performance estimate increases because it becomes more susceptible to the points that happened to fall in the test set by chance. One could try to compensate for this by increasing the fraction of points allocated to the test set. But, this would shrink the size of the training set, giving a poorer model fit and thus increasing the bias.
Instead, one could perform multiple training/test splits and average the test performance. Different variants of this procedure exist (e.g. k-fold cross validation, monte carlo cross validation, repeated k-fold cross validation, plus related techniques like bootstrap). Averaging over multiple test sets reduces the variance. This gives some wiggle room for allocating a larger fraction of points to the training set on each iteration, reducing the bias. The downside of this approach is that the model must be fit multiple times, increasing the computational load.
Typically, simple holdout is used when the dataset is large--there are enough points that a model can reasonably be fit on the training set and evaluated on the test set, and perhaps too many points for cross validation to be computationally feasible. Otherwise, a technique like cross validation is a better approach.
K-fold cross validation (e.g. 10 fold) or (repeated k-fold cross validation if you have the computational resources) is probably better than repeating a simple 2/3 vs. 1/3 split. You can find articles comparing different variants of cross validation.
Comment: thats really helpful, user20160 "instead, one could perform multiple training/test splits and average the test performance."
Comment: thats what I was thinking but I've never seen this " multiple splits" suggested for test/train only for k-fold CV - maybe everynoe else realises it doesn't need saying as they are smilar comcepts - or I've not looked hard enough - thanks again


How to bulk resize images imported with feeds importer module?

Question: I have a Drupal 7 site on a test machine (Windows 7/Apache/PHP 5.3), with the Commerce and Feeds modules installed, and succeded in importing a CSV of more than 400 products (images included!), which made me really happy.
Now I've got a problem: in the Commerce product settings, the maximum width & height are set to 700px and 400px, respectively. The feed importer didn't resize the product photos, so now I'm stuck with product images that are the original hi-resolution photos (all above 2000x1000 pixels)!
Is there a way to make Drupal automatically re-process all the Commerce product images (call it a bulk resize, or a batch resize...)? Or have I got to reprocess them through Photoshop or something like that, and then re-import the CSV?
I know that probably not many people have faced a similar situation... any hint is appreciated!
Edit
I'm using Views Slideshow with jQuery Galleria, which loads the original images and resizes them via img tag attributes width and height.
That is a reasonable part of the problem, because even if I use Image styles (Configuration>Media>Image styles), Galleria keeps using the original image, which slows down the browser and consumes a lot of RAM.
Answer: If you have access to a command line and ImageMagick, you can run convert from find.
In Unix et al
From Drupal root:
find sites/default/files/products -name '*.jpg' -execdir convert {} -resize 700x400 {}\;
(Note: this assumes all product images are in the "products" directory in sites/default/files. You DO want to make a copy of this directory with cp -r sites/default/files/products sites/default/files/products_backup before running the above in case it does something you don't want it to!)
In Windows:

Download and install findutils.
Download and install ImageMagick
Make sure both are working on the commandline. Type "find" and hit enter. Same with "convert". If neither gives you a "command not found" error, they're installed and working.
Backup your product images directory.
Instead of the above command, try:

find sites\default\files\products -name '*.jpg' -execdir convert '{}' -resize 700x400 '{}' ';'
If find chokes on that path, try using backslashes. Also, make sure it's using the GNU version of find and not some other version (The lender Windows machine I'm working on right now has a find command, don't know if that's standard or something somebody else installed).
Comment: Thanks a lot, It worked like a charm! The last hint was especially useful: `find` seems to be a predefined Windows command so I had to use the full path to the find.exe executable. BTW, on my machine the command ran without quotes. Thanks again!
Comment: Good to hear it worked! GNU Find is a great command, -execdir makes it really powerful for running batch queries on lists of files.
Answer: I think its ok to have the images in high res. So you're able to use them in whatever format and size you need. Have a look at the Imagecache Module. This module allows you to create image styles. For each image you show on your page, you can have different media styles or presets and use them for example in views or in different view modes.
Edit: Built in in Drupal 7. Have a look in Admin -> Image Styles
Comment: My problem, not a negligible problem, is that I'm using Views Slideshow with Galleria, which loads the original image and resizes it via img tag attributes. Anyway I'm updating the question adding this detail.


Find the speed of stream from rowing speeds with and against the stream

Question: Problem
A man rows to a place 48 km distant and come back in 14 hours. He finds that he can row 4 km with the stream in the same time as 3 km against the stream. The rate of the stream is:

(A)  1 km/hr; (B):   1.5 km/hr; (C): 2 km/hr; (D):   2.5 km/hr

Progress
I don't know how to solve these. Anybody can help me with these. Book answer is 1km/hr
Comment: @Shaun I got an answer with the help of satish.I am a new user to these site.next time I will share my own thought while posting the question.
Comment: Please share your thoughts so far. For instance, what do you think a solution might look like? :)
Comment: @Shaun Check out here for boats and stream concept `http://mrunal.org/2012/04/aptitude-boats-and-streams-made-easy.html`
Comment: Since this is homework, we'd prefer it if you provide *your own* thoughts on the problem. This isn't some site where people do your homework *for you*; it's for improving one's mathematical abilities. We would rather help you even more by helping you to do your homework yourself! :)
Answer: Answer:
V = speed of the boat
U = speed of the stream
$(V+U).t =4$
$(V-U)*t = 3$
$\frac{(V+U)}{(V-U)} = \frac{4}{3}$
Solving this you get $V = 7U$
$(V+U)*t_1 = 48$
$(V-U)*t_2 = 48$
$t_1 + t_2 = 14$
$8U*t_1 = 48$
$6U*t_2 = 48$
$\frac{48}{8U} + \frac{48}{6U} = 14$
Solving this we get U = 1
Thanks
Satish
Comment: Thank you for solving these to me.now I am get some clear idea about these.


Image between SVG

Question:

#home {
  height: 100vh;
  background-image: url("http://4.bp.blogspot.com/-yB6Tc3mleuE/T4NkAKeazYI/AAAAAAAACB0/tlichKzIu3Q/s1600/Simple+unique+odd+weird+wallpapers+minimalistic+%2330+battleship+titanic.jpg");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  overflow: hidden;
  padding: 0;
  margin-left: -10px;
}
.background {
  overflow: hidden;
}
#fg {
  fill: pink;
  stroke: #fff;
  stroke-width: 10px;
  stroke-dasharray: 1024px;
  -webkit-animation: dash 2s;
  animation: dash 2s;
}

@keyframes dash {
  from {
    stroke-dashoffset: 1024px;
  }
  to {
    stroke-dashoffset: 0px;
  }
}

@-webkit-keyframes dash {
  from {
    stroke-dashoffset: 1024px;
  }
  to {
    stroke-dashoffset: 0px;
  }
}

#bg {
  fill: white;
  stroke: none;
  transform-origin: 1270px 550px;
  -webkit-animation: bgfill 2s linear 2s forwards;
  animation: bgfill 2s linear 2s forwards;
}

@keyframes bgfill {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(4);
  }
}

@-webkit-keyframes bgfill {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(4);
  }
}

        <svg viewBox="0 0 1376 764">
            <defs>
                <path id="shape" d="M1034.5,770.5a125.59,125.59,0,0,0-17-32c-12.32-16.72-25.68-25.84-33-31-6-4.23-59.88-42.55-100-90-13.64-16.14-20.57-24.48-26-38-15-37.48-3.73-73.65,0-85,8.68-26.45,23-43.26,35-57,19-21.82,33.56-29.9,67-54,33.68-24.27,55.39-39.91,77-60,40.56-37.69,35.94-49.35,81-96,34.18-35.39,51.27-53.08,79-65,7.79-3.35,76-31.44,140,2a142.06,142.06,0,0,1,31,22l7.5,7.5  L 1376,770.5 Z" />
            </defs>
            <use xlink:href="#shape" id="bg" />
            <use xlink:href="#shape" id="fg" />
        </svg>

I can not seem to make the background image visible at all times while remaining the same effect, making the fill transparent gets rid of the animation, I also tried to play around with z-index on various elements but without success, how can I make it so that the background image is visible inside the white line instead of the pink svg?
I also tried applying the same image to the pink SVG as fill and it kind of works, I just can not seem to make the image appear like how it would if it was full screen, it also makes the page a bit slow:
#fg {
  fill: url(#image);
  stroke: #fff;
  stroke-width: 10px;
  stroke-dasharray: 1024px;
  -webkit-animation: dash 2s;
  animation: dash 2s;
}

<pattern id="image" width="1" height="1">
  <image xlink:href="http://4.bp.blogspot.com/-yB6Tc3mleuE/T4NkAKeazYI/AAAAAAAACB0/tlichKzIu3Q/s1600/Simple+unique+odd+weird+wallpapers+minimalistic+%2330+battleship+titanic.jpg"></image>
</pattern>

Answer: You can get rid of the pink with fill-opacity. But you would need to adjust the white "background" as it overlays the background-image.
You might need to change the shape for that.
You could also include the image as a layer in the svg.

#home {
  height: 100vh;
  background-image: url("http://4.bp.blogspot.com/-yB6Tc3mleuE/T4NkAKeazYI/AAAAAAAACB0/tlichKzIu3Q/s1600/Simple+unique+odd+weird+wallpapers+minimalistic+%2330+battleship+titanic.jpg");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  overflow: hidden;
  padding: 0;
  margin-left: -10px;
}
.background {
  overflow: hidden;
}
#fg {
  fill: pink;
  fill-opacity: 0;
  stroke: #fff;
  stroke-width: 10px;
  stroke-dasharray: 1024px;
  -webkit-animation: dash 2s;
  animation: dash 2s;
}

@keyframes dash {
  from {
    stroke-dashoffset: 1024px;
  }
  to {
    stroke-dashoffset: 0px;
  }
}

@-webkit-keyframes dash {
  from {
    stroke-dashoffset: 1024px;
  }
  to {
    stroke-dashoffset: 0px;
  }
}

#bg {
  fill: white;
  opacity: .5;
  stroke: none;
  transform-origin: 1270px 550px;
  -webkit-animation: bgfill 2s linear 2s forwards;
  animation: bgfill 2s linear 2s forwards;
}

@keyframes bgfill {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(4);
  }
}

@-webkit-keyframes bgfill {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(4);
  }
}

        <svg viewBox="0 0 1376 764">
            <defs>
                <path id="shape" d="M1034.5,770.5a125.59,125.59,0,0,0-17-32c-12.32-16.72-25.68-25.84-33-31-6-4.23-59.88-42.55-100-90-13.64-16.14-20.57-24.48-26-38-15-37.48-3.73-73.65,0-85,8.68-26.45,23-43.26,35-57,19-21.82,33.56-29.9,67-54,33.68-24.27,55.39-39.91,77-60,40.56-37.69,35.94-49.35,81-96,34.18-35.39,51.27-53.08,79-65,7.79-3.35,76-31.44,140,2a142.06,142.06,0,0,1,31,22l7.5,7.5  L 1376,770.5 Z" />
            </defs>
            <use xlink:href="#shape" id="bg" />
            <use xlink:href="#shape" id="fg" />
        </svg>

Comment: Here would be a link if you want to try the image inside the svg: https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/SVG_Image_Tag
Comment: I would like to keep the white fill, I edited the code that shows my try on using fill to show the same image but I can not make it so that it only displays the bottom right part of the image
Comment: Where do you want the white fill? outside of the shape? if so, you need to rewrite your shape for your BG
Comment: Yeah outside of the white line, do you know what the shape should look like if I want to achieve it? I have no problems drawing it but I wouldn't know what it should look like
Comment: You could try the shape of the line and then increase the stroke to the left top...

Image between SVG


Javascript how to store predefined function (with arguments)

Question:
Possible Duplicate:
Javascript infamous Loop problem?

I have the following:
function test(a,b,c){
    console.log(a+b+c);
}
for (var i=0; i < array.length; i++){
    steps.push(
        function(){ test(array[i].something, array[i].wow, i);}
    );

I want to store functions with several parameters, and bind them to buttons later when the DOM is loaded
for (var i=0; i<steps.length; i++){
    $('#mydiv li a').eq(i).click(steps[i]);
}

It's not really working since steps[i] contains do(array[i].something, array[i].wow, i); instead of do('bob', 'john', 1) for example
I have tried using the .apply javascript function but it will execute in the loop, instead of storing them
Comment: note the `do` is a reserved javascript name... if you'r using this name in your code, i suggests you to change it to something else.. maybe this is the cause to your bug
Comment: ugly solution would use eval :/
Answer: Closures can help you here. Here's one solution to the first bit of code:
function do(a,b,c){
    console.log(a+b+c);
}
for (var i=0; i < array.length; i++){
    (function (i) {
        steps.push(
            function(){ do(array[i].something, array[i].wow, i);}
        );
    })(i);
}

There's no "block scope" in Javascript, just function scope. With your code, each function you pushed into the steps array had a reference to the last value of i, not the one it had when the function was pushed into steps. Invoking an immediately executing function enables the pushed function to have a value for i that doesn't change, because a closure is being created. And this closure has a value for i that is independent of the loop's value for i, which will be whatever is the last index of array.
Comment: why do you need the i parameter in each closure?
Comment: Because that saves a "permanent" value for `i`, that won't change, even though the loop's value for `i` will. It creates an `i` variable that is only visible and modifiable by the function you're pushing into your `steps` array. The `i` contained in the line `})(i);` is passing the loop's `i` into the function. Inside the function, the `i` referred to there is the one and only parameter of the anonymous function. Make sense?
Comment: See [this Stack Overflow question](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) for more information (on the general subject of JS closures, with references to articles and other content).
Comment: is it test.bind(null, array[i].something, array[i].wow, i);
Comment: You can use `bind`, but there are cross-browswer issues that you have to navigate. `Function.prototype.bind` isn't automatically defined in all browsers. Whereas, closures are an integral part of the language; the closures solution works everywhere. (Note, I believe Prototype inserts this method where it doesn't exist. jQuery's own `.bind` is for setting event handlers. (And it's now quasi-depricated.)
Answer: Use function.bind.
// Create a new function with null for the `this` object, and 1 and 2 for its arguments.
// Unlike `apply`, you shouldn't enclose the arguments in an array.
var fn = someFn.bind(null, 1, 2, 3, 4);
// This is like calling someFn.apply(null, 1, 2, 3, 4);
fn();

See the docs here. Note under the heading Compatability, it explains how to make sure this function will work on all your target browsers (even old verison of IE). You can just copy and paste the code there.
Comment: is it test.bind(null, array[i].something, array[i].wow, i); or test.bind(null, [array[i].something, array[i].wow, i]);
Comment: This method wants the arguments to be listed out as normal: `test.bind(null, array[i].something, array[i].wow)`.
Answer: //assuming it's always the same function
for (var i=0; i < array.length; i++){
    $("#mydiv li a").eq(i).on('click',function() {
        // your function here
    });
}

Comment: I need to store these click functions (for reuse), either in an array, either using the onlick attribute of  tags
Answer: function doSomething(a,b,c){
    console.log(a+b+c);
}

functionPrepare(func, args, thisarg) {
  return function() { func.apply(thisarg, args); };
)

var steps = [];
for (var i=0; i < array.length; i++) {
  steps.push(
    functionPrepare(doSomething, [array[i].something, array[i].wow, i])
  );
}

// later...
for (var i=0; i<steps.length; i++) {
  steps[i]();
}


windows command pattern match failing

Question: Problem :
I have the below command which runs the console file and parallely executes the dll files
This below command fails stating that the file is not at the source. Basically it says the file is not found at <code>..\bin\unittest</code> path
<code>%VSINSTALLDIR%\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe" /Logger:trx --Parallel "..\bin\UnitTest\*unity*tests*.dll"
</code>
The above command works fine when i run for the single file like the below. The below cmd works fine.
<code>%VSINSTALLDIR%\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe" /Logger:trx --Parallel "..\bin\UnitTest\Lang.unity.tests.dll"
</code>
So I believe the problem is due to the pattern matching with unity tests. I tried multiple workaround but the command fails
Can any one point out why the command fails ?
Comment: Maybe the tool cannot resolve wildcards, but you could put a [`for` loop](https://ss64.com/nt/for.html) around to do that job…
Answer: A quick google finds these links:

VSTest.Console.exe command-line options

[test file names] - Run tests from the specified files. Separate multiple test file names with spaces.
Examples: mytestproject.dll, mytestproject.dll myothertestproject.exe

Support wildcards in filenames for vstest.console.exe

Q: is this done. I see that there was a PR above that was merged with this support
A: Yes this is complete
Q: Do you perhaps now in which version this improvement has been included?
A: Here is the latest version that is released https://github.com/microsoft/vstest/releases/tag/v16.3.0-preview-20190808-03

So I'm going to go out on a limb and say either space-delimit the filenames, or upgrade to a newer version of vstest.console.exe...

windows command pattern match failing


What is the name of this design pattern (exposing private method to collaborator via delegate)?

Question: What is the name for the design pattern where a class exposes a private method or property to a collaborator via a delegate? This is in C#, but may be relevant to other languages too.
For example:
class Foo
{
    public int X
    {
        get;
        private set;
    }

    public void UpdateX(Bar bar)
    {
        bar.UpdateX(x => this.X = x);
    }
}

class Bar
{
    public void UpdateX(Action<int> setter)
    {
        setter(7);
    }
}

Foo foo = new Foo();
Bar bar = new Bar();
foo.UpdateX(bar);

I think this would be useful in the state pattern to allow states to update their contexts without requiring the context to expose stuff via its public interface, or nest state classes within the context class.
Answer: i don't see any pattern here but its a break of encapsulation.
if you are having a readonly property so why you are trying circumvent it.
Comment: I think the idea here is to store the state of another object in Foo. It's a contrived example, sure.
Comment: Upon reflection, I tend to agree with this reply. I guess it's a coding idiom that doesn't qualify as a pattern. The encapsulation break would stem from the fact that client code could hang on to the delegate and change the property after the Update call has returned.
Answer: Strategy Pattern or State Pattern
Answer: Delegation is a design pattern.
Answer: This has striking similarity to the Memento pattern, which is indeed useful for storing and manipulating states.
It also has elements of Dependency Injection or Delegation.
Perhaps someone more seasoned than I will recognize it by it's true name.
Here is some information on the Memento pattern:
Wikipedia: Memento
And the Dependency Injection pattern:
Wikipedia: Dependency Injection
Answer: I'll take Double Dispatch for 200. And well on your way to the visitor pattern.
I would also argue that this doesn't break encapsulation, simply because Foo defines the delegate.


Pointing subdomain (from cpanel, hosting company) to an external public IP

Question: How can I create a subdomain from a public IP and an existing domain name ?
I have a website hosted by an external hosting company.:
www.example.com

I have a public IP (not real): 127.180.150.20
I have a LAN.
What I want to do:
I am developing a web application (php/html/perl) that will need a lot of space for that I have planed
  to have my own dedicated server. I want to use my own computer and assign it a public IP
  but the application should be accessed from the following subdomain address:
  www.app.example.com

Is it possible to create a subdomain from the cpanel and point it to my public IP address?
Do I need to set up maybe a DNS server and a client, what I predict will be tough

I don't necessarily need the step by step on how to achieve this but rather the outline.
Answer: If the server running cpanel also is the primary NS server for your domain, then yes, using these instructions: http://docs.cpanel.net/twiki/bin/view/AllDocumentation/WHMDocs/EditZone
Answer: Its just a matter to define the correct A record for this name in the DNS zone file :
www.app.example.com    IN A 127.180.150.20

But this can only be done if you are the actual owner of example.com domain and can manage directly the DNS records. If this domain is owned by your hosting company, that you will need to ask them to do this change.
Answer: Is your public IP a fixed(static) or dynamic?.
Assuming it is a static one and your cPanel server is your primary dns server, you can simply add an "A" record to the zone file".
If you have WHM access, use the below link
http://docs.cpanel.net/twiki/bin/view/AllDocumentation/WHMDocs/EditZone
If you only have the cPanel access, follow the below link
http://docs.cpanel.net/twiki/bin/view/AllDocumentation/CpanelDocs/SimpleDnsEditor
Basically what you need to do is adding the following A record to the zone file
www.app.example.com.    IN A 127.180.150.20

If your public IP is dynamic and changing, the above methods will not work.


How to Handle Zeroes in Ratio of Count Variables

Question: In my discipline, it's common to use the ratio of predators:prey as a proxy for pest control by naturally occurring pest insects and spiders. That means making a ratio of two negative binomial distributions, (which I would then use as the response variable in a GLM analysis with AICc model selection). Since these distributions are independent, that ratio can vary btw 0 and positive infinity, not 0-1 (in practice, my data go from 0-10). This works fine except when either of the values is a zero (yielding infinity or NaN). Most papers seem to handle this by lumping samples together so no zeroes occur, but I want to analyze my data at the scale I collected them, maximizing sample size and resolution of other variables.
Eliminating all Inf/NaN values works, and I get usable analyses, but it sacrifices information (difference between 30:0 and 1:0 samples) in a way that biases analysis towards processes active in samples where both occur. Adding a small value to all numbers arbitrarily sets the scale of ratios in a pretty extreme way. Is there a good solution for this?
Comment: Since taking a ratio obliterates all information about the actual counts, this approach looks unpromising (and clearly is inadmissible in the technical sense of being a uniformly inferior statistical procedure).  Why not model *both* responses simultaneously?
Comment: Could you give some more details of the glm analysis you are using? Which glm family function? Or references to some papers using this?
Comment: @kjetil
Here's the paper I'm using as a point of reference, though this is not an uncommon approach in the field: http://www.sciencedirect.com/science/article/pii/S1049964416302377

I'm not entirely sure the best family to use--it has the shape of a negative binomial distro but also is non-integer so maybe that's not ideal?
Comment: @whuber I'll look into modelling them both together, that seems like a good solution, other than my unfamiliarity with the technique/functions. Is glm.nb capable of handling multiple response vars or do I need something fancier?
Answer: You can try to use a joint model for the two species counts, using a bivariate negative binomial distribution. That could be more informative than analyzing the ratio, as hinted in a comment by user whuber. Now, there are multiple bivariate negative binomial distributions, some papers are Characterization of the Bivariate Negative Binomial Distribution and A Classification of Bivariate Negative Binomial Distributions.  A limitation might be not admitting negative correlations.
R has multiple implementations of this, and models based on it. See for instance VGAM or bzinb.  Also RMKdiscrete.  I will add an example later.
Answer: Perhaps you can use predators as response like you have, and prey as offset in your negative binomial model. This way you would keep the ratio without having to model with two dependent variables.
Comment: That's an interesting suggestion! My understanding of offsets is fuzzy but I was under the impression they needed to be constants? Have you seen an example of someone using offsets in this way?
Comment: From my understanding, offsets are there to account for varying "exposure" across observations so to speak. So, by definition, offsets are not constants. In your case you would get a model like this: glm(predators~ x1+x2+xi, offset = log(prey), family = neg.bin). I dont know of any good examples but there are quite a few posts on offets. I do not think offsets can be zero however.
Comment: I thought about this, but it doesnt seem to be a good match.  First, you cant have a zero offset, secpnd, what to do woth cases such as (0,1)? That is prey=0,, predator=1? The number of prey doesnt reallt match the defonition of exposure.


Postgresql Stored Procedures: Using id from one statement in another

Question: Is it possible to create a stored procedure with two insert statements where id/primary_key from the first insert statement will be used in second.
For eg.
INSERT INTO activity VALUES (DEFAULT, 'text', 'this is a test');
If the id returned from the above statement is x, the second insert will be like:
INSERT INTO activity_tree VALUES (DEFAULT, **x**, user_id) or something like that.
I understand thatlibpq has functions which can give the id from the first statement.
But I want to combine them into a stored procedure. Please advise.
Regards,
Mayank
Answer: Declare a variable, e.g. new_id and then you can store the generate id in there:
INSERT INTO activity VALUES (DEFAULT, 'text', 'this is a test')
   RETURNING id INTO new_id;

INSERT INTO activity_tree VALUES (DEFAULT, new_id, user_id);

This assumes the column where the value is generated is called id
Btw: do not use "unqualified" insert statements. Always specify the columns in the INSERT part. That makes your code much more stable:
INSERT INTO activity (id, some_column, other_column)
VALUES
(DEFAULT, 'text', 'this is a test')

And make sure you are not calling variables the same way as columns. user_id seems to be a potential naming conflict here. This will compile with 8.x but might give you strange errors. I think this will no longer compile with 9.x
Comment: **Excellent** Info. Thanks a lot. I'll take care of each and everything you suggested. Thanks once again
Comment: Accepted. I did not know about this provision. I'm relatively new to Stackoverflow :)


how to change the path of the preference files in PL/SQL Developer version 9

Question: my pl/sql developer give me an error (file access denied) every time I execute a sql statement in sql window.  it is running fine in command window.  when I look in support info I notice the Preference files are located as follow
Preference Files
C:\Program Files\PLSQL Developer\Preferences\Default\Default.ini
C:\windows\system32\config\systemprofile\AppData\Roaming\Preferences\USER\default.ini
and I don't have access to this file hence I got the error.
C:\windows\system32\config\systemprofile\AppData\Roaming\Preferences\USER\default.ini
is there a way to change the path to
C:\Users\USER\AppData\Roaming\PLSQL Developer\Preferences\USER\Default.ini
thanks inadvance
Tuan
Answer: There is a prefpath command-line argument, so you can start PL/SQL Developer using something like:
"C:\Program Files (x86)\PLSQLDeveloper\plsqldev.exe" userid=un/pw@svc prefpath="%APPDATA%\Preferences"


Odd one out questions

Question: These are two questions given to a grade 5 student.
I couldn't get a conclusive and compelling answer to any.
Comment: In both sets, d) represents the set with a different set of digits compared with the others.
Answer: I don't think there is one.  I have seen one like 38 where three of the four choices had a clear difference from all the rest, so you were supposed to pick the fourth.  I would not call that grade 5 logic-it was in a Martin Gardner column.  But here I can find something wrong with all the choices-1.01 is the only one with a zero in the middle, 1.10 is the only one that ends in 0, 1.11 is the only one with an odd number of 1's, 1.111 is the only one with four digits.
Comment: agreed,nothing conclusive.Also 1.10 is the only one with a redundant digit(the zero).
Comment: @Ross I have first downvoted your answer, because it looked as one of those that try to "outsmart" the author, without taking into account that it is a 5th grade problem, but since there are several others in the same direction, decided to remove my vote, but for some reason it does not let me now... Hopefully, this does not matter that much for you.
Comment: @Vadim:  no problem.  I believe it is not appropriate for 5th grade.   In fact, I don't think it is a good problem at all.  To make it a good problem, when somebody explains the answer you should be convinced.  Maybe there is a good answer, but nobody has shown it yet.
Comment: @RossMillikan I agree, and the OP already says that he/she cannot find a compelling answer, I just thought that there might be a 10-year boy/girl sitting with their farther/mother trying to get some ideas about how to solve this, and simply criticizing the problem itself (and implicitly their teacher) is not the best thing to do, even if the teacher is mistaken this time giving this problem. So, anyway, let move on.
Comment: $1.01$ is the only option with a value less than $1.1$. (Of course, this isn't really *too* much better than punting with "item $x$ is the only option with value equal to item $x$".)
Answer: I would say c) and b) for the two problems.  For the first one, 1.11 is the only number that's written with an odd number of 1's (making it literally the odd one out).  For the second, the pair (7,9) is the only one which, when written in binary, uses an even number of 0's.  I.e., (3,5)=(11,101) has one 0, (7,9)=(111,1001) has two, (41,53)=(101001,110101) has five, and (91,119)=(1011011,1110111) has three.
On the other hand, c) is a compelling answer for the second problem because it's the only one that involves an even digit.
On yet one more hand, d) is a compelling answer because (91,119) is the only pair that's not relatively prime.
Clearly this makes a) the compelling answer, because it's the only one for which I'm unable to find anything compelling that makes it stand out from the others....
Answer: In 38:
  I would say b) for the only reason that it is the only value that could (should) be written in a shorter form: 1.1 instead of 1.10.
In 5
c) is the only one using 4 digits, not 2. Also, it uses the only even digit(4).
Comment: 91, 119: 2 digits.
Comment: Your reasoning for 38 is good, but I disagree with that for 5 since d) has a similar condition...  Except that bit about the even digit.
Comment: Ah, got it, good point
Comment: interesting observation.
Answer: In $38$, if you consider those to be numbers in base two expansion, $d$) is the only one that is not a multiple of $.25$ once converted to base $10$.
In $5$, $c$ is the only one that is not a pair of numbers, with one congruent to $1$, the other congruent to $3$ mod $4$.
We can keep naming ways to find one that is the "odd one out"... it's quite subjective.
Comment: OK, changing my comment: 9 was removed.

Odd one out questions


Como determinar o horario em que uma tarefa de segundo plano vai ser executada

Question: Estou programando para Windows 10, e em determinado horário em um dia eu quero que minha tarefa em background seja deparada.
Aqui está meu código de registro:
na tela inicial:
var trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);
            var condition = new SystemCondition(SystemConditionType.InternetAvailable);
            var tarefa = RegistrarTarefasSegundoPlanoAsync.RegisterBackgroundTask(typeof(SalvaImagemTask).FullName, "SalvaImagemTask", trigger, condition);

RegisterBackgroundTask.cs
public static BackgroundTaskRegistration RegisterBackgroundTask(
                                                string taskEntryPoint,
                                                string name,
                                                IBackgroundTrigger trigger,
                                                IBackgroundCondition condition)
        {

            foreach (var cur in BackgroundTaskRegistration.AllTasks)
            {
                if (cur.Value.Name == name)
                {
                    return (BackgroundTaskRegistration)(cur.Value);
                }
            }

            var builder = new BackgroundTaskBuilder();

            builder.Name = name;
            builder.TaskEntryPoint = taskEntryPoint;
            builder.SetTrigger(trigger);

            if (condition != null)
            {

                builder.AddCondition(condition);
            }

            BackgroundTaskRegistration task = builder.Register();

            return task;
        }

aqui é como ela tá registrada no meu manifest
Comment: Creio que você possa usar a clase Time.  https://msdn.microsoft.com/pt-br/library/system.timers.timer(v=vs.110).aspx
Answer: Não é possível determinar um horário especifico para uma background task ser executada. Você pode usar uma trigger de timer para especificar o intervalo de tempo entre as execuções da background task, respeitando o tempo minimo de 15 min, é uma regra. Segue exemplo de uso da trigger timer:
                BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
                taskBuilder.Name = nameof(BackgroundClassName);
                taskBuilder.TaskEntryPoint = typeof(BackgroundClassName).ToString();
                // min 15 minutes
                taskBuilder.SetTrigger(new TimeTrigger(15, false));
                BackgroundTaskRegistration registration = taskBuilder.Register();

Se quiser ver outras triggers e como usar background tasks com eficiencia acesse esse MVA em portugues (https://mva.microsoft.com/pt-br/training-courses/live-tiles-e-background-execution-14433?l=K9L5uVmkB_1605192797)


Gradient of Coefficient of Variation of weighted geometric mean

Question: This question is another version of the one here which I've previously asked. the difference is instead of WM here we have exp(WM). exp(W×log(M)) is equivalent to weighted geometric mean of M when W sums to 1 (wikipedia) (the exp operation is applied element-wise). I just replaced log(M) with M for simplicity.
I have a d×n matrix called M. What is the best 1×d W that minimizes CoV(exp(WM)) which is Coefficient of Variance of exp(W×M), considering that W sums to 1
$$\underset{W}{\operatorname{argmin}}\frac{SD(exp(WM))}{Mean(exp(WM))}$$
$$\sum_{i=1}^{d} w_{i}=1$$
I can rewrite this as:
$$\underset{W}{\operatorname{argmin}} \frac{\sqrt{\frac{1}{n}\left\|exp(WM)-\frac{1}{n} exp(WM)
 A\right\|_{2}^{2}}}{\frac{1}{n} exp(WM) A}$$
$$\sum_{i=1}^{d} w_{i}=1$$
A is a n×1 matrix of ones.
I hope I get a closed form for W* or have the gradient so i can use gradient descent to find the minimum.

Edit: Here is my try based on this answer. but couldn't solve it. I think the main problem is with the Hadamard Product ($\circ$) which appears when differentiating the exp(WM).
Introduce an unconstrained vector $x$ and use it to construct a column vector $w$ which satisfies the constraint.
$$\eqalign{
&w = \frac{x}{{\tt1}^Tx} \quad\implies\quad {\tt1}^Tw = \frac{{\tt1}^Tx}{{\tt1}^Tx} \doteq {\tt1} \\
}$$
Then for algebraic convenience, define some auxiliary variables
$$\eqalign{
{\tt1} &= A,\quad &J = AA^T \\
C &= I-\tfrac{1}{n}J\quad &({\rm Centering\, Matrix}) \\
w &= W^T \quad &({\rm column\, vector\, constructed\, from\, }x)\\
B &= d×1\,\,matrix\,of\,ones \\
Q &= M\circ By^T \\
y &= exp(M^Tw)  \quad&\implies dy = M^T\circ exp(M^Tw)B^Tdw = Q^Tdw \\
z &= Cy  \quad&\implies dz = CQ^Tdw \\
\alpha &= {\tt1}^Tx \quad&\implies d\alpha = {\tt1}^Tdx \\
\beta &= {\tt1}^Ty \quad&\implies d\beta = {\tt1}^Tdy = {\tt1}^TQ^Tdw \\
w &= \alpha^{-1}x \quad&\implies dw = \alpha^{-1}dx - x\alpha^{-2}d\alpha \\
 & \quad&\implies dw = \alpha^{-1}(I - w{\tt1}^T)\,dx \\
}$$
Note that $C^T=C=C^2\;$ and
$\;\beta={\tt1}^Texp(M^Tw)={exp(w^TM){\tt1}}=exp(WM)A$
these properties will be used in several of the steps below.
Use the new variables to simplify the vector appearing in the numerator.
$$\eqalign{
&\Big(exp(WM)-\tfrac{1}{n}exp(WM)AA^T\Big)^T = \Big(exp(M^Tw) - \tfrac{1}{n}Jexp(M^Tw)\Big)
 = Cy = z \\
}$$
Call the objective function $\phi$, and start by differentiating its square.
$$\eqalign{
\phi^2 &= n\beta^{-2}z^Tz \\
2\phi\,d\phi &= 2n\beta^{-2}z^Tdz - 2n\beta^{-3}z^Tz\,d\beta \\
d\phi
 &= n\phi^{-1}\beta^{-3}z^T\Big(\beta\,dz - z\,d\beta\Big) \\
 &= n\phi^{-1}\beta^{-3}z^T\Big(\beta\,CQ^T - z{\tt1}^TQ^T\Big)\,dw \\
 &= n\phi^{-1}\alpha^{-1}\beta^{-3}z^T\Big(\beta\,CQ^T - z{\tt1}^TQ^T\Big)\,\Big(I - w{\tt1}^T\Big)\,dx \\
\frac{\partial\phi}{\partial x}
 &= n\phi^{-1}\alpha^{-1}\beta^{-3}\Big(I - {\tt1}w^T\Big)\,\Big(\beta\,QC - Q{\tt1}z^T\Big)z \\
}$$
Set the gradient to zero.
$$\eqalign{
\Big({\tt1}w^T\Big)\,\Big(\beta\,QC - Q{\tt1}z^T\Big)\,z
  &= I\Big(\beta\,QC - Q{\tt1}z^T\Big)\,z \\
}$$
Eliminate $z$ .
$$\eqalign{
\Big({\tt1}w^T\Big)\,\Big(\beta QC - Q{\tt1}y^TC\Big)\,Cy
  &= \Big(\beta QC - Q{\tt1}y^TC\Big)\,Cy \\
\Big({\tt1}w^T\Big)\,Q\Big(\beta I - {\tt1}y^T\Big)\,Cy
  &= Q\Big(\beta I - {\tt1}y^T\Big)\,Cy \\
}$$
Answer: $
\def\a{\alpha}
\def\b{\beta}
\def\c#1{\color{red}{#1}}
\def\o{{\large\tt1}}
\def\g{\sigma}
\def\L{\left}\def\R{\right}\def\LR#1{\L(#1\R)}
\def\Diag#1{\operatorname{Diag}\LR{#1}}
$You were doing great until the final step where you "eliminated $z$".
That's not valid, so you must find a different way to solve the equation.
Here is an idea, but not a complete solution.
Define the matrix
$$H = {\b QC -Q\o z^T}$$
Then the zero gradient condition becomes
$$Hz = \LR{\o w^T}Hz \;=\; \LR{w^THz}\o \;=\; \g\o$$
This eliminates $z$ from one side of the equation
$$\eqalign{
\LR{\beta QC -Q\o z^T}z &= \g\o
}$$
Other substitutions can be used
$$\eqalign{
\b &= \o^Ty \\
Cz &= C^2y = {Cy = z} \\
Y &= \Diag{y} \quad&\implies\quad Q=MY,\quad z=Cy=CY\o \\
}$$
to rewrite the equation entirely in terms of $y$ $\,($or $Y)$
$$\eqalign{
\g\o_d
 &= M\Diag{y}\Big(\LR{\o^T_ny}C\Diag{y} -\LR{y^TCy}I_n\Big)\o_n \\
 &= M\Big(\LR{\o^T_n{Y}\o_n}\c{YCY}
  - \LR{\o^T_n\c{YCY}\o_n}{Y}\Big)\o_n \\
 &= S\o_n \\
S\o_n &= \g\o_d
 \quad\implies\quad {\frac{S\o_n}{\|S\o_n\|}} = \frac{\o_d}{\sqrt d} \\
}$$
This looks promising. It almost looks like an eigenvalue equation, however... $S$ is rectangular, so the $\o$ vectors on the RHS and LHS have different lengths.
The next step is to come up with an iteration formula akin to the classic power iteration to solve for a $y$ vector (or $S$ matrix) such that the pseudo-eigenvalue equation is satisfied.

Update
Since a closed-form eigenvalue-like solution seems improbable, and since we already know how to calculate the gradient and the cost function for any value of $x,\,$ i.e.
$$\eqalign{
\phi(x) &= \LR{n\beta^{-2}z^Tz}^{1/2} \\
g(x)
 &= n\phi^{-1}\a^{-1}\b^{-3}\Big(I-{\tt1}w^T\Big)\,\Big(\b\,QC - Q{\tt1}z^T\Big)z \\
}$$
a better idea is a numerical solution using a gradient-based method.
The Barzilai-Borwein method is particularly simple and effective.
Initialize
$$\eqalign{
x_0 &= random
 \qquad\qquad\qquad\qquad\qquad\quad \\
}$$
First step
$$\eqalign{
g_0 &= g(x_0) \\
x_1 &= x_0 - \LR{\frac{0.05\;\phi(x_0)}{g_0^Tg_0}} g_0
 \qquad\qquad\quad \\
k &= 1\\
}$$
Subsequent steps
$$\eqalign{
g_k &= g(x_k) \\
x_{k+1} &= x_k - \LR{\frac{\LR{x_k - x_{k-1}}^T\LR{g_k - g_{k-1}}}{\LR{g_k - g_{k-1}}^T\LR{g_k - g_{k-1}}}}g_k \\
k &= k+1 \\
}$$
Stop when $g_k\approx 0$.
Comment: No, in that linked post I did not divide by the $z$ vector. Instead I showed that the entire LHS (the stuff in red) is actually _equal_ to the zero vector. And the remaining RHS (the stuff in green) is an eigenvalue equation in disguise. In the current problem, the LHS is not equal to zero (as far as I can tell).
Comment: @asalimih The pseuodoinverse of the vector is
$$z^+=\frac{z^T}{z^Tz}$$
Note products
$$\eqalign{
z^+z&={\tt1},\qquad
zz^+&\ne I \\
}$$
Therefore you can clear vectors from the LHS, but not the RHS, i.e.
$$\eqalign{
za^T &= zb^T \quad\implies\quad a^T=b^T
 \quad&{\rm since}\quad z^+zb^T = b^T \\
Az &= Bz \;\;\quad\not\!\!\!\!\implies\quad A=B
 \quad&{\rm since}\quad Bzz^+ \ne B \\
}$$
Comment: Thanks alot for your answer. would you explain why was eliminating z invalid?
Comment: but you've done a similar thing [here](https://math.stackexchange.com/a/3491528/738053) if I understand it well.


Does Oracle Database have open issue list?

Question: I am carrying out some study of bugs in Databases, so I have to dig into those bugs reported by the users of databases. As we know, MySQL, MariaDB, PostgreSQL have ether open bug repository or open mailing list to track. HOWEVER, Oracle DB does not have such kind of thing.
Is that right ?
Thank you.
Answer: Oracle is not open-source, so no, they don't have a public bug tracker. If you have a support contract, you can see some bugs on Oracle Support, fixed and some not, but there are also unpublished bugs, not visible to the public.