MUDAR STATUS PHP

Question: Estou tendo um problema ao mudar o status dos usuario do meu banco de dados , aquando eu vou mudar o status de algum usuario ele não aprova o usuario daquela linha e sim ultimo usuario  o que pode ser?
logado.php
  <?php
                //Consulta
                $buscarusuario=$pdo->prepare("SELECT * FROM usuario");
                $buscarusuario->execute();

                //atribuindo dados á variavel
                $linha = $buscarusuario->fetchAll(PDO::FETCH_ASSOC);

                //percorrendo a variavel para listar os dados
                foreach ($linha as $listar) {
                    $iduser = $listar['id'];
                    echo "
";
                    echo " ".$listar['id']."	";
                    echo "".$listar['nome']."	";
                    if($listar['status'] > 0 ){
                    echo "Aprovado
  <form method='post' action='pg/mudastatus.php'>
    <input type='hidden' name='desaprovauser' value='$iduser'>
      <button type='submit' class='btn btn-xs btn-success alinha-btn' name='desaprova' value='desaprovar'>Desaprovar</button>

                    	";
                  }else{
                    echo " Aguardando aprovação
  <form method='post' action='pg/mudastatus.php'>
   <input type='hidden' name='aprovauser' value='$iduser'>
   <button type='submit' class='btn btn-xs btn-danger alinha-btn' name='aprova' value='aprovar' >Aprovar</button>
</form>

                    	";
                  }
  }
              ?>

mudastatus.php
    if(isset($_POST['aprova'])){

   $atualizarstatus = $pdo->prepare("UPDATE usuario SET status=1 WHERE id='".$_POST["aprovauser"]."' ");
   $atualizarstatus->execute();
   $linha = $atualizarstatus->rowCount();

   if($linha > 0){
     header("location:../logado.php");
   }else{
    echo "Erro ao Mudar status";
   }
}elseif (isset($_POST['desaprova'])){

   $atualizarstatus = $pdo->prepare("UPDATE usuario SET status=0 WHERE id='".$_POST["desaprovauser"]."' ");
   $atualizarstatus->execute();
   $linha = $atualizarstatus->rowCount();

   if($linha > 0){
     header("location:../logado.php");
   }else{
    echo "Erro ao Mudar status";
    header("location:../logado.php");
   }
}

Comment: Tá faltando um `` no primeiro bloco, é bom corrigir isso antes de prosseguir com os testes. Depois dá pra enxugar bem esse código fazendo um form só para tudo e tirando os hidden, mas antes é bom você conseguir fazer funcionar do jeito que sabe, pra não complicar demais. Depois, basta tirar os campos hidden, e usar o ID dos usuários no value dos buttons aprova e desaprova.
Comment: Estou votando para fechar, pois se trata de erro de digitação, e as respostas não resolvem o problema do código, alem de conterem afirmações incorretas, atrapalhando outros usuários. Veja prova de funcionamento com nomes repetidos aqui: http://codepen.io/bacco/pen/BzkBPy
Answer: Primeiro um breve comentario sobre segurança, já que esta usando PDO e prepare... é recomendavel que vocenao passe as variaveis direto na query...
$atualizarstatus = $pdo->prepare("UPDATE usuario SET status=1 WHERE id=? ");
$atualizarstatus->execute(array($_POST["aprovauser"]));

Assim, você já evitaria a a injeção de sql, atraves de variaveis inseridas diretas na query.
Agora voltando a sua pergunta talvez seja que, pelo que percebi, seu codigo tera
um usuario e o botao aprovar ou desaprovar. E se tiverem mais de um, Ficaria:
Usuario1 Aprovar
Usuario2 Aprovar
Usuario3 Aprovar
Sendo esse aprovar o botao submit, voce concorda que quando eu clicar no aprovar eu vou enviar normalmente, mas como existem mais de um botao aprovar, ou seja com o mesmo nome, nao hora de pegar o valor ele nao vai saber qual voce clicou e sim pegar o ultimo botao, que é o que esta acontecendo.
Espero ter ajudado
Comment: os botões estão em forms separados (deveriam estar, na verdade. parece que faltou um ).
Comment: Não adianta estarem em forms diferentes se a propriedade name estão iguais
Comment: Pode ter quantos name repetidos quiser em forms diferentes. Não confunda com ID. ID é um por HTML, name vc pode repetir em forms diferentes. Ou até no mesmo, desde que o backend saiba o que fazer. Inclusive, array de PHP usa o mesmo name em vários campos.
Comment: já testei nao sou tao leigo quanto acha
Comment: Não me lembro de ter comentado sobre ninguém ser ou não leigo, só apontei o engano na informação para que você tivesse oportunidade de corrigir. Apenas isso. E o codepen é apenas pra facilitar o teste pra você e quem mais tiver duvidas. http://codepen.io/bacco/pen/RRgbrd
Answer: Você está criando vários input hidden com  mesmo name, por isso você não tem garantido qual o valor que chega no backend, tente mudar sua lógica pra cada input ter um name único.

MUDAR STATUS PHP


JavaScript prototype array member cannot find push of undefiend

Question: I am trying to implement a stack. when I try to push into the arr this error pops up

TypeError: Cannot read property 'push' of undefined

var MinStack = function() {
    let Min = null;
    const arr = new Array(); // I also tried arr = []
};

/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.arr.push(x);
    this.Min = Math.min(...arr);
};

I searched for answers but I didn't find out why can't I access my arr in the constructor?
Comment: you can not because `Min` and `arr` are private properties of the constructor function and can not be accessed by the instantiated ones. Such as when done like `var x = new MinStack()` then `x` has access to it's constructors prototype and known as the `this`, hence `x` is the `this` in `MinStack.prototype.push` but `x` does not have any way to access `Min` or `arr`. So `this.arr` is `undefined`...
Answer: This is because this.arr is not defined.
You have defined the arr as a variable as you have used let to declare it, but not as a property of the instances of MinStack.
Variables declared using let or const are scoped to the enclosing block and not available outside of it.
The enclosing block in your case the function block, so it becomes a local variable scoped to the function and not visible outside of it.
When you use a function as a constructor and use the new keyword to instantiate it a new object is created in memory and is assigned to the this reference in the constructor function. properties assigned to that this reference become properties of the instance created from the constructor function:

var MinStack = function() {
    this.Min = null;
    this.arr = new Array();
};

/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.arr.push(x);
    this.Min = Math.min(...this.arr);
};

MinStack.prototype.min = function(x) {
    return this.Min;
};

const minArr = new MinStack();
minArr.push(1);
minArr.push(2);
minArr.push(3);
minArr.push(-9);
console.log(minArr.min());


Vboxheadless without a command prompt (VirtualBox)

Question: I'm trying to run VirtualBox VM's in the background from a service. I'm having trouble starting a process the way I desire. I'd like to start the virtualbox guest in headless mode as a separate process and show nothing as far as GUI.
Here's what I've tried:
From command line:
start vboxheadless -s "Ubuntu Server"
In C#:
        ProcessStartInfo info = new ProcessStartInfo
        {
            UseShellExecute = false,
            RedirectStandardOutput = true,
            ErrorDialog = false,
            WindowStyle = ProcessWindowStyle.Hidden,
            CreateNoWindow = true,
            FileName = "C:/program files/sun/virtualbox/vboxheadless",
            Arguments = "-s \"Ubuntu Server\""
        };

        Process p = new Process();
        p.StartInfo = info;
        p.Start();

        String output = p.StandardOutput.ReadToEnd(); //BLOCKS! (output stream isnt closed)

I want to be able to get the output to know if starting the server was a success. However, it seems as though the window that's spawned never closes its output stream.
It's also worth mentioning that I've tried using vboxmanage startvm "Ubuntu Server" --type=vrdp. I can determine whether the server started properly using this. But it shows a new command prompt window for the newly started VirtualBox guest.
Answer: Just in case somebody faces the thing again here is what I do for this...
start-process "vboxheadless" "-s ubuntu" -WindowStyle Hidden
either put it in a powershell script or type in a powershell console window. You may create a shortcut or an alias etc.
Comment: works well even in Windows 10, tho in my case I needed to specify the full path to vboxheadless. You can save it as a one-liner .ps1 file in `%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup` and then it will run headless at start up.
Answer: I've recently managed to do it here. The solution is not very good: I don't like Windows development.. but it works, what else can you desire? :))


Estou precisando fazer uma comparação utilizando JavaScript

Question: Preciso resolver um exercício aparentemente simples para um curso de JavaScript, mas eu não estou conseguindo fazer.
Preciso pegar os dados de um formulário onde adiciono o nome, sobrenome e idade de uma pessoa, criar uma lista das pessoas que vou adicionando e após isso, fazer uma comparação de idades para mostrar ao usuário quem é a pessoa mais velha.
Eu já consegui fazer o formulário e adicionar as pessoas criando a lista..
só esta faltando fazer a comparação de idades e mostrar quem é a pessoa mais velha para o usuario.
Nesse link deixei um video com a minha duvida mais explicita para vocês entenderem um pouco melhor, o que estou pretendendo resolver. https://youtu.be/KP7rTY710NE

function adicionarPessoa() {
    let nome = document.querySelector("#nome")
    let sobreNome = document.querySelector("#sobreNome")
    let idade = document.querySelector("#idade")
    let lista = document.querySelector("#lista")
    let registro = document.querySelector("#registro")
    registro.textContent = "Registros de:"

    let nomeCompleto = `${nome.value} ${sobreNome.value}: ${idade.value}`
    nome.value = ""
    sobreNome.value = ""
    idade.value = ""

    let pessoaRegistrada = document.createElement("li")
    pessoaRegistrada.textContent = nomeCompleto

    lista.appendChild(pessoaRegistrada)
}

document.querySelector("#botao").addEventListener("click", adicionarPessoa)
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>teste</title>

    <form>

        Nome:
        <input id="nome" type="text" name="nome" />

        Sobrenome:
        <input id="sobreNome" type="text" name="SobreNome" />

        Idade:
        <input id="idade" type="number" name="idade" />

      <button id="botao" type="button">Adicionar</button>
    </form>

Comment: percorre a lista pegando os atributo de idade e quando tiver percorrendo vai ter um if que vai armazenar a idade em uma variavel somente quando a atual idade for maior que a que ja esta armazenada
Answer: Uma opção é criar uma variável que mantenha a idade da pessoa mais velha (você pode utilizar um objeto se tiver que armazenar mais informações sobre a pessoa).
Assim, iniciamos o valor como 0 e, se a pessoa que inserimos tiver idade maior que o número que temos armazenado, atualizamos o valor e a mensagem que informa a pessoa mais velha.
Algo assim:

const form = document.getElementById('form');
const oldestPanel = document.getElementById('oldest-panel');

// Variável que utilizaremos para manter a idade da pessoa mais velha:
let oldest = 0;

form.addEventListener('submit', (event) => {
  event.preventDefault();

  const name = form.elements.name.value;
  const age = parseInt(form.elements.age.value, 10);

  // Insira na lista ao invés de dar um `console.log`...
  console.log('Registrado: %s, que tem %d anos.', name, age);

  // Se a idade do indivíduo atual for maior do que a da pessoa mais velha (anterior):
  if (age > oldest) {
    oldest = age;
    oldestPanel.textContent = `A pessoa mais velha (${name}) tem ${age} anos.`;
  }
});
<form id="form">
  <input name="name" type="text" />
  <input name="age" type="number" />
  <input type="submit" value="Enviar" />
</form>

Desse modo você evita ter que percorrer uma lista completa cada vez que uma pessoa nova for adicionada. Fazemos uma simples verificação a cada novo "registro".
Não modifiquei o seu código (fiz um novo) para evitar dar-lhe a resposta completa. Isso é apenas uma ideia que funciona para o seu caso.


Group results by headings from other table

Question: I have two tables, one contains the page/heading number and the heading text, the other contains values to print under each heading:
Headings:
page | heading | text
1    | 1       | "heading 1"
1    | 2       | "heading 2"

Contents:
page | heading | contents
1    | 1       | "some stuff"
1    | 1       | "some more stuff"
1    | 2       | "some other stuff"

I want the results for page 1 to be:
heading 1
some stuff
some more stuff
heading 2
some other stuff

Augmented with HTML where needed.
Using two while loops with mysql_fetch_array() doesn't work because you have to fetch before you can check if it's under the correct heading. This means I miss the first entry of every next heading.
$query = "SELECT text,heading FROM headings WHERE page=".$page." ORDER BY heading ASC";
$headings = mysql_query($query) or die(mysql_error());
$query = "SELECT filename,heading FROM pictures WHERE page=".$page." ORDER BY heading ASC";
$pictures = mysql_query($query) or die(mysql_error());

while($heading = mysql_fetch_array($headings)){
echo $heading[0];
    while($image = mysql_fetch_array($pictures)){ # This skips entries because I have to check the contents themselves
        if($image[1] != $heading[1]){
            break;
        }
        echo $image[0];
    }
}

Is there any way to do this without running multiple queries for every heading? (There may be many on a page)
Comment: why have you separated the heading from its content, seems counter intuitive, means your have todo at least a join for every query for every piece of content
Comment: Because there are multiple content per heading I need a separate table for the headings.
Answer: Just fetch all results into 2 arrays before iterating with while  loops.
Comment: Something like `while($images[] = mysql_fetch_array($pictures)){}`? Thanks that worked like a charm
Answer: What you are looking for is a query with a JOIN in it.
I have assumed your database looks something like this: Fiddle
Included is the query you may be looking for


Abrir página após 2 segundos com js no intel xdk

Question: Estou usando o intel xdk.
Na primeira página tem a logo do sistema, quero que seja carregada a página inicial do sistema após 2s.
Como teste fiz isso com botão para saber como é feito, mas não estou sabendo fazer para que seja carregado automaticamente após 2s.
Veja:
<code>$(document).on("click", ".uib_w_2", function(evt){
         activate_page("#inicio");
    });
</code>
Answer: Consegui!
Para quem tiver a mesma dúvida segue a resposta:
<code>setTimeout(function() {
    activate_page("#inicio");
}, 2000) ;
</code>
Comment: Marque sua resposta como aceita


Sending an email to everyone with a certain role

Question: Me: Small business owner with no coding or Drupal background who wants to learn by doing instead of hiring a developer for every small thing.
Goal: I have a Drupal 7 website and would like to send different types of emails to users of specific roles using the Rules (or an easier way if you care to suggest it). I've explored using Rules to accomplish this with some success by cloning similar ones and making small changes, but making one from scratch is more challenging. I've wrapped my head around scheduling the event and creating the email in the action, but specifically editing the condition is a barrier. I assume that the element "User has role(s)" is what I should use, but I'm confused on how to drill down the "data selector" under the USER area. I'd like the system to evaluate all members of the site and email everyone with a specific role...I don't see an appropriate option. Maybe I'm looking at the wrong condition element. Little lost - I'm sure it is a painfully obvious to someone who knows what they're doing.
All constructive suggestions and guidance welcome on how to accomplish this - trying to learn!
Comment: If all you want to do is to send emails specifically to users in a certain role, you can use this module https://www.drupal.org/project/mass_contact   . Or are you trying to use rules as part of a workflow?
Comment: learn views rules, https://www.drupal.org/project/views_rules
Comment: Also see here for more help https://drupalize.me/series/learning-rules-framework-series
Answer: If all you want to do is send emails to users of a certain role, you can use the Mass Contact module.  It enables a user to send an email to users by role or taxonomy. It is very easy to use, without any coding knowledge necessary. I have used it on a couple of business-related sites.
The other alternative is to use Simplenews. This is used mostly for sending email newsletters to lists of subscribers, if that is the kind of email you want to send.
But if you really want to use rules, I suggest you go through some documentation like this. Under the "Add a new action" of your rule, under the "System" section, there is a "Send email to all users of a role" action. That may be what you need.


How do I update an eval() calculation based on user inputs into a data table in R Shiny?

Question: I have an app where a user selects an equation from a drop down list. The app pulls all the variables that get input into the equation from a table, plugs the variables into the equation, and provides the result. However, I want a user to be able to override any of the values and see how the calculation is affected. The calculation is facilitated using eval and a list of variables, so I suspect what I'm trying to do is change the value of the variable in the environment when a user updates a table value, but I'm open to other ideas! See screenshot and reprex provided below.

I am able to get the text box where a user can input their own values for the variables. (Small victory!) I tried using a proxy table to facilitate the recalculation, but the problem is I haven't found an example where there is a proxy table and a dynamic input field in the table.
Many of the examples I found start with mod_df <- shiny::reactiveValues(x = df) (or something similar). When I try to replicate the code, I get the following error:
You tried to do something that can only be done from inside a reactive consumer.
Reprex:
library(shiny)
library(DT)
require(stringr)

df1 = data.frame("ID" = c(1:3), "Equation" = c(" *  + <C>", " +  + <C>", " -  + <C>"))
df2 = data.frame("Equation" = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                 "Variable" = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
                 "Value" = c(5,3,10,2,4,NA,7,5,NA))
df3 = data.frame("Premise" = c("Red", "Yellow", "Green"),
                 "Value" = c(5,4,3))

ui <- fluidPage(
  selectizeInput("df1Select", "Select Equation", choices = df1$Equation, multiple = TRUE, options = list(maxItems = 1)),
  h3("This is the static table of the variables as defined"),
  dataTableOutput("StaticTable"),
  br(),
  htmlOutput("CalcResultStatic"),
  h3("Here, I want to be able to manipulate the fields and recalculate the results"),
  dataTableOutput("InteractiveTable"),
  br(),
  htmlOutput("CalcResultInteractive"))

server <- function(input, output, session) {

  ### Filter Data
  StaticTableFiltered = reactive({
    EqSelect = if(is.null(input$df1Select)) unique(as.vector(df1$ID)) else df1$ID[df1$Equation == input$df1Select]
    filter(df2, Equation %in% EqSelect)})

  ### Render Static Table
  output$StaticTable = renderDataTable({
    if(is.null(input$df1Select)) return(NULL) else {StaticTableFiltered()}},
    options = list(dom = 't'), selection = "none")

  ### Render Static Result as Text
  CalculateResultStatic = reactive({
    if(is.null(input$df1Select)) return(NULL) else {
      ### Define algorithm
      CalcEq = paste(input$df1Select)
      ### Make list of input variables
      Variables = as.data.frame(str_extract_all(input$df1Select, "<(.*?)>"))
      colnames(Variables)[1] = "Vars"
      ### Remove < > from algorithm and assumptions
      CalcEq = gsub("<","",gsub(">","",CalcEq))
      Variables$Vars = gsub("<","",gsub(">","",Variables$Vars))
      ### Get values from Assumptions table
      Variables = merge(Variables, df2[df2$Equation == df1$ID[df1$Equation == input$df1Select],], by.x = "Vars",  by.y = "Variable", all.x = TRUE, all.y = FALSE)
      ### Convert variables to list
      Variables.List = as.list(Variables$Value)
      names(Variables.List) = Variables$Vars
      ### Evaluate equation on list
      eval(str2lang(CalcEq), envir = Variables.List)}})

  output$CalcResultStatic = renderUI(HTML(paste("",CalculateResultStatic(), sep = "")))

  ### Render Interactive Table
  output$InteractiveTable = renderDataTable({
    if(is.null(input$df1Select)) return(NULL) else {
      data = data.frame(StaticTableFiltered(),
                        UserValue = sapply(1:nrow(StaticTableFiltered()), function(i) {sprintf('<input id="text" type="text" class="form-control" value=""/>', i)}))}},
    selection = "none", escape = FALSE,
    options =
      list(
        preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } '),
        dom = 't',
        processing = FALSE))

  ### Render Interactive Result as Text
  CalculateResultInteractive = reactive({
    if(is.null(input$df1Select)) return(NULL) else {
      ### Define algorithm
      CalcEq = paste(input$df1Select)
      ### Make list of input variables
      Variables = as.data.frame(str_extract_all(input$df1Select, "<(.*?)>"))
      colnames(Variables)[1] = "Vars"
      ### Remove < > from algorithm and assumptions
      CalcEq = gsub("<","",gsub(">","",CalcEq))
      Variables$Vars = gsub("<","",gsub(">","",Variables$Vars))
      ### Get values from Assumptions table
      Variables = merge(Variables, df2[df2$Equation == df1$ID[df1$Equation == input$df1Select],], by.x = "Vars",  by.y = "Variable", all.x = TRUE, all.y = FALSE)
      ### Convert variables to list
      Variables.List = as.list(Variables$Value)
      names(Variables.List) = Variables$Vars
      ### Evaluate equation on list
      eval(str2lang(CalcEq), envir = Variables.List)}})

  output$CalcResultInteractive = renderUI(HTML(paste("",CalculateResultInteractive(), sep = "")))

}

shinyApp(ui = ui, server = server)

In addition, if you play with the reprex, you'll see some equations require a value to be looked up. I also wanted to create a column to facilitate the lookup, but I thought let's start with just the text field and see if the help I get there guides me in the right direction to do the next piece myself.
Thanks in advance for any help!
Comment: Rather than using string substitutions and evaluations, you could add a column to `df1` that contains actual R functions and then use `do.call` with a list of arguments, coming from the original data.frame and/or the user's values.
Comment: @MichaelDewar That sounds interesting... what would that look like?
Answer: I suggest storing the equations as actual R functions in a data frame column.  The label should be a separate column.
Equations are chosen using a selectInput with choices given by a named list.  The names are the labels and the values are the actual functions.  They come from the data frame I just mentioned.  When a new equation is chosen, an observer updates the numericInputs with the initial values.
User editable data tables (not just DT) are painful in Shiny.  I suggest using numericInputs for each of your needed variables.  In the example below I have hard-coded three numericInput in the UI, but you could dynamically create/destroy or show/hide if needed.  It partly depends on whether you need arbitrarily many or arbitrarily named variables, or if you have a small set of re-used variables.
The server function below is basically dynamic in terms of variable names.
library(tidyverse)
library(shiny)

eqn_df <- tibble(
    id = 1:3,
    label = c(" *  + <C>", " +  + <C>", " -  + <C>"),
    func = list(
        \(A,B,C) A*B+C,
        \(A,B,C) A+B+C,
        \(A,B,C) A-B+C
    )
)

values_df <- tibble(
    id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
    var = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
    value = c(5,3,10,2,4,NA,7,5,NA)
)

ui <- fluidPage(
  selectInput("eqn", "Select Equation", choices = set_names(eqn_df$id, eqn_df$label)),

  numericInput("var_A", "Choose A", 0),
  numericInput("var_B", "Choose B", 0),
  numericInput("var_C", "Choose C", 0),

  textOutput("result")
)

server <- function(input, output, session) {

    observe({
        values_df |>
            filter(id == input$eqn) |>
            transmute(inputId = paste0("var_", var),
                      value) |>
            pwalk(updateNumericInput)

    }) |> bindEvent(input$eqn)

    output$result <- renderText({
        req(input$var_A, input$var_B, input$var_C)

        func <- eqn_df |>
            filter(id == input$eqn) |>
            pull(func) |>
            nth(1)

        helper <- tibble(id = str_subset(names(input), "var_"),
                         var = str_sub(id, 5))
        args <- map_int(helper$id, ~input[[.x]]) |>
            set_names(helper$var) |>
            as.list()

        do.call(func, args)
    })
}

shinyApp(ui, server)

Comment: Thanks Michael. I ran this and it works and looks nice. The problem is I have more than 8,000 equations sitting in a database. I tried making a column in the dB to define the functions and wrote them in as you have them here, but I am unable to turn text from a database column into a list of functions. If I were able to do that though, it would still require me to manually write more than 8,000 functions into my dB, so not ideal for me in this application unfortunately. Unless you have any thoughts on how I could more easily tackle the functions list!
Comment: I understand.  There are [some SO answers](https://stackoverflow.com/questions/12982528/how-to-create-an-r-function-programmatically) about converting text to a function.  Perhaps by parsing the text into functions in advance, your Shiny users won't have to wait so long for the parsing on the fly.  Also, it's the only way to verify that all 8000 equations are parseable.
Comment: Separately, I reiterate my suggestion to not use an editable table.  Dynamically create/modify/show the `selectInput`s based on the variables appearing in the user's selected equation.
Answer: Do you require the "UserValue" column to be an input?
If not, here's quick and dirty way to give you a jump start to what you want. Without re-writing too much of the app - I've set the InteractiveTable to be editable.
In the example below, technically all cells are editable but you can change that to only specify the "User_Value" column.
Upon double clicking the cell in that column, you can add a new value which can be retrieved by input$InteractiveTable_cell_edit. Then you can update the table with the new value and perform you calcs.
That portion is performed here:
# Update the DT with the new user entered value
if(!is.null(input$InteractiveTable_cell_edit)) {
   new_data = input$InteractiveTable_cell_edit
   df2[new_data$row, new_data$col] = as.integer(new_data$value)
}

Ex:
library(shiny)
library(DT)
library(stringr)
library(dplyr)

df1 = data.frame("ID" = c(1:3), "Equation" = c(" *  + <C>", " +  + <C>", " -  + <C>"))
df2 = data.frame("Equation" = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                 "Variable" = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
                 "Value" = c(5,3,10,2,4,NA,7,5,NA))
df3 = data.frame("Premise" = c("Red", "Yellow", "Green"),
                 "Value" = c(5,4,3))

ui <- fluidPage(
  selectizeInput("df1Select", "Select Equation", choices = df1$Equation, multiple = TRUE, options = list(maxItems = 1)),
  h3("This is the static table of the variables as defined"),
  dataTableOutput("StaticTable"),
  br(),
  htmlOutput("CalcResultStatic"),
  h3("Here, I want to be able to manipulate the fields and recalculate the results"),
  dataTableOutput("InteractiveTable"),
  br(),
  htmlOutput("CalcResultInteractive"))

server <- function(input, output, session) {

  ### Filter Data
  StaticTableFiltered = reactive({
    EqSelect = if(is.null(input$df1Select)) unique(as.vector(df1$ID)) else df1$ID[df1$Equation == input$df1Select]
    filter(df2, Equation %in% EqSelect)})

  ### Render Static Table
  output$StaticTable = renderDataTable({
    if(is.null(input$df1Select)) return(NULL) else {StaticTableFiltered()}},
    options = list(dom = 't'), selection = "none")

  ### Render Static Result as Text
  CalculateResultStatic = reactive({
    if(is.null(input$df1Select)) return(NULL) else {
      ### Define algorithm
      CalcEq = paste(input$df1Select)
      ### Make list of input variables
      Variables = as.data.frame(str_extract_all(input$df1Select, "<(.*?)>"))
      colnames(Variables)[1] = "Vars"
      ### Remove < > from algorithm and assumptions
      CalcEq = gsub("<","",gsub(">","",CalcEq))
      Variables$Vars = gsub("<","",gsub(">","",Variables$Vars))
      ### Get values from Assumptions table
      Variables = merge(Variables, df2[df2$Equation == df1$ID[df1$Equation == input$df1Select],], by.x = "Vars",  by.y = "Variable", all.x = TRUE, all.y = FALSE)
      ### Convert variables to list
      Variables.List = as.list(Variables$Value)
      names(Variables.List) = Variables$Vars
      ### Evaluate equation on list
      eval(str2lang(CalcEq), envir = Variables.List)}})

  output$CalcResultStatic = renderUI(HTML(paste("",CalculateResultStatic(), sep = "")))

  ### Render Interactive Table
  output$InteractiveTable = renderDataTable({
    if(is.null(input$df1Select)) return(NULL) else {
      data = StaticTableFiltered() %>%
        rename(User_Value = Value)
    }
  },
    selection = "none", escape = FALSE, editable = TRUE, # make dt editable
    options =
      list(
        preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } '),
        dom = 't',
        processing = FALSE))

  ### Render Interactive Result as Text
  CalculateResultInteractive = reactive({

    if(is.null(input$df1Select)) return(NULL) else {
      ### Define algorithm
      CalcEq = paste(input$df1Select)
      ### Make list of input variables
      Variables = as.data.frame(str_extract_all(input$df1Select, "<(.*?)>"))
      colnames(Variables)[1] = "Vars"
      ### Remove < > from algorithm and assumptions
      CalcEq = gsub("<","",gsub(">","",CalcEq))
      Variables$Vars = gsub("<","",gsub(">","",Variables$Vars))

      # Update the DT with the new user entered value
      if(!is.null(input$InteractiveTable_cell_edit)) {
        new_data = input$InteractiveTable_cell_edit
        df2[new_data$row, new_data$col] = as.integer(new_data$value)
      }

      ### Get values from Assumptions table
      Variables = merge(Variables, df2[df2$Equation == df1$ID[df1$Equation == input$df1Select],], by.x = "Vars",  by.y = "Variable", all.x = TRUE, all.y = FALSE)
      ### Convert variables to list
      Variables.List = as.list(Variables$Value)
      names(Variables.List) = Variables$Vars
      ### Evaluate equation on list
      eval(str2lang(CalcEq), envir = Variables.List)}})

  output$CalcResultInteractive = renderUI(HTML(paste("",CalculateResultInteractive(), sep = "")))
}

shinyApp(ui = ui, server = server)

Comment: Thanks Jamie. This is pretty cool. It's not my preferred method for a few reasons...
1. It's not obvious to a user that the column takes an input since you have to double click on the field... you'd have to know that functionality is available.
2. In the actual app (not the reprex), whether or not the cell allows input is conditional based on a previous column's value. Do you know if there's a way to make that happen in this method?
Comment: For point 1. Understandable - I agree it's not obvious. However maybe you could add an info box or description explaining that functionality.  For point 2, can you give an example of what you mean?
Comment: In my actual code, the field UserValue is actually defined as `UserValue = ifelse(StaticTableFiltered()$someothercolumn == TRUE, sapply(1:nrow(StaticTableFiltered()), function(i) {sprintf('', i)}),NA),`, so, essentially text inputs are only rendered on certain rows.
Comment: Additionally, when I played with this method, it seems that the table keeps rendering after every change. So if you edited 1 value, then another, the first value would revert back in the underlying table where the math happens but the UI is showing the overwritten value.


Accessing the height of div in javascript

Question: I have a div :
css
    div { width: 200px; height:auto }

markup

 Text is editable

Now what should i do to access the height ( numeric value ) of the above div in javascript ? I tried
$('div').height() & $('div').css("height"); both returns auto.
Comment: Both work fine http://jsfiddle.net/sySFk/
Answer: You may want to try .innerHeight() or .outerHeight(), depending on what you want.
Answer: try using
$('div').innerHeight()

or
$('div').outerHeight()

Answer: Try This
var divs = document.getElementsByTagName('div');
if(divs.length>0)
     divs[0].offsetHeight;

Answer: For returning the NUMERIC height value :
document.getElementsById('myElementId').offsetHeight; // Without jQuery

$('#myElementId').outerHeight(); // With jQuery

Note 1: outerHeight(true) returns the size with margin and padding inclued, more informations on http://api.jquery.com/outerHeight/
Note 2 : innerHeight() returns the current computed height for the first element in the set of matched elements, including padding but not border.
Note 3: $('div').height() or $('div').css("height") returns the css value only.


Omitted Variables and Endogenity

Question: I am currently trying to figure out the problem of endogenity, which occurs when an explantory variable is correlated with the error term. There are apparently different causes for endogenity, but one of the most frequent one seems to be omitted variable bias.
I created a short R-code in order to understand the dynamics of an omitted variable bias and how it would cause the error term to be correlated with the explanatory variable:
<code>set.seed(111)

x1 <- sample(1:20, 100, replace = T)

x2 <- 3 * rnorm(n = 100, mean = x1, sd = 10)

a <- 2; b = 1.5; c = - 3

y <- a + b * rnorm(100, x1, 5) + c * rnorm(100, x2, 5)

my_model <- lm(y ~ x1)

eps <- resid(my_model)

cor(x1, eps)
[1] -1.088585e-16
</code>
So apperently the explanatory vaariable $x_1$ is not correlated with the error term at all, despite an important explanatory variable being omitted.
What am I doing/getting wrong?
Answer: You should not look for the signs of endogenity in the correlation between OLS residuals and the explanatory variables. Because you will never see any correlation and that is because by design OLS residuals and explanatory variables are independent. The idea of OMV is that if you have an important missing variable, it could (will) lead to biased estimators for the remaining explanatory variables. As you can see in your own example, the coefficient of x1 is very far away from its expected value (-6.3 compared to 1.5). on the other hand if you include the omitted variable to the model the estimation would be much closer to their actual values.
<code> set.seed(111)
 x1 <- sample(1:20, 100, replace = T)
 x2 <- 3 * rnorm(n = 100, mean = x1, sd = 10)
 a <- 2; b = 1.5; c = - 3
 y <- a + b * rnorm(100, x1, 5) + c * rnorm(100, x2, 5)

 my_model <- lm(y ~ x1)
 true_model <- lm(y ~ x1 + x2)

 coef1 <- coefficients(my_model)
 coef1

 coef2 <- coefficients(true_model)
 coef2
</code>
Hope it helps
Comment: Hi Masood, Thanks a lot for your answer. It helped me to understand the problem of my thinking. To answer my own question a little bit more precisely, I would put it the following way:

My problem was that I confounded the estimated/emprical residuals with the theoretical/real residuals. While the estimated residuals will never be correlated with the models explanatory variables, since they are, as you said, designed that way, the real/theoretical residuals would be in case of OBV.

So I mixed up empirical and theoretical residuals

Omitted Variables and Endogenity


How can I add a custom part to emails

Question: How can I add create a multi-part email in D7?  I need to add custom part to an email.
I am trying to use hook_mail_alter to append a new content type.  The content type is Content-Type: text/calendar.  I can't figure out where to add it in the $message array.
I have tried mimemail but it seems to disregard my SMTP settings.
Comment: What do you mean by adding part to emails? Which email? User confirmation email, lost password email etc?
Comment: I do agree with @herci , without enough information provided in question , its impossible to answer .
Answer: You could use hook_mail_alter to alter the email message before sending it out. you could change or alter the email body, sender, attachments....etc as you wish
Comment: Yes that is what I am trying to do.  hook_mail_alter gives me access to the message array.  But I don't see how I can add another content type to the message.
Comment: What you mean "add another content type to the message."?
Comment: Emails are composed of different content types: Content-Type: text/plain, Content-Type: text/html, etc. I need add another content type of Content-Type: text/calendar;
Comment: I see, it's a bit confusing becase I thought you are refering to "Drupal content types". anyway according to the API you can change that in the "$headers" param
Comment: Any examples anywhere?
Comment: something similar here [link](http://drupal.stackexchange.com/a/55197/16315) `$headers = array(
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/html; charset=iso-8859-1; format=flowed',
        'Content-Transfer-Encoding' => '8Bit',
        'X-Mailer' => 'Drupal',
    );`

How can I add a custom part to emails


Is there a limit to the key length for localStorage?

Question: Is there any limit (up to the amount of local storage available) for the key when using localStorage?
i.e. can I do something like:
<code>localStorage.setItem("pretend that this is a 1MB string", "whatever");
</code>
Answer: Yes, the limit is 5MB per domain.
Your string can be as long as you want. The total usage must, however, be under 5 MB.
http://dev.w3.org/html5/webstorage/
http://www.stackoverflow.com/questions/2747285/html5-localstorage-restrictions-and-limits
Comment: @ParchedSquid Just tested on IE9, Chromium 30, Firefox 25; the key can have any length, as long as the total size of the key+value pair falls within the boundaries of the storage (approx 5MB). Code used to test: `localStorage.clear();localStorage.setItem(new Array(5e6).join(' '),'');localStorage.key(0).length;`
Comment: The OP was asking about the key length more than the total storage. Those links didn't particularly answer the question. Are you saying key length is infinite, so long as it doesn't exceed the total 5 MB?
Comment: Tested in the `UIWebView` on iOS 8.1 (iPhone 4S) and the limit was **~2.6MB**.
Comment: I tested quickly in FF24 with the same result. Thanks for confirming.


Communication between remote Angular app and Electron desktop app

Question: the scenario is the following:

An Angular app deployed in an external server
Desktop electron app running locally serving a remote url (the one where the Angular is served from)

Is there any way to use electron API to interact with the OS from the Angular app? I do believe IPC will not work since they are not running on the same instance, but I wanted to know if someone can come up with another solution.
Thanks, Javi
Answer: After doing some research it seems feasible to use IPC to and from an Angular app.
Since the Angular app is rendered in a Renderer Process, it's possible to call ipcRenderer module in order to have such communication:
In Main Process in Electron app:
const { ipcMain } = require('electron');

ipcMain.on('customChannel', (event, args) => {
  console.log('event: ', event);
  console.log('args: ', args);
});

On Angular app, on a component:
// Component implementing OnInit

ngOnInit(): void {
 if ((<any>window).require) {
   try {
    const ipc = (<any>window).require('electron').ipcRenderer;
    ipc.send('customChannel', 'this is a test');
   } catch (error) {
    throw error;
   }
  } else {
     console.warn('Could not load electron ipc');
  }
}

Answer: Looks like in above example the remote web application has electron installed. In case some one wants to communicate without having the electron dependency on the web app then we can use contextBridge.
In your electron app
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld(
  'electron',   //This will be exposed as window.electron in your remote app
  {
    doThing: () => ipcRenderer.send('do-a-thing')
  }
)

In your remote app
window.electron.doThing()

Source https://www.electronjs.org/docs/api/context-bridge


Need simple, fast way to store large gobs of xml to a server

Question: Our client software is currently sending large amounts of xml to our SQL Server db, stored as NTEXT, and the db is getting huge and performance is suffering. This xml doesn't need to be indexed, just needs to be persisted somehow to disk. Is there an easy, robust way of
storing this stuff to disk on a remote server? I looked into CouchDB, but I'm sure there is an easier way of doing this. I prefer unix solution, but anything goes.
Thanks!
Answer: I would use rsync and store it as flat files; if you don't need indexing there's no need for a database. That way when you need to add more data to what's there, you don't have to send the entire file over again.
It should be as simple as rsync -avz source/dir/ remote:/path/to/dest/dir, if the remote server has SSH running; the manpage can tell you more (be careful with the closing slash thing, I can help you more with that if I'm given more specific details if you like).
Comment: Thanks, Mickey. Sadly, the client is on windows, so rsync is not available by default. But flat files are a good idea.
Comment: I've had a lot of success using rsync through Cygwin; see [this backup solution for Windows](http://justinsomnia.org/2007/02/how-to-regularly-backup-windows-xp-to-ubuntu-using-rsync/).
Answer: Since there is no need to use SQL features (like XML type in Microsoft SQL Server), I would suggest storing the files directly to the hard disk.
Depending on the context, you can either create a shared directory with write-only access (it was possible in Windows XP, so it is probably possible with Unix solution).
Or if the client software is used outside local network, you can receive XML data through Web services and store it to the hard disk. Or if performance is a major concern, you can use HTTP protocol directly (POST/PUT), instead of using Web services.
Comment: Thanks, MainMa. The client myst connect outside LAN, so web service is the way to go. Or just hit our FTP server.


Required Checkbox Field Has No Effect

Question: I used hook_form_alter to add a required 'confirmation' checkbox to the node deletion form and the #required status is not honored.
The fields/fieldset are property displayed 'node-delete-confirmation' form.
Here is the hook_form_alter content:
$form['warning'] = array(
    '#type' => 'fieldset',
    '#title' => t('Warning! - You Must Check The Box Below To Continue'),
    '#weight' => -30,
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
);
$form['confirm_delete'] = array(
    '#title' => t('I fully understand that this action cannot be undone and that statistics linked to this item will be permanently removed.'),
    '#type' => 'checkbox',
    '#required' => TRUE,
    '#default_value' => 0,
);

How can I enforce the 'required' status so that nodes cannot be deleted until the confirmation is acknowledged.
If I change the code, to completely remove the added fieldset everything works as it should.
Works:
$form['warning']['confirm_delete'] = array(
'#title' => t('I fully understand that this action cannot be undone and that statistics linked to this item will be permanently removed.'),
'#type' => 'checkbox',
'#required' => TRUE,
'#default_value' => 0,

);
Comment: Seems to work if I completely remove the fieldset.  I would still prefer the fieldset as it looks way better.
Answer: You can add your form validation handler (hook_form_alter):
$form['#validate'] = array('delete_validation_handler') + $form['#validate'];

Your validation handler:
function delete_validation_handler($form, $form_state){
    if(!$form_state['values']['confirm_delete'])
        form_set_error('confirm_delete', t('Message about to confirm it first'))
}

Answer: Try this one: http://drupaldeveloper.in/codelet/drupal-make-single-checkbox-required-field
It will always work!
Please note, its for Drupal 6.x, but you can use it for 7.x as well!

Required Checkbox Field Has No Effect


Showing that the identity $(j + k)^2 = j^2 + k^2$ is wrong.

Question:
"For all numbers $j$ and $k$, $(j + k)^2 = j^2 + k^2$."

How would you prove this is wrong??
When I times out the bracket with the number it makes $j^2 + k^2$ but that's wrong.
Should I put a number for $j$ and $k$ and then times it out?
Comment: Are your "2" supposed to be exponents, ie. $(j+k)^2 = j^2 + k^2$?
Comment: @HonkyHanka try to clear (edit) the question so that someone could help you
Comment: What is $j2$? You can format math on this site by following the instructions [here](http://meta.math.stackexchange.com/questions/5020/tex-latex-mathjax-basic-tutorial-and-quick-reference).
Comment: j2 is to j2 ... I don't know?
Comment: I don't know how to and the instructions don't help me much!!!!The 2's are squared...
Answer: Oh ok, well I think I've got a way of prooving it. I'm going to add a number for each letter  j and k...
$j = 1$
$k = 2$
$(j+k)^2=j^2+k^2$
$(2 + 1)^2 = 3^2 =9$ and $j^2 + k^2 = 1^2 + 2^2 = 1 + 4 = 5$ and $5$ isn't equal to $9$!
Comment: A counterexample like this is a fine way to show the equation is invalid.
Comment: Almost any time you have a statement beginning "for all *j*, *k*, …" or similar, and you're asked to disprove it, the best way is to give a specific counterexample, some specific *j* and *k* for which the equation isn't true.
Answer: We develop this product term by term
$$(j+k)^2=(j+k)\times(j+k)=(j\times j)+\underbrace{(j\times k)+(k\times j)}_{=2\times j\times k}+(k\times k)$$
Therefore, we find this identity that you must learn by heart:
$$(j+k)^2=j^2+2jk+k^2$$
hence you can see that $$(j+k)^2=j^2+\underbrace{2jk}_{\text{a term more}}+k^2\neq j^2+k^2\quad\text{unless}\quad 2jk=0\quad\text{i.e unless}\quad j=0\,\text{or}\, k=0 $$
Answer: $(j + k)^2$
If $j = 3$ and $k = 2$
= $(3+2)^2$
= $(3+2)(3+2)$
= $9+6+6+4$
= $25$
However, if we were to say that
$(j+k)^2=j^2+k^2$
then:
= $3^2+2^2$
= $9+4$
= 13
Which means that $(j + k)^2 \neq 3^2+2^2$


counterexample to a proof.

Question: Prove the following statement;
$$\forall a,b \in R (\forall \epsilon > 0 (a \le b + \epsilon) \rightarrow a \le b)$$
I can't see how this is true
This means that I can pick a number for all three variables and this statement should hold, but
Let $\epsilon$ = 100
let b = 0
let a = 1
then $(a \le b + \epsilon)$ holds but $a \le b$ doesn't.
This question is given right after a true/false section, so I'm assuming i'm somehow missing something, and there is a proof for this?? But, right now my reasoning seems sounds, to me.
Comment: I think the inner statement reads "if $a \le b + \epsilon$ for all $\epsilon>0$, then $a \le b$," rather than "for any $\epsilon>0$, the statement $a \le b+\epsilon$ implies $a\le b$."
Comment: It says that if $a\le 10.1$ and $a\le 10.01$ and $a\le 10.000001$, and $\dots$, then $a\le 10$.
Comment: Does this answer your question? [Intuition: If $a\leq b+\epsilon$ for all $\epsilon>0$ then $a\leq b$?](https://math.stackexchange.com/questions/679038/intuition-if-a-leq-b-epsilon-for-all-epsilon0-then-a-leq-b)
Answer: The key is that it needs to be true for ALL $\epsilon >0$.  if $\epsilon < 1/2$ for example and b = 0, a = 1 it is not true that $a <= b + \epsilon$.
Answer: You may be misinterpreting the statement due to ambiguous parenthesization. It is almost certainly meant to be interpreted
$$\forall a, b \in \mathbb R.\ ((\forall \epsilon > 0.\ a \le b + \epsilon) \rightarrow a \le b).$$
The important thing is that the scope of the quantification of $\epsilon$ should stop before the $\rightarrow$. If you think about the difference between $\forall \epsilon. (p \rightarrow q)$ and $(\forall \epsilon. p) \rightarrow q$, you will see why your reasoning doesn't apply to the latter.
Why did I infer that the statement should be interpreted this way? Just because this way the statement is true. Notational conventions seem to vary here, and depending on the conventions in use, it's possible that the statement may be written incorrectly.
Answer: The statement requires that the inequality holds FOR ANY epsilon greater than 0. So if epsilon is less than $1$ this statement does not hold in the case that you mentioned.
This statement can be proven by contradiction is you assume $a\leq b+\epsilon$ and $a>b$.
Answer: The example that you considered a counterexample to the proposition is wrong; for, your choice of $a$ and $b$ does not satisfy the hypothesis of the proposition. If $a:=1$ and if $b:=0$, then $a > b$, so $a > b + \varepsilon$ for some $\varepsilon > 0$, say $\varepsilon := \frac{1}{2}$; but the proposition only considers pairs of $a,b$ such that $a \leq b + \varepsilon$ for all $\varepsilon > 0$.

counterexample to a proof.


Deseasonalize data AND deflate with CPI?

Question: I have property return variables and economic variables that I am using in a VECM/VAR to generate Impulse Response Functions. I have deflated my data with CPI, but do I also have to deseasonalize the data? My results are much better when the data is non seasonally adjusted but deflated with the Consumer Price Index (CPI) to adjust for inflation, than when it is deseasonalized and deflated.
Is there sufficient theory to support the use of non seasonally adjusted data where it is deflated with CPI?
Answer: CPI itself can be seasonally adjusted, for instance the CPIAUCSL series are already adjusted. Just make sure that when mixing unadjusted data you don't introduce the artefacts of the phase and frequency differences.
Imagine, your series A and B are both annual seasonality but one is lowest in July while the other is in January. If you divide A/B you can get weird seasonality effects that are result of the transformation itself. For instance, this may show up like 6 or month seasonality. In this case it's best to deseasonalize series before transformation.
In your case if the series that you're deflating have annual seasonality and CPI is not adjusted, then if you first deseasonalize the series then divide by CPI, your resulting series will acquire seasonality from CPI. That's why simple deflation may seem to work better
Answer: Deflating the data does not exclude the need for seasonal adjustment. If you are using month over month return, I recommend seasonal adjustment. For YoY or 12mo moving average, there is no need.
If you use R, you can check seasonal::seas.


Determinants: divisibility by 6 without remainder and $n\times n$ matrix

Question:
Compute the determinant of \begin{pmatrix}
 1 & 2 & 3 & ...& n\\
 -1 & 0 & 3 & ...& n\\
  -1 & -2 & 0 & ...& n\\
...& ...& ...& ...& \\
-1 & -2 & -3 & ...& n
 \end{pmatrix}
after some elementary raw operation, one can reach:
\begin{pmatrix} 1 & 2 & 3 & ...& n\\
 -2 & -2 & 0 & ...& 0\\
0& -2& -3& ...&0& \\
...& ...& ...& ...& \\
0 & 0 & 0 & 1-n & n
 \end{pmatrix}
but I don't sure how to proceed.
Why the det. of the following matrix is divisible by 6 without remainder?
\begin{pmatrix} 2^0 & 2^1 & 2^2 \\ 4^0 & 4^1 & 4^2\\ 5^0 & 5^1 & 5^2 \end{pmatrix}
So I know that I have to show that its det. is divisible by $2$ and $3$, or equivalently that the sum of its digits divisible by $3$ and last digit is even. But I don't sure how to start the process.

Thank you.
Comment: I don't see the pattern in the first matrix...
Comment: I guess it should be $(1,0,...,0,n)$ on the main diagonal, while beneath there are all negative (real numbers) and above all positive.
Answer: Regarding (2), you can reduce the matrix $A$ modulo $2$ to obtain
$$ A' = \begin{pmatrix} 1 & 0 & 0 \\ 1 & 0 & 0 \\ 1 & 1 & 1 \end{pmatrix}. $$
Clearly, $\det(A') = 0$ which shows that $\det(A) \mod 2 = \det(A') = 0$. Similarly, reducing $A$ modulo 3, we obtain
$$ A'' = \begin{pmatrix} 1 & 2 & 1 \\ 1 & 1 & 1 \\ 1 & 2 & 1 \end{pmatrix} $$
and this implies that $\det(A) \mod 3 = \det(A'') = 0$ which shows that $\det(A)$ is divible by both two and three.
Comment: Consider the definition of the determinant as a sum of products. If you think about it, to calculate $\det A \mod n$, you can either calculate $\det A$ and then do the modulo or you can reduce each element in $A$ and calculate the determinant as a matrix in $M_k(\mathbb{Z}_n)$. The fact that the answers are the same follows from the general properties of modulo with respect to sum and product.
Comment: Can you please give more details on the process of modulo reduction? (For instance, only for $A'$). Thank you!
Answer:
Add the first row to the other rows:
$$
\pmatrix{
 1 & 2 & 3 & 4 & 5 \\
-1 & 0 & 3 & 4 & 5 \\
-1 & -2 & 0 & 4 & 5 \\
-1 & -2 & -3 & 0 & 5 \\
-1 & -2 & -3 & -4 & 5 \\
}
\to
 \pmatrix{
 1 & 2 & 3 & 4 & 5 \\
 0 & 2 & * & * & * \\
 0 & 0 & 3 & * & * \\
 0 & 0 & 0 & 4 & * \\
 0 & 0 & 0 & 0 & 2\times 5 \\
}
$$
So the determinant is $2(n!)$.
The matrix is a Vandermonde matrix and its determinant is $(4-2)(5-2)(5-4)=6$.


Education in years, ordinal or continuous variable?

Question:
I am struggling with figuring out whether the variable "Education in years" should be used as an ordinal variable or as a continuous variable, or would either work? I haven't coded the data myself.
What I would like to do with the 'education' variable is to run a linear regression with it as a dependent variable. My independent variables are gender, age, occupation etc. Would this be possible with the education data I have? What would you suggest?
Answer: The first thing I would do is check out how the variable was coded, even though you didn't do it yourself, and to check out if education in actual years is available.  I also wonder what 1 year of education means (probably it means "less than high school" but ... check it out to be sure).
Next, I'm wondering about some of your proposed independent variables.  Age and gender make sense, but education can't be dependent on occupation (unless you mean parents' education).
As to your actual question, I think education here is best treated as ordinal or maybe even multinomial. There are various models for ordinal dependent variables, but by far the most common is ordinal logistic regression which depends on the assumption of proportional odds.  That seems likely to be violated.
Comment: (+1) But it does make sense to use a regression model purely to *predict* how long someone's spent in formal education from their job. Also, a continuation ratio ordinal logistic model rather than a proportional odds one might be attractive given that people pass through preceding educational stages to reach the next one.


Registrar NS records not pointing to Route 53

Question: I'm having difficulty setting up Route 53 and my registrar settings. I've purchased the domain from InMotion Hosting. On the AWS side, I have my AMI set up with an Elastic IP. I successfully view the landing page (/var/www/html/index.html) when I type the Elastic IP in the browser.
I've set up a Hosted Zone and I see the two auto-created record sets for NS and for SOA. I've also created an A type record set with name of www.example.com and value set to the Elastic IP.
On the registrar site, I can edit what they call the delegation details. There are fields for primary and secondary, set to ns1.inmotionhosting.com and ns2.inmotionhosting.com. Below that are 3 empty inputs, each labeled 'Name Server'. Route 53 provides 4 NS values, so I'm not sure if I delete what's called Primary and Secondary, and use the 4 AWS values and have a leftover NS slot remaining? Or do I keep the default primary/secondary (nsX.inmotionhosting.com) and only use 3 AWS NS values?
Currently I have it set to the latter. When I visit www.example.com, I get a page that says Not Found: The requested URL / was not found on this server. When I visit http://example.com, I get an error that example.com's server DNS address could not be found.
After reading around a bit, I added a directory at /var/www/mysite.com/html and also public_html, putting an index and setting permissions in both.
Now when I visit www.example.com, I get the AMI test page (not my index.html). When I visit http://example.com, I am redirected to a page by InMotion saying the website is unavailable. All the while, visiting the Elastic IP in the browser serves me the expected page at /var/www/html/index.
I also understand I may need to add an alias record set to have the example.com A record point to the www.example.com A record, but I believe I need to get www.example.com working first.
Thanks for the help!
Answer:
Or do I keep the default primary/secondary (nsX.inmotionhosting.com)
  and only use 3 AWS NS values?

No, remove whatever is there by default and populate your domain nameservers with the NS records for your R53 hosted zone.
Comment: Thanks. I used 4 of the 5 spaces with the R53 NS values, and left the other space blank. As far as the default pages, I added an index in /var/www/example.com/ and it's being loaded ok. However, when I go to the Elastic IP, it display the index in /var/www/html/. Is it ok that these aren't the same, or is there a way to have them load the same page (without something like a symlink)? Presumably the site will only be accessed through the domain name, and not the IP, but I want to make sure everything checks out.
Comment: That's a completely separate topic, so I'd recommend that you post a separate question.


What's the use case for a thickness measurement tool in a guitar toolkit?

Question: I purchased a toolkit specifically designed for guitars, and beside the tools I expected, it contained this:

The description lists it as a thickness measurement tool. What thickness would one measure with this on a guitar? Distance between strings and fretboard?
Googling only gave me results about building guitars from scratch, but the rest of the toolkit is basic stuff like Allen keys and a string winder, so I assume there is some more regular use of that tool.
Answer: Those are called "feeler gauges" and can measure all kinds of things. Distance between strings and the fingerboard or the frets is one common use for them. I just used my set yesterday to measure string height at the nut. Another likely place to use them would be string height above a pickup. You could also measure the height of a floating tremolo bridge above the body.
If you're building a guitar, you might want to measure gaps between parts and other small spaces like that.
Comment: With strings above a pup likely to be 2-3mm, you may need a couple of these sets of feeler gauges! My answer from yesterday never landed. Also be aware that feeler gauges come in two distinct sets - metric (as shown) and imperial - in 'thous' - thousands of an inch. Which is how most strings are considered, coming from the States. Not that feeler gauges are any good for measuring strings - I use a set of caliper gauges. - in 1/1000".
Answer: This is for measuring the thickness of the nut slot.
Comment: Oh, I didn't even know the nut was usually a part that would need maintenance, as the one on my guitar is made of metal, so no cutting in. Interesting.
Comment: @crater2150 - should you consider fitting heavier gauge strings, it may be necessary to do a spot of nut cutting. Zero fretted guitars obviate that problem, if the slots are wide enough anyway.


Calculating the probabilty of drawing a specific number

Question: A friend and I got into a small argument the other day, but neither of us are good enough with probability to get a definitive answer.
Say there is game with 100 participants. Each person draws a random number from a bag, the numbers being 1-100. Every person draws one number, and the number is not put back into the bag after it has been drawn. Drawing #1 wins you the lottery, and I have been given the choise of where in the line of 100 people drawing numbers I want to stand.
Question is then, where should I stand to have biggest chance of drawing #1?
We ended up concluding the probability is the same regardless of where in the line you stand, you'll always have a 1/100 chance. We arrived at this answer by using a smaller example of 4 people and 4 numbers. Intuitively though, neither of us could really accept that answer, but we can't really see any other way to look at it.
Comment: Your intuition is good, trusting that the tickets are ordered uniformly at random means that it is equally likely that any given card is in any given position.  Hence your chances are $\frac 1{100}$ regardless of where you stand.
Comment: You are right, assuming that noone knows where number $1$ is placed (which we can safely assume).
Answer: You got the right idea. One way to see why is to calculate the odds of winning for each participant. Let's call the participants $P_1,P_2,\ldots,P_{100}$.
For $P_1$, the probability of winning is $\frac{1}{100}$.
For $P_2$, the probability of winning is $\frac{1}{99}$, if $P_2$ gets to play. $P_2$ only gets to play if $P_1$ loses, and the probability that $P_1$ loses is $\frac{99}{100}$. Hence the probability that $P_2$ wins is $\frac{99}{100}\cdot\frac{1}{99}=\frac{1}{100}$.
For $P_3$ to win, $P_1$ and $P_2$ must lose. Hence the probability of $P_3$ winning is $\frac{99}{100}\cdot\frac{98}{99}\cdot\frac{1}{98}=\frac{1}{100}$.
The probability that $P_4$ wins is $\frac{99}{100}\cdot\frac{98}{99}\cdot\frac{97}{98}\cdot\frac{1}{97}=\frac{1}{100}$.
The probability that $P_5$ wins is $\frac{99}{100}\cdot\frac{98}{99}\cdot\frac{97}{98}\cdot\frac{96}{97}\cdot\frac{1}{96}=\frac{1}{100}$.
For each $P_n$, the probability that $P_n$ wins will be a similar telescoping product that is equal to $\frac{1}{100}$.
Answer: This point is often a source of confusion.
If you like, you can prove it inductively.  Small $n$ pose no difficulty, so suppose we have shown it up to collections of size $n-1$.
Now, you have a collection with $n$ tickets (and one winning one). Draw one from the lot.  The probability that it is the winning one is  $\frac 1{n}$.  If it is not the first choice then you have a collection of $n-1$ tickets with one winning one.  By the inductive hypothesis, the probability that the winning one is in any of the slots numbered $2$ to $n-1$ is now $\frac 1{n-1}$.  Thus, prior to drawing the first ticket, the probability that the winning one was in a specifed slot between $2$ and $n-1$ was $$\frac {n-1}n\times \frac 1{n-1}=\frac 1{n}$$ as desired.


Arrow function's lexical scope not behaving as expected

Question: Arrow functions have a bound lexical scope. So in this code person.person1.sayName() is supposed to output HB but instead it outputs GOT (the global scope). Why is this so?

var name = "GOT";
var person = {
   name : "HB",
   sayName : function() { return this.name },
   person1 : {
       name : "WW",
       sayName : () => this.name
    }
};
console.log(person.person1.sayName());
Answer: Behavior is as expected. Because it's an arrow function, the calling context is inherited from the outer scope (the block in which person is defined, in which this refers to the global object), not from the outer object in which person1 is nested. No calling context is captured when sayName is called, and (possibly nested) object initializers do not create a new scope.


how to use, with active cell.offset 0,-1 and add a word to existing value

Question: I'm trying to do, with active cell offset 1 cell to left and add a word to the end of that existing text. I get an error 91 "object variable or with block variable not set."
Option Explicit

Sub ADD_OPD()

    Dim CELL As Range

    With ActiveCell
        CELL.Offset(0, -1) = CELL.Offset(0, -1).Text & "-" & "OPD"
    End With

End Sub

Comment: try `.Value` instead of `.Text`. Also note that this wont work in column A because the offset would be pointing to nowhere
Comment: you either have to define which cell that `CELL` is supposed to represent or only use `Activecell`. It seems like the latter is what you're looking for, so you'd only have `.Offset(0, -1).Text = .Offset(0, -1).Text & "-OPD"
Comment: So I tried this and it gives me object required:  `.Offset(0, -1).Text = .Offset(0, -1).Text & "-" & "OPD"`
Comment: now works perfect thanks
Answer: You're getting an object error because Range.text is a read-only property. Changing to Range.value should solve part of the problem.
The other issue is that you're not setting the value of the CELL range that you created. However, you can just throw out the CELL object because you can just reference the ActiveCell using the with statement you already have, like so:
Sub ADD_OPD()
    With ActiveCell
        .Offset(0, -1).Value = .Offset(0, -1).Value & "-" & "OPD"
    End With
End Sub


C++ compiler gives unitialized variable warnings when declared in if-else statements

Question: I'm sure there's an easy explanation for this, but I have some code like this:
  RoutingTablePoolEntry rtpe;
  RoutingTablePoolEntry* rtpePtr;

  if (rtpeItr == m_rtpool.end()) {
    RoutingTableEntry* routeEntryPtr = m_nlsr.getRoutingTable()
      .findRoutingTableEntry(destRouter);

    if (routeEntryPtr == nullptr) {
      RoutingTablePoolEntry rtpe(destRouter);
    }
    else {
      RoutingTablePoolEntry rtpe(*routeEntryPtr);
    }

    RoutingTablePoolEntry* rtpePtr = addRtpeToPool(rtpe);
  }
  else {
    RoutingTablePoolEntry* rtpePtr = &(rtpeItr->second);
  }
  doSomeStuffWithRtpe()

EDIT: Here is some real code. Is the error still variable scope? I realize in the example it was, but is that still the problem here? I tried conditional initialization of the form:
RoutingTablePoolEntry rtpe(routeEntryPtr == nullptr? ... : ...); but that didn't seem to cooperate too much either.
EDIT #2: I'm an idiot, excuse me. The reason is abundantly clear and I just wasn't seeing it.
rtpe = RoutingTablePoolEntry(destRouter) and
rtpePtr = &(rtpeItr->second)
in the slim chance anyone makes this gaff, too.
Comment: Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Note that `doThing` won't see neither of `object` declared in your code because they are out of scope.
Answer: Each object declared in the statements following the if and else has the scope of these statements. After the if-else statement the object is not visible and alive.
Answer: your variables are local to the if-statement. Probably you have a previous declaration of object, which is not initialized because is not used. In this situation, you get a warning, without any previous declaration of this object, you get an error.


Different HC3 standard error estimates when normalising weights for weighted least squares fit using Python statsmodels

Question: When I normalize the weights I use for fitting a line with weighted least squares, the parameters of the fitted line and the 'normal' standard errors stay exactly the same, as I would expect.
The HC3 standard error estimates, however, change completely.
I get the feeling that I am missing something quite important here, but... well, I am missing it...
Here is some test code in Python:
import statsmodels.api as sm
import numpy as np

myData = np.array([1, 1, 2, 2, 3, 3, 4, 4], dtype=float)
myIndex = sm.add_constant(range(len(myData)))

myWeights = np.array([100,10,100,10,100,10,100,10], dtype=float)

fit1 = sm.WLS(myData, myIndex, weights=myWeights).fit()

print "Parameters: %s" % fit1.params
print "Normal standard errors: %s" % fit1.bse
print "HC3 estimates: %s" % fit1.HC3_se

# Normalise the weights
myWeights /= myWeights.sum()

fit2 = sm.WLS(myData, myIndex, weights=myWeights).fit()

print "Parameters: %s" % fit2.params
print "Normal standard errors: %s" % fit2.bse
print "HC3 estimates: %s" % fit2.HC3_se

Which produces:
Parameters: [ 0.9796748   0.49186992]
Normal standard errors: [ 0.09876738  0.02581648]
HC3 estimates: [ 0.00976334  0.00314918]
Parameters: [ 0.9796748   0.49186992]
Normal standard errors: [ 0.09876738  0.02581648]
HC3 estimates: [ 44.54587593   0.75750668]

Comment: This looks strange to me. Have you tried with some other data or software? I don't read python but I've tried to reproduce this result in R and cannot do so.
Comment: Stackoverflow won't let me post as an answer for some reason, but I cannot reproduce this with current master. What version of statsmodels are you using?
Comment: This is not supported in statsmodels 0.5. `HCCM matrices are only appropriate for OLS` documentation for HCxxx http://statsmodels.sourceforge.net/stable/generated/statsmodels.regression.linear_model.RegressionResults.html
Answer: Different browser let's me post an answer now...
What version are you using? I can't reproduce this with current master. Probably best to post these kinds of issues to github in the future.
https://github.com/statsmodels/statsmodels/issues
Parameters: [ 0.9796748   0.49186992]
Normal standard errors: [ 0.09876738  0.02581648]
HC3 estimates: [ 0.06187963  0.02651504]
Parameters: [ 0.9796748   0.49186992]
Normal standard errors: [ 0.09876738  0.02581648]
HC3 estimates: [ 0.06187963  0.02651504]

Version
[~/]
[3]: sm.version.full_version
[3]: '0.6.0.dev-3396b98'

Comment: OK, thanks! I've got version 0.5.0. Seems like quite a serious bug if this is really it. Anyway, thanks again, I'll check!
Comment: Indeed, upgrading to '0.6.0.dev-c65f584' solves it.
Comment: From the docs "HCCM matrices are only appropriate for OLS." Granted, we should've at least raised a warning for use after WLS. We need to update the docs now that they're right for weights.
Comment: Do you mean that HCx estimates actually do not work at all for WLS?
Or just not in statsmodels 0.5.0?
As in: the ones returned for the WLS fit in 0.6.0 do make sense??
Comment: Just in statsmodels 0.5.0. The ones in the development branch should be correct, but I'd double-check yourself until there's an official release. They're almost certainly correct, but we need to do a bit more testing before the next release.
Comment: OK, thanks!

Well, in general, the values do look a lot more like what I'ld expect. Though it does happen that sometimes the HC3 standard error estimates are in fact smaller than the normal standard errors. Which is not, I think, what you would expect. Or is it?
Comment: And not just for the intercept, I mean...


Java : Converting colored image to monochrome and keep text readable

Question: I am working on a project in which I am planning to use tesseract OCR to extract text from given image. When I provide monochrome images, then Tesseract does not have much problem.
Colored images are however a completely different scenario. I get mostly garbled text out of it. So I thought of converting to image to monochrome and then passing it to Tesseract. Unfortunately my efforts of conversion have not yielded any satisfactory results.
The image is getting converted to monochrome, but the text is somehow getting screwed(can't think of an appropriate word). Even I was unable to read the text properly, how can I expect the program to?
So the main problem I am facing is, how can I convert a colored image to monochrome in Java where text is not screwed(again).
Our project runs on Linux server, so if there are any scripts or some other programs, which I can call from Java and get result back is also okay. But I would prefer in Java.
Here is the code I have :
 @Override
    public void testOcr() {
        ITesseract instance = new Tesseract();
        File imageFile = new File("/home/username/other.jpg");
BufferedImage img = null;
            img = ImageIO.read(imageFile);

            BufferedImage blackNWhite = new BufferedImage(img.getWidth(),img.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
            Graphics2D graphics = blackNWhite.createGraphics();
            graphics.drawImage(img, 0, 0, null);
            File outputfile = new File("/home/username/other1.jpg");
            ImageIO.write(blackNWhite, "jpg", outputfile);
   instance.setDatapath("/usr/share/tesseract-ocr/");
            // ISO 693-3 standard
            instance.setLanguage("deu");
            String result = instance.doOCR(outputfile);
            System.out.println(result);
}

Both images :

Converted image :

Here is what I got back from Tesseract for above :
90/(/a —'Ä(l/énÄ ' ß(l(1(»m]«u
"" "'""" " "" "" "'""" "" n 00 w—v """ s 3 na
'"''';' J';;Mt:.' *' " '"*;;131:"'r"':1 " . A "" "" _ «3 uu
"" "."""\ "" "" uu """"\"..\ ; 5 oo " ' " "' '* '=* —" "°
"..."."". "' '"' "" ""-".."'""'»  3 — "».>' ' z«""«."«""" <3(m
' ')\'ia "' " l' '""".""\_ "rm
.".'\ ' . \. .
'. '".'.A _ \ " " "*°'Ä' ""w""m"»v.. mm
; ' \ :« ' 4 ' _.
»"9 » @ We have Spema\smr
' Lunch & D\nner ew3rydav
' ßm/n'/ '0(*JJP1/'
V\S\\ Cur '<'e3\au\an\ '
?""':'"1"1C1" 55"" ::'':J:'.J'.'t':';1f:.1?t" "" Fur6'2a:'z:'e '
.."".'"'".""'".." ' s7uu x."".""..".'<h".""" ;7uu Eng\gnCp -
5::r'Ja'.'7r"x:1f'."'3:l'_"" "" '°°° @ us '
".".."'" """'"' " uu m."""< """" sB 00 \23'g5f" 78% .L
—

So, any suggestions on how to improvise reading of colored images. Thank you.
Comment: Is the input image given in *this* resolution, and *not* a higher one? Then it will be difficult. (The smaller text is hard to read even in the input image now...)
Comment: @Marco13 : This is just a test image. Width : 700pixels, Height : 542 pixels. Type : JPEG. But even if that is correct, the big text is also not identified as seen from the output.
Comment: I think the approaches that can be used here will also depend on the size of the input image. So how large is this image in the **real** application case? And can you provide/add an image that is as large as the images that you actually want to process?
Comment: @Marco13 : Unfortunately, use-case does not involve specific size images. Best possible translation is what I am looking for. I agree there will be some mistakes for large text and weird font text, but that's acceptable. But basic functionality should work.
Answer: You can use OpenCV for binarisation. But; teserract still needs resizing if you want proper result for this example.
This order should work fine.

Additional image process operations(denoise, deskew, unsharp, crop, border)
Resize image
Binarize image
OCR
Comment: Why is resizing necessary, I fail to understand that part. Shouldn't Tesseract scan the image pixel by pixel and determine characters in those pixels? Can you tell me any way how I can club tasks 1 and 3 somehow.
Comment: 1) You can use OpenCV `threshold` method for binarisation. **OTSU** threshold can be good choice for binarisation. You can use OpenCV in Java.

2) For this part, there is no certain solution. You need to try different methods and see which methods works for you.

3) Teserract works best if font size is about 12 pt. If texts are smaller than 12 pt, enlarging can improve performance.


How to keep going in the fugue

Question: So I decided to start over my fugue writing. I had a good subject but it was overwhelming to compose it and I forgot so much about the fugue that I am restarting it.
I have been doing all these things to make writing a fugue easier:

Studying counterpoint(crucial)
Listening to Bach's fugues
Listening to analyses of Bach's fugues
Trying to analyze at least 1 fugue myself(figured that fugue in C minor WTC I would be a good start, simplest fugue of the bunch)
Composing
Looking at other people's analyses of Bach's fugues

So it seems I am very well prepared for composing a fugue, not just in the general sense but in the baroque style as well(which is a style I otherwise tend to avoid, most of my pieces are classical or romantic style). But here is what happened with my fugue in C minor which I don't plan on coming back to:
Fugue in C minor history
I was improvising on the keyboard when all of a sudden, I hit what I thought was a good subject. So I did every possible development to just the subject starting with stretto. It worked with every development. But I thought "That is just 2 measures, I should probably expand this melody at least to 4 measures"
The countersubject also came to me very fast. But once I got to the free counterpoint, it was like I entered a vast musical fog. Thousands if not millions of viable fugues. Some triple fugues, some short fugues, etc. But once I got past the question of "How am I going to get past this musical fog", a lot of other questions came to me like "Do I want to change dynamics" and "What ornaments to add" and "Do I want a Picardy third?" and lots more. It was just overwhelming. So I took a break and focused more on sonatas for a while.
I forgot I was working on the fugue but I had an idea of what to do. I composed for a while and reached another point of composer's block. It wasn't until I looked at it carefully that I realised I broke a rule of counterpoint, to not have parallel octaves when there are just 2 voices. This rule I find the easiest to break and my thoughts on the subject and countersubject often lead me to not just octaves but parallel octaves.
I took another break, months this time. I then looked at my fugue and thought:

I wish Bach were here. He could tell me exactly what was wrong and how
  to fix it. He would practically be analyzing every time he looks at my
  works because he is such a calculative composer and wrote a lot of
  fugues. But all I have is his music. And it isn't like I can get into
  Bach's shoes and look at my fugue the way Bach would unlike how I can
  easily be in Mozart's or Beethoven's shoes.

I then said "Rest in peace" to my fugue in C minor and decided to start over my fugue writing.
So, is there anything besides what I'm doing that will make writing a fugue easier? It is like I have 2 things going on at the same time. Bach, in my head is like "Listen to my fugues, keep going with yours, you won't know until you finish it whether or not it is a good fugue". Beethoven, in my head, though is like "Fugues are mostly irrelevant as a genre these days, it isn't like sonatas which while few are composed these days, they are still relevant. You would be better off writing a sonata. Still involves melody in both hands but not nearly as complex as a fugue in terms of counterpoint."
And it is like they are in a tug of war and while Bach wins for a while(which corresponds to me composing my fugue), eventually Beethoven wins(which brings me away from my fugue for a long time).
Is there anything I can do besides what I am already doing to make writing a fugue easier?
Comment: I would suggest that if you're prone to writing parallel octaves then a fugue is ambitious. First you would have to comfortable with writing chorales and two part inventions.
Comment: Have you watched [this](https://www.youtube.com/watch?v=ZlwKH5xiINE&list=PLwId08CT_exogL5pG4c6jNm4WYtntWa-q)? I feel it's one of those gems youtube is great for. Glenn Gould giving you an analysis on fugues. For free.
Answer: My composition teacher suggested using bits of the subject for use during the episodes. This will reduce the overwhelming number of choices.
As far as whether fugues are useful to write: the short answer is yes. Even if you don't write another fugue, the discipline in counterpoint will be very useful. Beethoven struggled with counterpoint, according to the author of Beethoven: Anguish and Triumph, so it seems he would have a bias against fugues. Another aspect of doing fugues (especially if you discipline yourself to write several) is that the counterpoint becomes more intuitive and faster to do. Counterpoint is like math. You might understand the concept, but you won't be able to solve the problems quickly without practice.
I assume you have already written simpler contrapuntal forms, like minuets and inventions? If not, maybe start with those.
Answer: The more fugues you play, the more often Bach will visit you while improvising.  Also, try the retrograde inversion.

How to keep going in the fugue


Can the harmonic function $u$ in $U$ be extended continuously to $\overline{U}$?

Question: Suppose that
\begin{equation}
u(z)=\arg \frac{1+z}{1-z}
\end{equation} is harmonic in the unit disk $U$. Can this function be extended to a continuous real function on $\overline{U}$? I guess it can be, but I don't know how to prove it. Please help!
Comment: If you give the precise formula for $u$, then there isn't any need to "suppose" that it is harmonic, right? Either it is, or it isn't.
Comment: @Calvin I guess the supposition is more about the properties applied to $U$ than to the map $u$?
Answer: The answer is no because at $z= \pm 1$ there are $\pi$ jumps. Assume we take the principal branch of the argument with values in $(-\pi, \pi]$ (if we take the branch with values in $[0, 2\pi)$ same applies except that the values in cause will be $\pi/2, 3\pi/2$).
An easy way to see this is to note that if $z=e^{it}, -\pi \le t \le \pi$ we have $\frac{1+z}{1-z}=\frac{1+e^{it}}{1-e^{it}}=\frac{2 \cos t/2 e^{it/2}}{-2i \sin t/2 e^{it/2}}=i \cot t/2$ so the argument switches from $-$ to $+$ precisely at $t =0$ and since the function is purely imaginary, this means that $u(e^{it})=-\pi/2, -\pi \le t < 0$ and $u(e^{it})= \pi /2, 0< t \le \pi$ (where the extension at $-\pi= \pi$ (mod circle) is by continuity of course so there are left and right hand limits there too)
As an aside the above shows that $u(z)$ (interpreted using the principal branch with values in $(-\pi, \pi]$) is the solution to the Dirichlet problem on the circle with data that is $-\pi/2$ on the lower half-circle and $\pi/2$ on the upper one


iOS: how to assign the app background to UIView at runtime

Question: "A" is the color of the View controller and "B" the color of the UIView containing the UIView I need to modify, called "C".
So I can't use [UIColor clearColor] because it has an other parent in the middle with different color. This view must have the background color of the UIViewController at runtime.
Something like this,
    [cview setBackgroundColor:(self.window.backgroundColor)];

(it doesn't exist a self.window field, where self is the viewcontroller)
Comment: sorry -- don't quite get. you want A to be the Background behind C?
Comment: yes, if A is red and B is blue, C must be red
Comment: but A may be any possible color so I need to modify C at runtime
Comment: see if one of my answers is for you. both acomplish it
Answer: capture A as an IMAGE and set this image as C's backgroundcolor
ios7+
id aImg = [a snapshotViewAfterScreenUpdates:YES];
[c setBackgroundColor:[UIColor colorWithPatternImage:aImg]];

iOS6:
UIGraphicsBeginImageContextWithOptions(viewA.bounds.size, NO, [[UIScreen mainScreen] scale]);
[viewA renderInContext:UIGraphicsGetCurrentContext()];
UIImage *aImg = UIGraphicsGetImageFromCurrentImageContext();
[c setBackgroundColor:[UIColor colorWithPatternImage:aImg]];

Comment: app crashes at runtime, but I'm not sure if the fault is mine or these lines'.
Comment: the code is ios7+ :: if aImg != nil? what os version are you using?


The optimization and regression formulas of Ridge and Lasso: difference between $t$ and $\lambda$ regularization parameters, and contour plots

Question: I have been trying to understand the details in Ridge and Lasso regression and I am having some troubles. For what I know the formula that we want to minimize is the following:

The formula was of the Lasso regression, and so the material that I was reading says:

and here I have one question in the above equation I see lambda, but I cannot see t, or is that:

Also, in the following figure:

For what I know the ellipses are the level curves of the function:

where in the center of the ellipses is the OLS, or the more complex model; and according I get further away from the center of the ellipse the RSS increases. In some material I read, that for example in the Ridge regression, the sphere decreases until the point where it touches the border of the outer level curve, it is like that? Could anybody explain me why one should search for that intersection? Does it has to be the point where the model is less complex, but avoiding maybe a high bias or an underfitting situation?
Please any detailed clarification would be greatly appreciated.
Thank you.
Comment: did the answer below answer your question? mark whichever is best if it does
Answer: There is a one-to-one correspondence between $t$ and $\lambda$ that shows them to be inversely related.
The first formula you showed is the constrained optimization formula of lasso, while the second formula is the equivalent regression or Lagrangean representation. Notice that the off-hand constraint in the first has been absorbed into the objective function in the second. But because of the difference in scales for these two hyperparameters, $t \neq \lambda$ for the same $\beta$ solution.
It is not that $\|\beta\|_1 = \|\beta\|_1<t$, but that decreasing $t$ in the first (constrained) formula has the same effect as increasing $\lambda$ in the second (Lagrangean) formula. And that effect is the shrinkage/regularization of the regression coefficients $\beta$. The one-to-one correspondence between $t$ and $\lambda$ does not have an analytical solution because their values depend on the data itself, but they will always move in opposite directions by design.
As for the RSS elliptical contours touching the ridge sphere in the bivariate case, that tangency point merely is the location that proves that ridge (left-hand plot) is differentiable at $\|\beta\|_q = 0$ for $q>1$ ($q=1$ being lasso), making ridge unable to reduce all the way to $\beta=0$. The upside of this, though, is that it allows an analytical closed-form solution to be derived for ridge, so that optimization is not required.
On the other hand, lasso (right-hand plot), because of its diamond shape in the bivariate case, can reduce to $\beta=0$. The downside of this is that lasso, unlike ridge, does not have a closed-form solution, and must be solved with optimization.
These intersections are of interest because they are the locations where full regularization is achieved, which can be interpreted as lower model complexity because of the lower, or no, weight ($\beta$) being applied to individual variables in the regression through the introduction of bias (via $t$ or $\lambda$) as a means of reducing overfitting


Retain content while deleting user using services

Question: I need to delete a user account using services module & does it fine.
I can see that content(forum) created/updated by the user gets deleted.
Is it possible to achieve below screenshot option via services module in drupal 7?
Answer: Answering my own question,
I have updated the default account setting of when cancelling a user account in the path /admin/config/people/accounts to Delete the account and make its content belong to the Anonymous user
Resolves my query.


Valor nothing em uma consulta a uma tag da xml usando linq .net

Question: Tenho a seguinte xml:
<code><ns1:TRetLote_GNRE xmlns="http://www.gnre.pe.gov.br" xmlns:ns1="http://www.gnre.pe.gov.br">
  <ns1:ambiente>1</ns1:ambiente>
  <ns1:situacaoRecepcao>
    <ns1:codigo>100</ns1:codigo>
    <ns1:descricao>Lote recebido com Sucesso</ns1:descricao>
  </ns1:situacaoRecepcao>
  <ns1:recibo>
    <ns1:numero>1600831117</ns1:numero>
    <ns1:dataHoraRecibo>2016-01-14 14:18:48</ns1:dataHoraRecibo>
    <ns1:tempoEstimadoProc>2000</ns1:tempoEstimadoProc>
  </ns1:recibo>
</ns1:TRetLote_GNRE>
</code>
E estou usando o seguinte código para pegar o valor da tag 'codigo'
<code>   Dim xmlBase As String = retorno.OuterXml
   Dim xXml As XElement = XElement.Parse(xmlBase)
   Dim num As String = xXml.Elements("codigo").Value
</code>
Porém está retornando 'Nothing', pode ser o namespace da xml ?
Answer: É preciso criar uma variável com o namespace e depois concatena-lo junto a tag de busca:
<code>    Dim xmlBase As String = retorno.OuterXml
    Dim xXml As XDocument = XDocument.Parse(xmlBase)

    Dim nspace As XNamespace = "http://www.gnre.pe.gov.br"

    Dim num As String = xXml.Descendants(nspace + "codigo").Value
</code>


Showing the existence of $\int_0^1\sqrt{x}\ln (x)\, dx$ and calculating it

Question:
Show that the integral $$\int_0^1\sqrt{x}\log (x)\, dx$$ exists and calculate that.

To calculate that integral I have done the following :
We substitute $z=\ln (x) \Rightarrow x=e^z$.
When $x=0$ then $z=-\infty$
When $x=1$ then $z=0$
We have that $\frac{dz}{dx}=\frac{1}{x} \Rightarrow dx=xdz=e^zdz$
Then we get $$\int_0^1\sqrt{x}\ln (x)\, dx=\int_{-\infty}^0\sqrt{e^z}z\, e^zdz=\int_{-\infty}^0e^{z/3}z\, dz$$
Is that the correct way to calculate the integral?
At the beginning where we have to show the existence, do we show that just by calculating the integral or is there also an other way to show the existence?
Comment: Where have you calculated the integral -- you still need to show $\int_{-\infty}^0 e^{z/3}zdx$ exists, right?
Answer: By using this substitution, you are using the fact that the map $x \mapsto e^x$ is differentiable with a continuous derivative.
But no, this is not the most efficient way. You may use integration by parts immediately here. The reason is that product of the integral of $\sqrt x$ and the derivative of $\log x$ is readily integrable: $x^{3/2} \cdot \frac 1 x = x^{1/2}$.
You may read about the two topics in depth here: Integration by parts
, and substitution.
Comment: Also the limit of $x^{3/2}\log x,$ when $x\to 0^+,$ exists (and is equal $0$)
Comment: Thank you!! :-)
Answer: You could make it simpler using $x=t^2$
$$I=\int_0^1\sqrt{x}\log (x)\, dx=4\int_0^1 t^2\log(t) \,dt$$ and we know that $\lim_{t\to 0} \, t\log(t)=0$.
Now, one integration by parts to obtain the result.
Comment: This is the simplest and most effective way in my opinion.
Comment: Thank you for your answer!! :-)
Answer:
Then we get $$\int_0^1\sqrt{x}\log (x)\, dx=\int_{-\infty}^0\sqrt{e^z}z\, e^zdz=\int_{-\infty}^0e^{z/3}z\, dz$$

The last step should be
$$I=\int_{-\infty}^0e^{\frac{3}2z}z\, dz$$
you can define: $z=-\frac{2}3u$
$$I=-\frac{4}9\int_0^\infty ue^{-u}du=-\frac{4}9\Gamma(2)=-\frac{4}9$$
Comment: you are most welcome :) @MaryStar
Comment: Thank you!! :-)
Answer: One way to show just existence is as follows:
Note that $\ln(0) = -\infty$ so we need to show that
$$\lim_{c \to 0^+} \int_c^1 \sqrt{x}\ln(x)dx\;\;\text{exists}$$
We can use the fact that $\sqrt{x},\ln(x)$ are continuous on $(0,1]$, so their product is continuous on $(0,1]$
Let $0<a<1$, then by the mean value theorem for definite integrals:
$$\exists k \in (a,1]: \sqrt{k}\ln(k) = \frac{1}{1-a}\int_a^1 \sqrt{x}\ln(x)dx$$
So in the case where $a>0$ we know the integral exists.
Now we need to show that $\sqrt{x}\ln(x)$ is right-continuous at $x=0$.
$$\lim_{x \to 0^+} \sqrt{x}\ln(x) = 0\cdot -\infty \implies \lim_{x \to 0^+} \frac{\ln(x)}{x^{-\frac12}} =  \frac{-\infty}{-\infty}$$
$$ \stackrel{\text{L'Hopital}}{\implies} \lim_{x \to 0^+}\frac{\frac{1}{x}}{-\frac12 x^{-\frac32}}=\lim_{x \to 0^+}\frac{-\frac12 x^{\frac32}}{x} = -\lim_{x \to 0^+}\frac12 x^{\frac12} = 0$$
So it $\sqrt{x}\ln(x)$ is (right)-continuous on $[0,1]$ so by above the integral exists.
Comment: @MaryStar you're welcome :-)
Comment: Thanks a lot!! :-)


Are there series/non-trivial integrals that converge to $e\pi$?

Question: I've tried for hours but I can't really find series representations without explicitly involving either $e$ or $\pi$ within the series expression.
Edit: I am asking this for $e$ times $\pi$, and not for $e$ or $\pi$ like some edits have suggested.
Comment: @NiklasHebestreit Are you sure? For $e\pi$? Could you link me to the article?
Comment: While this may not be exactly what you are seeking but it involves the constant $e\pi$ and infinite series and infinite continued fraction: http://math.stackexchange.com/q/833920/72031
Comment: How about [this?](http://math.stackexchange.com/questions/958624/prove-that-int-01-sin-pi-xxx1-x1-x-dx-frac-pi-e24)
Comment: @nospoon That involves $\pi$ in the integral itself.
Comment: Wikipedia gives a lot of examples. So what _exactly_ is your question?
Comment: Sorry for the confusion. I read $e$ or $\pi$.
Comment: That's alright (:
Comment: @ParamanandSingh Thanks, those were beautiful nonetheless.
Comment: This is also related, although it is "just" a sequence: https://math.stackexchange.com/questions/3637085/is-lim-n-to-infty-frac4na2-n-pi-e-for-a-n2-a-n1-fraca-n2n
Answer: Here's a somewhat unpleasant answer, but an answer nonetheless.
$$ e^x = \sum_{n=0}^{+\infty} \frac{x^n}{n!} \qquad \text{and} \qquad \arcsin x = \sum_{n=0}^{+\infty} \frac{{2n \choose n} x^{2n+1}}{4^n(2n+1)}$$
Let $x = 1$ in both series, and in the second series make sure to scale appropriately ($\arcsin 1 = \pi/2$, so $\pi = 2\arcsin 1 = \cdots$).
Now use the Cauchy product to multiply the two series representations.
Comment: Thanks! I knew this answer would come but I'm not sure this is what I was looking for :P
Answer: Here is one strategy to construct integrals converting to $\pi e$ relatively easily. Basically all we need is a differentiable function $F(t)$ (which does not contain $\pi$ or $e$ in itself) such that $\lim_{t \to t_0}F(t) = \pi e$. Then supposing $F'(x)=f(x)$ we have
$$
\int_0^{t_0}f(x) \,dx = \lim_{t\to t_0} \int_0^{t}f(x) \,dx = \lim_{t\to t_0} F(t) = \pi e
$$
So we just need to find suitable function with limit we want, without containing $\pi$ or $e$ in the function itself. It seems also desirable to find function which has simple derivative, and that is the hardest part... So let's construct one and perhaps better one will come up later. Let's try
$$
F(x)=2 \arcsin x\cdot (2-x)^{\frac1{1-x}}
$$
It is not hard to verify that $\lim_{t\to 1} F(t) = \pi e$ and so we have
$$
\int_0^{t_0}F'(x) \,dx = \int_0^{1}\frac{2(2-x)^\frac1{1-x}}{\sqrt{1-x^2}}+2 \arcsin x (2-x)^\frac1{1-x}\left(\frac{\ln (2-x)}{(1-x)^2}-\frac1{(1-x)(2-x)}\right)\,dx = \pi e
$$
Even though the end result is not very satisfying, it is in principle possible to try other choices for $F(x)$ and try to find something which will look better.
Edit: One can do the similar also for infinite series, we need sequence $a_n$ converging to $\pi e$ with $a_1=0$. Then we have
$$\sum_{n=1}^{\infty} a_n -a_{n-1} = \lim_{k\to \infty} \sum_{n=1}^{k} a_n-a_{n-1} = \lim_{k\to \infty} a_k-a_{0} = \pi e$$
so choosing similarly as above let $a_n = 2\arcsin\left(\frac{n}{n+1}\right)\left(1+\frac{1}{n}\right)^n$ for $n>0$ and $a_0=0$, then
$$\sum_{n=1}^{\infty} 2\arcsin\left(\frac{n}{n+1}\right)\left(1+\frac{1}{n}\right)^n -2\arcsin\left(\frac{n-1}{n}\right)\left(1+\frac{1}{n-1}\right)^{n-1} = \pi e$$


In nodereference field of a content type, Is it possible to show the content type name added with the autocomplete results?

Question: In nodereference field of a content type, Is it possible to show the content type name added with the autocomplete results ?
Example :
I have a content type named Article which has a node reference field (Related content -> field_related_documents), So that this article will referenced to other nodes.
While creating an article, by entering 'help' in 'field_related_documents' I am getting autocomplete results (titles of referenced nodes) like below
helpsystems - rules
Decision management Help
Using help menu
Help support glossary

Instead, I like to show results like below
Page | helpsystems - rules
HelpSystems | Decision management Help
Page | Using help menu
Document | Help support glossary

ie) autocomplete results should display title of other nodes added with their related content type.
How should i achieve this ?
Answer: I created a new custom Module nodereference_patch with below hook
/*
 * Altering nodereference/autocomplete menu using menu alter
 */
function nodereference_patch_menu_alter(&$items) {
  $items['nodereference/autocomplete']['page callback'] = 'nodereference_patch_new_nodereference_autocomplete';
}

Then, I copied the nodereference_autocomplete function into your custom module, changing it's name to nodereference_patch_new_nodereference_autocomplete.
Then I changed this line:
$matches[$row['title'] ." [nid:$id]"] = '
'. $row['rendered'] . '
';

to
$matches[$row['type'] . " | " . $row['title'] . " [nid:$id]"] = '
' . $row['type'] . " | " . $row['rendered'] . '
';

I copied _nodereference_potential_references function from nodereference.module to custom module and renamed it as _nodereference_patch_potential_references
Then I changed the following line as
$references = _nodereference_potential_references_standard($field, $string, $match, $ids, $limit);

to
$references = _nodereference_patch_potential_references_standard($field, $string, $match, $ids, $limit);

I copied _nodereference_potential_references_standard from nodereference.module to custom module and renamed it as _nodereference_patch_potential_references_standard
Then I added 'type' element to $references[]. ie) changed following array from
$references[$node->nid] = array(
    'title' => $node->node_title,
    'rendered' => check_plain($node->node_title),
);

to
$references[$node->nid] = array(
    'title' => $node->node_title,
    'type' => $node->node_type,
    'rendered' => check_plain($node->node_title),
);