Block body translation for Full HTML content

Question: After block creation and put HTML content in body field I can't translate this content because of:

The string blocks:block:1:body for textgroup blocks is not allowed for
  translation because of its text format.

If I change to plain text I can translate block but it is treated as plain text while displaying. Do I have to create another block with the same HTML content (translated) and select to display only in specific language?
Answer: Found it,
http://drupal.org/node/1298440#comment-5127390

In case anyone else has trouble finding this setting, it's at
  Configuration > Regional & Language > Multilingual Settings > Strings
(admin/config/regional/i18n/strings)
Comment: Thanks! I am always looking for this tweak, and your post saves my life everytime ;-)


SELECT * FROM table_name ORDER BY column_name?

Question: ok so i coded in a news section and everytime i insert new news,its shows below the old one.
i want to make it ORDER BY id but make it start like backwards.i dont know how to explain but yeh
i want them to be ordered by the newest added by the id so if the 1st row that was inserted's id is 1 then i want it to show below the next id.
so row with id = 2 will be here
so row with id = 1 will be here
thats how i want it to be, instead of it being like this
so row with id = 1 will be here
so row with id = 2 will be here
.
Sorry for my bad explanation i hope this is understandable
heres my code so far
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id");
while($row = mysql_fetch_array($sqlnews)) {
    $dbdate = $row['date'];
    $dbnews = $row['news'];
    echo "
$dbdate
";
    echo "
$dbnews

";
}
?>

Answer: add DESC in your ORDER BY clause
SELECT * FROM news ORDER BY id DESC

by default, it is in ASC mode.
Comment: `DESC` = Descending (going from higher to lower). `ASC` = Ascending (going up, from lower to higher).
Answer: SELECT * FROM news ORDER BY id DESC
DESC is the descending keyword  ASC is ascending
If you specify neither then default behaviour is ascending
Answer: Just use DESC keyword in your sql query.
Answer: $sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");

However, it isn't really such a good idea to use id, because semantically, there is nothing preventing somebody from changing the sequence which counts up automatically assigning the ID.
Therefore, you should add a column created_at. Everytime you insert a row, you can use the SQL function NOW().
The advantage is that you can say:
SELECT * FROM news WHERE created_at <= NOW() ORDER BY created_at DESC

This means that you can schedule news items ahead of time, and it will automatically display when the date/time arrives!
Answer:    $sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");

Answer: try this:
just have to add
order by id DESC

Answer: Just replace your code by this code:
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
while($row = mysql_fetch_array($sqlnews)) {
    $dbdate = $row['date'];
    $dbnews = $row['news'];
    echo "
$dbdate
";
    echo "
$dbnews

";
}
?>


Show that there is no continuous function f s.t $f=g$ a.e when $g=1_{[0,\infty)}$

Question: So I have to show that there can be no continuous function f s.t $f=g$ a.e when $$g=1_{[0,\infty)}$$
All i know is the following:
$g=0$ for $x<0$ and $g=1$ for $$0\leq x<\infty$$
If f is continuous at f(0) then there must exist a mapping from $(-\delta,\delta)$ to $(f-\epsilon,f + \epsilon)$ for any $\delta,\epsilon > 0$.
I have no idea how to show that this cannot be the case..
Comment: Sure there is. It's called $f : [0, + \infty), f(x) = 1$.
Answer: Assume such an $f$ exists. Then, clearly, $\lim_{x\to-\infty} f(x)=0$ and $\lim_{x\to\infty}f(x)=1$, so there must be some real number $c$ such that $f(c)=1/2$, by the intermediate value theorem.
By definition of continuity and $\epsilon=1/4$, there must be a $\delta>0$ such that on $(c-\delta, c+\delta)$, $f$ takes only values between $1/4$ and $3/4$. In other words, for any $x\in(c-\delta, c+\delta)$, we have $f(x)\neq g(x)$. Since that interval has measure $2\delta$, we cannot have $f=g$ a.e.
Answer: Suppose it is. Then, $m\{x\mid f(x)\notin\{0,1\}\} =0$. By continuity of $f$, $$f^{-1}(]-\infty ,0[\cup]0,1[\cup]1,\infty [)$$
is open (and of measure $0$). Therefore  $$f^{-1}(]-\infty ,1[\cup]1,0[\cup]1,\infty [)=\emptyset$$
and thus $f(x)=g(x)$ for all $x$ what contradict the continuity of $f$.
Answer: Let's prove it by contradiction: assume f exists.
We will get our focus on point 0.
if f exists then because f = g almost everywhere that means that however close you won't come from the minus side, you'll be able to find a point x where f(x) = g(x) = 0 (otherwise there would be an open (-e, 0) on which f is different then g, which is contradiction), so you create a sequence from these points coming to zero
with the same argument but from the right side, you show that there exists a sequence of points that come to zero from the right side (on every each of them f is evaluated as 1.
therefore these are two sequences in which f have different limits and they come to the same point (which is 0). so f cannot be continuous, and that is our contradiction.
Answer: Let $f:\mathbb R\to\mathbb R$ denote a continuous function.
Automatically $f(0)\neq1\vee f(0)\neq0$.
If $f(0)\neq1$ then $f(x)\neq1$ on some interval $(-\epsilon,\epsilon)$ so that $f(x)\neq g(x)$ for $x\in[0,\epsilon)$.
If $f(0)\neq0$ then $f(x)\neq0$ on some interval $(-\epsilon,\epsilon)$ so that $f(x)\neq g(x)$ for $x\in(-\epsilon,0)$.
(In the statements above $\epsilon$ is positive)
In both cases $\lambda(\{f\neq g\})\geq\epsilon>0$, hence $f=g$ a.e. is not true.


Do the hat functions have compact support?

Question: The definition of compact support is that a function is non-zero outside a compact set.
Consider the "hat functions"
$$\phi(x) = \begin{cases} x+1 & -1 \leq x \leq 0 \\ 1-x & 0 \leq x \leq 1  \end{cases} $$
This function is said to have compact support, but it is non-zero on the open interval $(-1,1) $.  Have I misunderstood compact support? Can I reconcile the definition with this example?
Answer: To say it with your own words, the definition of compact support is rather that a function is zero outside a compact set (the contrary of what you wrote).
Here the hat function $\phi(\cdot)$ is zero outside the compact set $[-1,1]$.


Como consigo alterar variável dentro do foreach?

Question: Por favor, como altero a variável $logado  dentro if no foreach ?
<?php

session_start();

$login = $_REQUEST["login"];
$senha = $_REQUEST["senha"];
$logado = FALSE;

$usuario = array(
    "login" => "admin", "senha" => "admin",
    "login" => "admin1", "senha" => "admin1",
    "login" => "admin2", "senha" => "admin2",

);

foreach ($usuario as $user => $value) {
    if ($value === $login and $value === $senha) {
        $logado = TRUE;
        break;
    }
}

if ($logado) {
    $_SESSION['logado'] = true;
    header("location: logado.php");
} else {
    echo '
erro!
';
}
?>

Comment: Seu array `$usuario` tá cagado, você cria duas chaves, na primeira linha, e depois as sobrescreve, nas duas linhas seguintes.
Comment: Redija melhor a sua pergunta, ela não esta clara.
Answer: O que você está fazendo é uma array simples e tentando pegar dois valores distintos onde $value pode ser "login" ou "senha", e como os valores associativos são todos iguais, o foreach irá retornar apenas o último.
$usuario = array(
    "login" => "admin", "senha" => "admin",
    "login" => "admin1", "senha" => "admin1",
    "login" => "admin2", "senha" => "admin2",
);     ↑                    ↑
  mesmos nomes        mesmos nomes

O que você precisa fazer é criar uma array onde cada índice possua uma entrada "login" => "valor", "senha" => "valor" separada:
$usuario[] = array("login" => "ladmin", "senha" => "sadmin");
$usuario[] = array("login" => "ladmin1", "senha" => "sadmin1");
$usuario[] = array("login" => "ladmin2", "senha" => "sadmin2");

E no foreach você verifica "login" e "senha" usando colchetes:
foreach ($usuario as $user => $value) {
   if ($value['login'] === $login and $value['senha'] === $senha) {
      $logado = TRUE;
      break;
   }
}

Então o código ficará assim:
<?php
session_start();

$login = $_REQUEST["login"];
$senha = $_REQUEST["senha"];
$logado = FALSE;

$usuario[] = array("login" => "ladmin", "senha" => "sadmin");
$usuario[] = array("login" => "ladmin1", "senha" => "sadmin1");
$usuario[] = array("login" => "ladmin2", "senha" => "sadmin2");

foreach ($usuario as $user => $value) {
   if ($value['login'] === $login and $value['senha'] === $senha) {
      $logado = TRUE;
      break;
   }
}

if ($logado) {
    $_SESSION['logado'] = true;
    header("location: logado.php");
} else {
    echo '
erro!
';
}
?>

Answer: Vlw dvd!
<?php

session_start();

$login = $_REQUEST["login"];
$senha = $_REQUEST["senha"];
$log1 = FALSE;
$log2 = FALSE;
$c =0;

$usuario = array(
    array("login" =>"ladmin", "senha" => "madmin"),
    array("login" => "ladmin1", "senha" => "madmin1"),
    array("login" => "ladmin2", "senha" => "madmin2"),
);

foreach ($usuario as $user => $v) {
    foreach ($usuario[$user] as $user2 => $value){
        if ($value === $login ) {
            $log1 = TRUE;
        }
        if ($value === $senha ) {
            $log2 = TRUE;
        }
    }
    if ($log1 and $log2) {
        break;
    }

}

if ($log1 and $log2) {
    $_SESSION['logado'] = true;
    header("location: logado.php");
} else {
    echo '
erro!
';
}

?>


Second handler cannot run inside toggle-event

Question: i try to create simple show/hide box using toggle but when box is open the button will change to "-" and when box closed, button will change back to "+"
you can check my jsfiddle here
i try with this code using first and second handler
$(document).ready(function () {
    //default
    $('.content').hide();

    $('#b_1').click(function () {

        $('.content').toggle(function () {
            $('#b_1').prop('value', '-');    //first handler
        },
            function() {
            $('#b_1').prop('value', '+');    //second handler
        });

    });
});

but second handler not working ..
Comment: what makes you think there should be a second handler? according to the docs there's only one http://api.jquery.com/toggle/
Comment: refer here http://api.jquery.com/toggle-event/
Answer: I have seen people using second handler in toggle.. but of what I know there is no second handler in toggle function.. check the docs..(let me know if I am wrong).. if its the toggle-event then it is deprecated in jQuery 1.8 and removed in jQuery 1.9.
Anyway here is how I would do to solve your problem
$('#b_1').click(function () {

 $('.content').toggle('slow',function () {
     if($('.content').is(':visible')){
        $('#b_1').attr('value', '-');
     }else{
        $('#b_1').attr('value', '+');
     }
 });
 });

working fiddle here
Comment: thanks for your answer .. but im refer from here http://api.jquery.com/toggle-event/
Comment: if its the toggle-event then it is depricated in jquery 1.8 and removed in jquery 1.9. .. updated my answer
Answer: Try

Comment: .toggle() is REMOVED in 1.9, use 1.8 or earlier
Answer: Better handle your toggle() manually.
$('#b_1').click(function () {

    var $button = $(this);
    $('.content').toggle(function () {
        var symbol = $button.attr("value"),
            newSymbol = symbol == "+" ? "-" : "+";

        $button.attr("value", newSymbol);
    });

});

JSFiddle.
Answer: You can try this: fiddle
$(document).ready(function () {
    var i = 0;
    $('.content').hide();
    $('#b_1').click(function () {
        if (i == 0) {
            $('.content').toggle('slow', function () {
                $('#b_1').val('-');
                i = 1;
            });
        } else if (i = 1) {
            $('.content').toggle('slow', function () {
                $('#b_1').val('+');
                i = 0;
            });
        }
    });
});


VirtualBox VBoxManage: How can I see the current configuration?

Question: VBoxManage provides some additional configuration possibilities for VirtualBox, for instance activating of symlinks in shared folders (is still not working for me...):
C:\Windows\system32>VBoxManage setextradata "VM_NAME" VBoxInternal2/SharedFoldersEnableSymlinksCreate/SHARED_FOLDER_NAME 1

How can I see the current configuration? E.g. if SharedFoldersEnableSymlinksCreate is set to 1 or not.
Thx
EDIT:
"VBoxManage provides some additional configuration possibilities for VirtualBox" -- that's wrong.
VirtualBox Manual -> Chapter 8. VBoxManage -> Introduction: "VBoxManage is the command-line interface to VirtualBox."
Answer: Is VBoxManage getextradata <VM> enumerate what you're after? --official docs for 'getextradata/setextradata' at https://www.virtualbox.org/manual/ch08.html#idm5419


Recasting column types with a function and a dictionary in pyspark

Question: I have a large dataset with many columns. I want to write a function, using pyspark, which does the following:
-> I define a dictionary with columnnames (values) and datatypes (keys)
-> Look up the columns from the dataframe in the dictionary
-> If a column is found in a category, use the key of that category to cast a columntype
I got the function so far that it does not throw an error, Unfortunatelly, the function does not change the column types. I could not find the mistake. Can someone maybe spot the problem? Thanks :)
import pyspark
from pyspark.sql.types import StringType, IntegerType, ArrayType

# This creates a sample dataframe
simpleData = [("James", "Sales", 3000),
    ("Michael", "Sales", 4600),
    ("Robert", "Sales", 4100),
    ("Kumar", "Marketing", 2000),
    ("Saif", "Sales", 4100)]
schema = ["employee_name", "department", "salary"]
table = spark.createDataFrame(data=simpleData, schema=schema)

# This is the function which is supposed to change datatypes en bulk
def recasting_function(data):
    df = data

    column_types = {
        "StringType()": ["employee_name", "department"],
        "IntegerType()": ["salary"]
        }

    for column in df.columns:
        if column in column_types.items():
            df = df.withColumn(item, df.item.cast(key))

    return df

# Here I apply it to my sample dataset
result = recasting_function(table)

Answer: Notice that item and key in your code are undefined variables, but it doesn't throw any error because the if clause is always False.  Try the code below:
# This creates a sample dataframe
simpleData = [("James", "Sales", 3000),
    ("Michael", "Sales", 4600),
    ("Robert", "Sales", 4100),
    ("Kumar", "Marketing", 2000),
    ("Saif", "Sales", 4100)]
schema = ["employee_name", "department", "salary"]
table = spark.createDataFrame(data=simpleData, schema=schema)

# This is the function which is supposed to change datatypes en bulk
def recasting_function(data):
    column_types = {
        "string": ["employee_name", "department"],
        "int": ["salary"]
        }
    for (k, v) in column_types.items():
        for c in v:
            if c in data.columns:
                data = data.withColumn(c, data[c].cast(k))
    return data

# Here I apply it to my sample dataset
result = recasting_function(table)


Ofuscar parte do background-image, e deixando nítida outras partes

Question: Estou tentando reproduzir este "exemplo" do Dribble, entretanto não estou conseguindo. Meu progresso atual é este (utilizando SCSS), entretanto como pode-se verificar eu dupliquei o background para alcançar esse efeito, para as imagens ficarem alinhadas exatamente uma em cima da outra tive que usar o background-position: center; o que não é o desejado (gostaria de usar a propriedade cover). Como posso fazer esse "efeito" usando apenas uma imagem de background?
Compilando o SCSS para CSS, fica assim:

* {
  margin: 0;
  padding: 0px;
}

#container {
  box-shadow: 0 0 10px #202020;
  width: 800px;
  height: 280px;
  margin: 20px auto;
  background-image: url(https://thumbs.dreamstime.com/b/usa-new-york-panorama-sunrise-71107239.jpg);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: center;
  background-color: darkslategray;
  background-blend-mode: overlay;
  display: flex;
  justify-content: center;
  align-items: center;
}

#main {
  background-color: #fff;
  background-image: url(https://thumbs.dreamstime.com/b/usa-new-york-panorama-sunrise-71107239.jpg);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: center;
  border-radius: 10px;
  width: 80%;
  height: 80%;
}

Answer: Opção 1
Vc pode usar mix-blend-mode:overlay no elemento que está por cima da imagem. Aqui é importante que esse elemento seja na cor branca para o overlay ficar bom, vc pode controlar a intensidade dele com o opacity
OBS: repare que eu mantive o background-blend-mode:color-burn no bg do pai, e também usei o size dele como cover sem problemas.

#container {
  box-shadow: 0 0 10px #202020;
  width: 800px;
  height: 280px;
  margin: 20px auto;
  background-image: linear-gradient(rgba(0,50,50,0.5) 0%, rgba(0,50,50,0.5) 100%), url(https://thumbs.dreamstime.com/b/usa-new-york-panorama-sunrise-71107239.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-blend-mode: color-burn;
  display: flex;
  justify-content: center;
  align-items: center;
  /* box-shadow: 0 0 0px 50px rgba(0,0,0,0.5) inset; */
}

#main {
    background-color: #fff;
    background-repeat: no-repeat;
    background-size: auto;
    background-position: center;
    border-radius: 10px;
    width: 80%;
    height: 80%;
    mix-blend-mode: overlay;
    opacity: 0.9;
}

Opção 2:
Se os cantos arredondados não forem problema vc consegue esse resultado usando um inset box-shadow
Veja o resultado no exemplo abaixo:

#container {
  box-shadow: 0 0 10px #202020;
  width: 800px;
  height: 280px;
  margin: 20px auto;
  background-image: url(https://thumbs.dreamstime.com/b/usa-new-york-panorama-sunrise-71107239.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 0px 50px rgba(0,50,50,0.5) inset;
}

Comment: Muito obrigado Hugo, funcionou!


Answer to sample size calculation is n1 = 2 + n2 = 2, can that be correct?

Question: I have computed a (online) sample size calculation for mean difference between two groups.
The calculation was done with the following data from literature:

The website used for the sample size calculation is: Sample Size Calculator (clincalc.com). This gave the following calculation with the data provided by literature

The results of the calculation was n1 = 2, n2 = 2. Total sample size needed = 4. Im wondering if this can be correct? What should I do different?
Our own dataset consists of only two variables: a) retention measured in Newton for conventional dentures and b) retention measured in Newton for digital dentures. With these variables we would like to conduct a t-test to test if there are significant differences in retention between the two types of dentures.
A pilot was conducted with four observations in total, maybe that helps (?)

The purpose of this study is for educational purposes.
If there is information missing, please let me know!
Thanks in advance!
Comment: That sounds unlikely. What is the actual analysis model ? Also please tell us about all the variables in the model, and what assumptions you have made in the power/sample size calculation.  A summary of your dataset could be useful too. You can edit the question rather than replying to this comment.
Comment: Power should _never_ be computed based on observed differences.  Power is based on the difference you would be embarrassed to miss.
Comment: It is not going to take much to show Group II has a higher mean than Group I.  But I suspect the interesting question is the absolute or relative change "since insertion" and whether that differs between the two groups
Comment: Thanks for your answers! I've edited the question and provided some more information :)
Answer: Given this huge difference in means relative to the standard deviations, that does seem possible.
I couldn't find an R power calculator for a t-test with unequal variances, but I ran a program with the smaller of the two SDs:
<code>power.t.test(n = NULL, delta = 15.99-8.77, sd = 1.61, sig.level = 0.05,
             power = .8,
             type = "two.sample",
             alternative = "two.sided",
             strict = FALSE)
</code>
and got a required N of 2.24 per group.  With your larger SD I got a required sample of 3.89 per group.
But, if your data is similar to what you posted (i.e. three time points) then I doubt that this is the analysis you want to run.


Verify integration of $ \int\frac{\sqrt{2-x-x^2}}{x^2}dx $

Question: This is exercise 6.25.40 from Tom Apostol's Calculus I. I would like to ask someone to verify my solution, the result I got differs from the one provided in the book.
Evaluate the following integral: $ \int\frac{\sqrt{2-x-x^2}}{x^2}dx $
$ x \in [{-2,0}) \cup ({0,1}]  $
As suggested in the book, we multiply both numerator and denumerator by $ \sqrt{2-x-x^2} $. This removes the endpoints from the integrand's domain, but the definite integral we calculate with the antiderivative of this new function will be still the proper integral between any two points of the original domain: we only remove a finite number of points from the original domain and the domain of the resulting antiderivative will be the same as the original domain.
$$ I=I_1+I_2=\int\frac{2-x}{x^2\sqrt{2-x-x^2}}dx-\int\frac1{\sqrt{2-x-x^2}}dx \tag{1} $$
Evaluating first $ I_1 $ by substituting $ t=\frac1{x} \; \text, \; dx=-\frac1{t^2}dt \text: $
$$ I_1=-\frac1{\sqrt2}\int\frac{2t-1}{\frac{t}{|t|}\sqrt{\left(t-\frac14\right)^2-\left(\frac34\right)^2}}dt \tag{2} $$
Substituting again $ \frac34\sec{u}=t-\frac14 \; \text, \; dt=\frac34\sec{u}\tan{u}du \; \text, \; t=\frac{3\sec{u}+1}{4} \; \text, \; u=\operatorname{arcsec}{\frac{4t-1}{3}} $, by considering the sign of $ t $ and $ \tan{u} $ in the integrand's two sub-domains:
a) $ x \in (-2, 0): t<-\frac12 \; \text, \; \frac{4t-1}{3}<-1 \; \text, \; u \in(\frac\pi2,\pi) \; \text, \; \tan{u}<0 $
b) $ x \in (0, 1): t>1 \; \text, \; \frac{4t-1}{3}>1 \; \text, \; u \in(0,\frac\pi2) \; \text, \; \tan{u}>0 $
$$ I_1=-\frac{1}{2\sqrt2}\int3\sec^2{u}-\sec{u}=-\frac1{2\sqrt2}\left(3\tan{u}-\log\left|\tan{u}+\sec{u}\right|\right)+C_1 \tag{3} $$
$$ \sec{u}=\sec\operatorname{arcsec}\frac{4t-1}{3}=\frac{4t-1}{3}=\frac{4-x}{3x} \tag{4} $$
$$ \tan^2{u}=\tan^2\operatorname{arcsec}\frac{4t-1}{3}=\left(\frac{4t-1}{3}\right)^2-1=\frac89\frac{2-x-x^2}{x^2} \tag{5} $$
Considering again cases a) and b):
$$ \tan{u}=\frac{2\sqrt2}{3}\frac{\sqrt{2-x-x^2}}{x} \tag{6} $$
$$ I_1=-\frac{\sqrt{2-x-x^2}}{x}+\frac1{2\sqrt2}\log\left|\frac{2\sqrt2}{3}\left(\frac{\sqrt{2-x-x^2}+\sqrt2}{x}-\frac1{2\sqrt2}\right)\right|+C_1= \tag{7} $$
$$ -\frac{\sqrt{2-x-x^2}}{x}+\frac1{2\sqrt2}\log\left|\frac{\sqrt{2-x-x^2}+\sqrt2}{x}-\frac1{2\sqrt2}\right|+C'_1 \tag{8} $$
Evaluating now $ I_2 $:
$$ I_2=-\int\frac1{\sqrt{\left(\frac32\right)^2-\left(x+\frac12\right)^2}}dx \tag{9} $$
Substituting $\frac32\sin{z}=x+\frac12 \; \text, \; dx=\frac32\cos{z}dz \; \text, \; z=\operatorname{arcsin}{\frac{2x+1}{3}} $:
$$ I_2 = -\int dz = -\operatorname{arcsin}{\frac{2x+1}{3}}+C_2 \tag{10} $$
The final result:
$$ I = I_1 + I_2 = -\frac{\sqrt{2-x-x^2}}{x}+\frac1{2\sqrt2}\log\left|\frac{\sqrt{2-x-x^2}+\sqrt2}{x}-\frac1{2\sqrt2}\right|-\operatorname{arcsin}{\frac{2x+1}{3}}+C \tag{11} $$
The solution provided in the book:
$$ I = -\frac{\sqrt{2-x-x^2}}{x}+\frac1{2\sqrt2}\log\left(\frac{\sqrt{2-x-x^2}}{x}-\frac1{2\sqrt2}\right)-\operatorname{arcsin}\frac{2x+1}{3}+C $$
Comment: The difference between the two solutions is not constant, so one of them is wrong.
Comment: Right, and there is also the difference in the absolute sign for the second term.
Answer: The solution in the book is most certainly a typo, your proof seems fine to me. As a confirmation, Mathematica evaluates the integral to be: $$I=-\dfrac {\sqrt {2 - x -
      x^2}} x + \dfrac1 {2\sqrt {2}}\left[\log\left |4 - x +
        2\sqrt {2}\sqrt {2 - x -
           x^2} \right| - \log |x| \right] \qquad - \arcsin\left (\dfrac
{2 x + 1} {3} \right) + \rm C_1,$$ which is the same as your proposed solution since $$\begin{align}
\log\left |4 - x +
        2\sqrt {2}\sqrt {2 - x -
           x^2} \right| - \log |x|&=\log\left|\dfrac{{2\sqrt{2}\sqrt{2-x-x^2}}+{4-x}}{2\sqrt{2}x}\right|+{\rm C_2} \\ &=\log\left|\frac{\sqrt{2-x-x^2}+\sqrt2}{x}-\frac1{2\sqrt2}\right|+{\rm C_2},\end{align}$$ so they only differ by a constant.
Comment: (2) seems ok to me: $ I1=\int\frac{2-x}{x^2\sqrt{2-x-x^2}}dx=\int\frac{2-1/t}{1/t^2\sqrt{2-1/t-1/t^2}}(-1)\frac1{t^2}dt=-\int\frac{2t-1}{t\sqrt{2-1/t-1/t^2}}dt=-\int\frac{2t-1}{t/|t| \sqrt{2t^2-t-1}}dt $
Comment: @ImreDeák See my edit.


TypeError: Cannot read property 'filename' of undefined

Question: Pretendo guardar o arquivo na pasta uploads e guradar no banco o nome do arquivo.
O console.log() me mostra isso:
{theBook: undefined,
  cover: undefined}
Guarda a imagem na pasta uploads mas não arquiva o nome no BD, vindo como undefined.
Porque estou tendo este resultado?:

TypeError: Cannot read property 'filename' of undefined

Meu arquivo:
eBook.js
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const User = mongoose.model('users');
const requireDir = require('require-dir');
requireDir('../models');
const eBook = mongoose.model('books');
const multer = require('multer');
const uploadConfig = require('../config/upload');

const upload = multer(uploadConfig);
var eBookUpload = upload.fields([
{ name: 'cover', maxCount: 1 },
{ name: 'theBook', maxCount: 1 }
]);

router.post('/add', eBookUpload, async (req, res, next) => {
    var erros = []

    if(!req.body.title || typeof req.body.title == undefined || req.body.title == null){
        erros.push({texto: "Título inválido"})
    }

    if(!req.body.author || typeof req.body.author == undefined || req.body.author == null){
        erros.push({texto: "Autor inválido"})
    }

    if(erros.length > 0){
        res.render("pages/ebooks/create", {erros: erros})
    }else{
        const filename = req.file.filename;
        const newBook = {
            title: req.body.title,
            author: req.body.author,
            genre: req.body.genre,
            publisher: req.body.publisher,
            edition: req.body.edition,
            isbn: req.body.isbn,
            pages: req.body.pages,
            theBook: filename,
            cover: filename,
            type: req.body.type,

        }
        new eBook(newBook).save().then(function(){
            req.flash("success_msg", "eBook adicionado com sucesso!")
            res.redirect("/ebook/galeria")
            console.log(newBook)
        }).catch(function(err){
            console.log(err)
            req.flash("error_msg", "Houve um erro ao salvar o eBook! Tente novamente")
            res.redirect("/ebook/galerias")
        })
    }
});

Comment: Segundo seu código o esperado para o `console.log` não é `{ theBook: undefined,
  cover: undefined }` visto que você está passando como parâmetro a constante `newBook`.

Se entendi bem, sua imagem está sendo salva fisicamente mas as informações no `req.body` não estão sendo preenchidas e por isto você não consegue salvar as informações da constante `newBook` no banco de dados?
Comment: Não, é o contrário... Os dados do `req.body` são salvos no banco e o `req.file` não. Apenas guarda fisicamente na pasta **uploads** e não regista o nome do ficheiro no baco dados nos campos **theBook** e **cover**.
Comment: se entendi corretamente o comportamento é este mesmo. O arquivo é salvo fisicamente na pasta **uploads**. No seu banco de dados você deve criar uma referência para este arquivo salvando seu nome, por exemplo. Os bytes da imagem não ficarão salvas no banco de dados a não ser que você altere seu código e adote uma nova estratégia. Você gostaria de salvar a imagem diretamente no banco de dados?
Comment: Veja se este post te ajuda, caso eu não tenha compreendido bem: https://stackoverflow.com/questions/56359137/how-may-i-upload-file-with-formdata-to-node-js-with-express
Comment: É isso mesmo que eu gostaria, mas no entanto ele não guarda o nome do arquivo no banco de dados. Retorna **undefined**. Tens uma ideia de como melhorar isso?
Answer: O problema é que vc tem um array de files, então seria:
const filename = req.files[index].filename;

Comment: O `index` precisa ser definido, do contrario o seu papel não será especifico. continuaremos tendo mesmo problema de **undefined** ou **not defined**.
Answer: Horácio, o exemplo abaixo é um código que escrevi há um tempo e que funciona corretamente. Retirei alguns pontos que não fazem parte do entendimento. Outro ponto é que se for trabalhar com Array os arquivos devem ser acessados através do req.files ao invés do req.file:
exports.post = async (req, res) => {
    var multer = null;
    try {
        multer = require('multer');
    } catch (ex) {
        // TODO console.error(ex);
        // TODO return res.json();
    }

    var upload = null;
    try {
        var path = require('path');
        var storage = multer.diskStorage({
            destination: function (req, file, cb) {
                // process.env.DIRETORIOUPLOAD = diretório
                // onde o arquivo será salvo
                cb(null, process.env.DIRETORIOUPLOAD);
            },
            filename: function (req, file, cb) {
                fileExtension = file.originalname.split('.')[1];

                // Não faz parte da questão mas estou dando um novo nome para o arquivo
                // físico
                const novoNome = require('crypto').randomBytes(64).toString('hex');
                cb(null, novoNome + path.extname(file.originalname));
            }
        });

        upload = multer({ storage: storage }).fields([
            // O name do input deve ser "anexo"
            { name: 'anexo', maxCount: 1 }
        ]);
    } catch (ex) {
        // TODO console.error(ex);
        // TODO return res.json();
    }

    upload(req, res, async err => {
        if (err) {
            // TODO console.error(ex);
            // TODO return res.json();
        }

        var obj = {
            // Informações postadas além do anexo
            campo1: req.body.campo1,
            campo2: req.body.campo2,

            // Novo nome do arquivo atribuído mais acima
            nomeArquivo: req.files['anexo'][0].filename,
            extensao: req.files['anexo'][0].filename.split('.')[1],

            // Nome original do arquivo
            nomeOriginal: req.files['anexo'][0].originalname,
            mimetype: req.files['anexo'][0].mimetype
        };

        // TODO salvar o "obj" no DB
        // TODO res.json();
    });
}

Mais detalhes sobre a documentação: https://github.com/expressjs/multer
Answer: Depois de muitas semanas de pesquisas, finalmente consegui resolver o problema.
A solução é simples req.files[nome-do-campo][0].filename... Deste modo a implementação ficaria assim:
router.post('/add', accessControl, fileBook, async (req, res, next) => {
var erros = []

    if(!req.body.title || typeof req.body.title == undefined || req.body.title == null){
        erros.push({texto: "Título inválido"})
    }

    if(!req.body.author || typeof req.body.author == undefined || req.body.author == null){
        erros.push({texto: "Autor inválido"})
    }

    if(erros.length > 0){
        res.render("pages/ebooks/create", {erros: erros})
    }else{
        //const { filename } = req.file;
        const newBook = {
            title: req.body.title,
            preface: req.body.preface,
            author: req.body.author,
            genre: req.body.genre,
            publisher: req.body.publisher,
            edition: req.body.edition,
            isbn: req.body.isbn,
            pages: req.body.pages,
            cover: req.files['cover'][0].filename,
            theBook: req.files['theBook'][0].filename,
            type: req.body.type,
            tags: req.body.tags

        }
        new eBook(newBook).save().then(function(){
            req.flash("success_msg", "eBook adicionado com sucesso!");
            res.redirect("/ebook/biblioteca");
            console.log(newBook);
        }).catch(function(err){
            console.log(err);
            req.flash("error_msg", "Houve um erro ao salvar o eBook! Tente novamente");
            res.redirect("/ebook/biblioteca");
        });
    }});


Inputs in material design are not themed

Question: I've got working, buttons, carts, lists, but my inputs are not themed like in the demo here: https://material.angularjs.org/#/demo/material.components.input
Now I've simply copied code from demo, but it's still not working. Here is html:

  <md-toolbar class="md-primary">

      Top Secret Project

  </md-toolbar>
  <md-content class="md-padding">
    <form name="projectForm">
      <md-input-container>
        Description
        <input md-maxlength="30" required name="description" ng-model="project.description">

This is required.

The name has to be less than 30 characters long.

      </md-input-container>
      <md-input-container>
        Client Name
        <input required name="clientName" ng-model="project.clientName">

This is required.

      </md-input-container>
      <md-input-container>
        Hourly Rate (USD)
        <input required type="number" step="any" name="rate" ng-model="project.rate" min="800" max="4999" required>

You've got to charge something! You can't just give away a Missile Defense System.

You should charge at least $800 an hour. This job is a big deal... if you mess up, everyone dies!

$5,000 an hour? That's a little ridiculous. I doubt event Bill Clinton could afford that.

      </md-input-container>
    </form>
  </md-content>

And js:
.controller('View1Ctrl', [function View1Controller() {
        $scope.project = {
            description: 'Nuclear Missile Defense System',
            clientName: 'Bill Clinton',
            rate: 500
        };

}]);

Result: https://i.stack.imgur.com/FEwzD.png
What am I missing?
Comment: Do you have any errors?
Comment: No, console is empty.
Comment: may be you can create a jsfiddle or plunkr ? because seems to be working for me..
Comment: [Here it is](http://jsfiddle.net/Lzgts/134/)
Answer: I had the same problem with the release 0.6
Updating to the master branch (currently 0.7-rc3) did fix the issue with  not being displayed in material style.
I did not search the issue queue, but there might be an answer/bug report.


Comparable Mutual Information and Conditional Mutual Information values

Question: Let's assume we have three continuous or discrete variables, X, Y and Z, for which I want to calculate Mutual Information (MI) and Conditional Mutual Information (CMI). The formulas to calculate this through Shannon Entropy (H) of the distributions for them would be:
MI(X;Y) = H(X)+H(Y)-H(X,Y)
MI(X;Z) = H(X)+H(Z)-H(X,Z)
CMI(X;Y|Z) = H(X,Z)+H(Y,Z)-H(X,Y,Z)-H(Z)

My question is, are these quantities directly comparable? In an operation like:
CMI(X;Y|Z)-MI(X;Y)+MI(X;Z)

If they are not directly comparable, can this be converted into the following formula?
CMI(X;Y|Z)-MI(X;Y)+MI(X;Z) = H(X,Z)+H(Y,Z)-H(X,Y,Z)-H(Z)-H(X)-H(Y)+H(X,Y)+H(X)+H(Z)-H(X,Z)

That simplifies into:
CMI(X;Y|Z)-MI(X;Y)+MI(X;Z) = H(X,Y)+H(Y,Z)-H(X,Y,Z)-H(Y)

Which brings us to the following conclusion:
CMI(X;Y|Z)-MI(X;Y)+MI(X;Z) = CMI(X;Z|Y)

Thank you for any tip!
Answer: I'm assuming by "comparable" you mean something like "you are allowed to add and subtract them" or "these have the same units."
If so, the answer is yes, as long as you use the same logarithm base when you compute the various MI/CMI values. (The units of entropy are generally called "bits" or "nats", or less commonly "shannons" or "hartleys," depending on the base of the logarithm--respectively 2, $e$, 2, and 10.)
Many similar identities are proven or assigned as exercises, for instance, in MacKay's Information Theory, Inference, and Learning Algorithms (Chapter 8), which I highly recommend if you want more intuition for how various entropies behave.
The question of whether estimators of these quantities are comparable is a tougher one, as estimating entropies and conditional entropies can be rather tricky. There are only a couple caveats to this in the estimation setting:

This identity holds for the true mutual information/entropy, but I don't believe it necessarily holds for estimators (it depends on how you're estimating).
If you're estimating each MI and CMI as the sum of a bunch of individual entropies, then the identity will hold since the equations go through just the same way for the estimated CMI as for the true CMI. But if you're directly estimating the (C)MI some other way, then you will need to analyze your specific estimator.
Estimators of different mutual informations/entropies may not be independent, so be careful what assumptions you make about the variance structure of their sums and differences.
Additionally, all estimators of mutual information and entropy are biased, so you need to study the bias properties of their sums and differences as well.
Comment: Ah, I should have realized you were asking specifically about estimation; sorry. I've fleshed out the part about estimation above. I hope it's helpful.
Comment: Thank you! I would vote your answer up but I spent all my reputation for this bounty :-)
You are right: the tricks are two. First, estimators may differ (however, I am using the same algorithm for MI and CMI, i.e. adaptive partitioning). Second, one must use the same logarithm base for estimating the entropies.


Validate user in project that is using OWIN auth middleware

Question: I am building a ASP.NET MVC 5 project that is using OWIN authentication middle-ware.
Part of the application is using Basic (or some custom) authentication. I have user name and password on the server side that I need to validate against the users database storage (this is a standard Visual Studio 2013 project with no changes).
In the past I was using membership provider to validate the user:
Membership.ValidateUser(userName, password)

What do I use in case of OWIN? Should I call SignInManager.PasswordSignInAsync?
Answer: If you using standard mvc project with ASP.Net Identity
It uses UserManager for handling all identity related logic.
The method you need is:
 UserManager.FindAsync(userName,password);

In case of success it returns you a user or null otherwise.
Some great articles about ASP.Net Identity:
http://odetocode.com/blogs/scott/archive/2013/11/25/asp-net-core-identity.aspx
http://odetocode.com/blogs/scott/archive/2014/01/20/implementing-asp-net-identity.aspx
Some articles about owin authentication:
http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown
http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux


Form hidden field doen't keeps its values

Question: I'm creating a form with hidden field, I change the values of that field with jQuery:
function mymodule_form($form, &$form_state) {
    $form = array();

    if (empty($form_state[FIELDS_NUM])) {
        $form_state[FIELDS_NUM] = 1;
    }

    // the form name
    $form[FORM_NEW_NAME] = array(
        '#type' => 'textfield',
        '#title' => t('New form name'),
        '#description' => t("automatically will be prefixed by isrh_form_"),
        '#required' => TRUE,
    );

    $form[FORM_SEND_AUTH_EMAIL] = array(
        '#title' => t('Send authentication email'),
        '#description' => t('If check will set the status field to disabled'),
        '#type' => 'checkbox',
        '#default_value' => 1,
    );

    $form[FORM_EMAIL_TYPE] = array(
        '#type' => 'select',
        '#title' => t('Email type'),
        '#options' => $mailTpls,
        '#default_value' => 0,
        '#description' => t('will be added as field:  Email template  (field_XYZ_email_tpl)'),
        '#required' => TRUE,
    );

    // Build the number of name fieldsets indicated by $form_state[FIELDS_NUM]
    for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++) {

        $isFieldRemoved = isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0;
        //dpm($form_state['values']['field'][$i][FORM_IS_REMOVED]);
        if($isFieldRemoved == 1){
            drupal_set_message("removed field");
        }

        $form['field'][$i] = array(
            '#type' => 'fieldset',
            '#title' => t('Field #@num', array('@num' => $i)),
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
            '#prefix' => '
',
            '#suffix' => '
',
        );

        $form['field'][$i][FORM_FIELD_NAME] = array(
            '#type' => 'textfield',
            '#title' => t('Field name'),
            '#description' => "max 20 characters",
            '#size' => 20,
            '#maxlength' => 20,
            '#required' => TRUE,
        );

        $form['field'][$i][FORM_FIELD_TYPE] = array(
            '#type' => 'select',
            '#title' => t('Field type'),
            '#options' => $fieldTypes,
            '#default_value' => 0,
            '#required' => TRUE,
        );

        $form['field'][$i][FORM_FIELD_REQUIRED] = array(
            '#type' => 'checkbox',
            '#title' => t("Required"),
            '#description' => t("Is this field will be mandatory in web service."),
            '#default_value' => 0,
        );

        $form['field'][$i][FORM_IS_REMOVED] = array(
            '#type' => 'hidden',
            '#value' => isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0 ,
            '#attributes' => array(
                'class' => array('remove-value'),
            ),
        );
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Create form',
    );

    // Adds "Add another name" button
    $form['add_name'] = array(
        '#type' => 'submit',
        '#value' => t('Add field'),
        '#submit' => array('mymodule_form_add_name'),
    );

    return $form;
}

function mymodule_form_add_name($form, &$form_state) {
    // Everything in $form_state is persistent, so we'll just use
    // $form_state['add_name']
    $form_state[FIELDS_NUM]++;

    // Setting $form_state['rebuild'] = TRUE causes the form to be rebuilt again.
    $form_state['rebuild'] = TRUE;
}

The jQuery:
jQuery(document).ready(function($) {

    //if ($(".new-field-wrapper").length > 1) {
        $('.new-field-wrapper .fieldset-legend')
            .append('<input type="button" value="remove" class="remove-button" style="margin-left: 10px;"/>');

        $('.remove-button').click(function () {
            var fieldSet = $(this).closest("fieldset");

            var removeField = $(this).closest("fieldset").find('.remove-value');
            var isRemoved = removeField.val();
            //var textBox = $(this).closest("fieldset").find(':text');
            if (isRemoved == 0) { // need to remove
                removeField.val(1);
                $(this).val("restore");
                //textBox.removeClass('required');
            } else {
                removeField.val(0);
                $(this).val("remove");
                //textBox.addClass('required');
            }

            $(this).closest("fieldset").find(".fieldset-title").click();

        });
    //}

});

This code add remove button to each field set lengend and when it pressed the value of the hidden field became 1.
When I submit the form ("add field button") I never get the 1 value (I checked that with 'Inspect element').
What am I doing wrong?
Comment: Next time, please do not post so much code when the relevant parts are only several lines, it helps to keep people who try to answer motivated (and believe me, seeing dozens of line of irrelevant code can be frustrating to read through)
Answer: From the Form API Reference:

Note that if you plan to use JavaScript to change your hidden
  element's value, you will need to use the #default_value property
  rather than #value.

So you just need to change you line
'#value' => isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0 ,

to:
'#default_value' => isset($form_state['values']['field'][$i][FORM_IS_REMOVED]) ? $form_state['values']['field'][$i][FORM_IS_REMOVED] : 0 ,

Comment: Correct and quick answer!!!!


Intuition of position vs time, and complex numbers

Question: I want to differentiate the following equation to obtain an object's velocity, but I can't figure out how the eqation is actually describing the object's position.
It goes as follows:
$r = (2.0 m + (3.00 m/s)t)i + (3.0 m - (2.00 m/s^2)t^2)j$, where $r = $ position at time $t$, and all quantities are in SI units.
Is $r$ a vector? And how do I differentiate or even integrate it given the complex $j$ and $i$? How do time fit in this cooridinate system?
Comment: $j$ and $i$ are unit vectors (most likely) corresponding to $\langle0,1\rangle$ and $\langle1,0\rangle$, respectively. This makes $r$ a position vector that depends solely on the variable for time $t$.
Comment: Notice that $i$ and $j$ are unit vectors in the $x$ and $y$ direction respectively. It may be more helpful to rewrite $r$ into its components, i.e. $r_x = 2+3t$ and $r_y = 3-2t^2$. Differentiating both will lead to $v_x = \frac{dr_x}{dt}$ and $v_y = \frac{dr_y}{dt}$, i.e., you'll get the horizontal and vertical velocities. Rewriting in vector notation, we have that $v = v_x +v_y = \frac{dr_x}{dt}i +  \frac{dr_y}{dt}j$.
Comment: Thanks! This makes much more sense
Answer: I think that's $i$ and $j$ as in the standard unit vectors in the $x$- and $y$-directions, respectively.  Not as in complex numbers.  The reason I think this is because the scenario involves finding a velocity vector from a position vector, and describing the position in terms of imaginary units $i$ and $j$ is extremely outlandish, if not completely nonsensical.  I think this has nothing to do with complex numbers at all.
So we should really be saying $\mathbf i$ and $\mathbf j$ to indicate they're vectors (and therefore avoid this type of confusion).
Anyway, to differentiate a vector, simply differentiate its components individually.
$$
  \mathbf r(t) = (2 + 3t)\mathbf i + (3-2t^2)\mathbf j
$$
Therefore
$$
  \mathbf r'(t) = (2+3t)' \mathbf i + (3-2t^2)' \mathbf j = 3\mathbf i - 4t \mathbf j.
$$
Integrating works the same way.  Integrate each component independently.  And make sure to add an arbitrary constant vector (a vector with two arbitrary constant components) if your integral is indefinite, which would be unusual for vectors given my experience.  Unusual but not impossible I guess.
Comment: In quaternions we usually have $i,j,k$ as the three imaginary units, but I'm fairly sure this question is not about quaternions.
Comment: @DavidK, ah, yes, quaternions.  Keep forgetting about those.  I updated my answer accordingly, slightly.
Comment: Thanks, @tilper! Normally when I see the units $i$ and $j$ I easily jump to the conclusion it's imaginary units. But is bold formatting indicating vectors?
Comment: @user80556: Yes, in this case, they are the basis vectors.  Note: $i$ and $j$ can both be imaginary units, but either (a) the subject is quaternions, as David K mentioned; or (b) they can both be $\sqrt{-1}$, but in different contexts: $i$ in most cases, $j$ in electrical engineering contexts where $i$ is likely to be used for current (that's another story for another time).
Comment: @user80556, yes, bold formatting such as $\mathbf x$ indicates something is a vector.  But typically when writing by hand, as opposed to typing, vectors will be denoted with an arrow instead of with boldface, like $\vec x$.


Rails: accessing associated models with several degrees of separation

Question: I am a beginner in rails, and I have a question about accessing one model from another model that is associated with several degrees of separation.
Let's say I have these models:
Account has_many Spies
Spy has many SpyRelationships and belongs to Account
SpyRelationship belongs to Listing and belongs to Spy

How would I set up the associations so that I could simply pull all the listings associated with a given Account (via its spies and spyrelationships)? What line of code would allow me to do so, after those associations are setup properly?
Answer: I'm guessing you want to access a listing through a spy?
class Account < ActiveRecord::Base
  has_many :spies
  has_many :listings, through: :spies
end

class Spy < ActiveRecord::Base
  belongs_to :account
  has_many   :spy_relationships
  has_many   :listings, through: :spy_relationships
end

class SpyRelationship < ActiveRecord::Base
  belongs_to :listing
  belongs_to :spy
end

class Listing < ActiveRecord::Base
  has_many :spy_relationships
end

Comment: Ok thanks, I did so here: http://stackoverflow.com/questions/23930789/rails-accessing-associated-objects-that-are-several-degrees-apart . Thanks for your help
Comment: Thank you for this. Actually I am trying to access listings through the account....is that possible?
Comment: Great, thank you. Currently in my listing controller I have the following query....how could I adjust it so that it only pulls the Listings for the current_user ?
      @listings = Listing.search(params[:query], page: params[:page])
Comment: @IsaacYerushalmi This sounds like an unrelated question. You should probably mark this question as done, and post a new question and be sure to show your model arrangement for `current_user` and how it relates to `Listing`


How to calculate the sum $ x + x^2 +...+ x^n$

Question: How can I get the result of this sum:
$$  x + x^2 +...+ x^n $$
Comment: why did you change the question?
Answer: Hint: for any $x \in \Bbb R$ with $x \neq 1$,
$$
1 + x + x^2 + \cdots + x^{n} = \frac{1-x^{n+1}}{1-x}
$$
Comment: I am not sure the result makes sense for $x=1$. The right side is not defined while the left side is $n$. The right side should be extended as a limit for $x=1$.
Comment: @AlexanderVigodner fixed.  We could also have multiplied both sides by the denominator.
Comment: @AlexanderVigodner: The left side is $n-1$  ;-)
Comment: @Stefan Hamcke Well, $n+1$ to be precise :).


how to redirect user to web admin interface of my device?

Question: how to redirect user to web admin interface of my device?
I am using following in my project.

httpd of busybox as http server.
html files/js/css to create web pages.
I don't have any kind of apache like servers.
cgi.
C language and linux.
16 MB FLASH.

User will connect to device via wifi. When the user want to access the internet via wifi then he should be first redirected to my web page.
The research which I have made is: I need captive portal for this. Truly speaking I have no idea how to implement captive portal and what it is. I have found that wifidog,chilispot and Nocatsplash are such kind of captive portals which are free.
After compiling the wifidog I have found that to run that I need iptables. By doing necessary changes in kernel I am at that stage that I can run wifidog. But when I run the wifidog I have to configure in the wifidog.conf. I have try to do that. I have added some parameters like :
<code>ExternalInterface br0,
GatewayInterface br0,
AuthServer {
               Hostname auth.ilesansfil.org
           }
</code>
I have tried to access my board in which wifidog is running using my browser but I am not getting anything related to wifidog. It just gives my admin page.
One thing is there is no master device in my project. All device should work the same way.
Would anyone please help me on this issue?
Comment: Should I give more information about the issue which I am facing?
Comment: Check the [FAQ], it's better to ask specific questions, for example start down the path you think is best, then when you run into a problem you can't solve bring the code and theroy back here.
Comment: I am sorry if I have asked in a wrong way. I am searching the web for this since last couple of days. The thing is I want to redirect the user to specific web page that is of my device.
Comment: Notice that the answer you got from bluszcz says "yes you are on the right track", that's answers your question, but it's not really helpful right? The key from the faq is `•a specific programming problem`. You said just now in the comments that you `want to redirect the user to specific web page that is of my device` so make an attempt at doing that... if you have no idea where to start very clearly define what you want to do and show your research then after you've updated flag the question to be reopened
Comment: I have edited the question and added the research which I have made. After this research I have no idea what to do.
Answer: As far I as understand - yes, you are on right track.
What you need now is AuthPuppy: https://launchpad.net/authpuppy
Comment: I am going to have a 100 devices of its kind. I should use the same firmware on all this devices. should I install it on all the devices?
Comment: I guess you need only one authpuppy share for wifdog
Comment: should this thing be installed on server? I mean I have to create on server which runs this software right? Not on my device because I don't have PHP or sql.
Comment: Yes, you need external server with LAMP stack to install it.
Comment: Thank you. I will work on it. If I get success then I will post the answer on this.


Use twig to style a specific block (unformated list)

Question: I have a block showing a unformated List of fields. Now I would like to use twig to style that block.
I am able to use block--views-block--blockname-block.html.twig to do the outer styling. But I could not get the fields out of the content.
Answer: Not sure to understand what you mean...
Do you want to customize the fields that appear in your block?? If so, Drupal normally provides you with available twig hooks you could use. Yours would probably be field.html.twig.
Exemple : you can customize a menu with menu.html.twig and then customize the links in that menu with links.html.twig
Comment: Thanks. Actually I try to override the `views-view-unformatted.html.twig` template with a specific only showing up on one node but it seems like it won't work.
Answer: Ok I got it. I've already overwritten form templates to add a template suggestion that included the form id. Here's the code :
function hugo_theme_suggestions_form_alter(array &$suggestions, array $variables) {
    if (isset($variables['element']) && isset($variables['element']['#type']) && $variables['element']['#type'] == 'form') {
        $original_theme_hook = $variables['theme_hook_original'];
        $suggestions[] = $original_theme_hook . '__' . str_replace('-', '_', $variables['element']['#id']);
    }
}

Maybe you could reuse this piece of code changing the form by the view, something like YOURTHEME_theme_suggestions_view_alter


NSURLSessionDownloadTask continue downloading even if I kill the App

Question: I am using the NSURLSessionDownloadTask to download a web file.
When I use [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:] to create NSURLSessionConfiguration, I found NSURLSessionDownloadTask continue downloading even if I kill the App.
This is not what I expect, I just want it download in the background. I don't want to kill the app, it's still being downloaded.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"DDDownloader"];
config.timeoutIntervalForRequest = 10;
self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithURL:[NSURL URLWithString:downloadModel.url]];
[downloadTask resume];

I hope that after I kill the app, the app will no longer perform the download task.
Comment: Your requirement is not clear what you want ?
Comment: @wuqh How do you know that URLSession keep downloading if you kill your app ?
Comment: When App killed  you have some time provided by the OS to complete something pending. You may use `applicationWillTerminate` to pause or cancel downloading task
Comment: I want NSURLSessionDownloadTask not to continue downloading when I kill my application.
Comment: @PrashantTukadiya Here's my code that you can test :https://github.com/wqhiOS/DDDownloader. Download a file, kill the app when half of it is downloaded, then open the app later, you will find that the download has been completed
Comment: @PrashantTukadiya The reason  keep downloading is because I use it 、`[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:]`,Use `[NSURLSessionConfiguration defaultSessionConfiguration]` and it won't happen again. But I don't want to use` [NSURLSessionConfiguration defaultSessionConfiguration]`
Comment: Use dataTask instead.
Answer: I have got the general idea now.
I saw the description of [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:] in the apple document:

If an iOS app is terminated by the system and relaunched, the app can use the same identifier to create a new configuration object and session and to retrieve the status of transfers that were in progress at the time of termination. This behavior applies only for normal termination of the app by the system. If the user terminates the app from the multitasking screen, the system cancels all of the session's background transfers. In addition, the system does not automatically relaunch apps that were force quit by the user. The user must explicitly relaunch the app before transfers can begin again.

Because I'm using the close button at xcode to close and restart my app, this is what the apple document says: "iOS app is terminated by the system and relaunched." When an app is closed in this way, the NSURLSessionDownloadTask will not end.
If the user close the app from the multitasking screen, the system cancels all of the session's background transfers.
So my problem is solved!


Custom Table or CCK?

Question: I'm currently working on a project with a new requirement that, in a nutshell, queues submissions from users and submits them them to a remote API:

collects submissions from users (with a form)
each submission points to a record on a remote system (uuid provided by remote API)
each submission has a status (ie: new, accepted, declined)
each submission stores a number of other fields of data
each submission references a node id that already exists in drupal
submissions with a status of "new" are presented to an administrator, who can accept or decline them (the queue)
changes to submissions are audited
submissions are never published as content, as they may contain personal info

Much of the data being stored for each submission is simply for interaction with the remote API. Only a small amount of the data for each submission is for human/administrator eyeballs.
I began architecting the storage for these submissions - basically just a really wide database table with one column that references a node id. The database table will also need to be exposed in Views, so that I can easily build pagable, filterable & sortable html tables. Will also perform some custom bulk operations (View Bulk Operations).
I'm now debating if it would be wiser to use a custom node type with a pile of CCK fields to store these submissions as unpublished nodes, rather than building it all custom. On the downside, I'd have to do a lot of form_altering to get the submissions form to where I want it, and I really don't need a lot of node functionality (workflow, comments, titles, etc, etc). On the plus side, if using nodes+cck the Views integration comes for free, and it's likely quicker to build.
I'm working in Drupal 6, and an upgrade to Drupal 7 is at least a year out - but it's also something I need to consider when making this decision.
Any thoughts?
Answer: Go with CCK.
I've done this in Drupal 5, and I'm doing it again for Drupal 6.  It's really not that hard to get this going.  You gets all kinds of things for free both with CCK and Views.  You already mentioned the benefits for Views, but it's the same for CCK.  You simply create everything you need from the UI, and then export it to a file that gets read during your install hook.
Also, why write your own CRUD?
I'm doing something very similar.  Take a look at my code over at Syndeploy.
I haven't exported the Views code yet, but I'll get there.
Comment: Thanks for your feedback. Interesting project, I'll keep an eye on it. Personally, I've been using Features + SVN to manage the deployment of cck & views with great success.
Answer: Sincerely, I'd build my own tables and information architecture.
You'll end up spending too much time fiddling with external information (cck) rather than actually getting your stuff to work.
Comment: Thanks for your response. I've been leaning this direction. My only concern is that I'll burn too many cycles exposing my tables to Views - however, I'm prepared to take the plunge. Thanks!

Custom Table or CCK?


Find list of strings that matches a pattern that start with a special character « and end with a special character »

Question: Given the text:
«Name» has an account on the bank «Bank Name»
Expected Output: ['Name', 'Bank Name']
I need Regex to get this list of matched strings. Please help me.
Comment: Can you share some code and input data?
Answer: You can match using unicode and replace the unicodes later
Unicode finder

let str = `«Name» has an account on the bank «Bank Name»`

let final = str.match(/\u00AB.*?\u00BB/gu).map(v=>v.replace(/\u00AB|\u00BB/g,''))

console.log(final)

Alternatively you can use exec and get the value from captured group

let str = `«Name» has an account on the bank «Bank Name»`
let final = []
let reg = /\u00AB(.*?)\u00BB/gu

while ((arr = reg.exec(str)) != null) {
  final.push(arr[1])
}

console.log(final)


How to go from this formula to F distribution

Question: I have the following formula.
$$\int_{0}^{\infty} x^{\frac{n-1}{2}-1} (a+x)^{\frac{1}{2} \frac{-n}{2} -v} dx.$$
The quantities $d1 ,d2$ appearing in the pdf of the F distribution are the following.
$$d1=n-1,\ d2=2v.$$
My problem is the term $a$ (which is a constant positive hyperparameter). I want to go from $(a+x)^{\frac{1}{2} \frac{-n}{2} -v}$ to something like $(1+\frac{d1}{d2}x)^{\frac{1}{2} \frac{-n}{2} -v}.$
Answer: The basic idea is to ignore the normalizing constants.  These are factors that might depend on the parameters but don't involve the variable $x:$ they are there solely to make the density integrate to $1.$  In many questions of this sort, they appear complicated and ignoring them is a great simplification.
The pdf for the $F$ ratio distribution is a multiple of
$$x^{d_1/2-1} \left(1 + \frac{d_1}{d_2}x\right)^{-(d_1+d_2)/2}.$$
Factoring out a power of $a,$ your integrand becomes proportional to
$$x^{(n-1)/2-1} \left(1 + \frac{1}{a}x\right)^{-n/4-v}.$$
For general values of the parameters these can be equal as functions of positive $x$ only when the powers $x$ are equal and when both $d_1/d_2 = a$ and the powers of $(1 + (*)x)$ are equal (the "$(*)$" denotes the common coefficient).  Thus
$$d_1/2- 1 = (n-1)/2-1,\ \frac{d_1}{d_2} = \frac{1}{a},\, \text{and}\ (d_1+d_2)/2 = n/4 + v.$$

The first equation tells you $d_1=n-1$ and the second equation implies $d_2 = ad_1.$

We have found the parameters $(d_1,d_2):$ that's the solution. Be careful, though!  Plugging this solution into the third equation gives
$$\frac{n}{4} + v = \frac{d_1+d_2}{2} = \frac{n-1 + a(n-1)}{2} = (n-1)\frac{1+a}{2}.$$
If this doesn't hold for your values of $(n,v,a),$ then you don't have an F ratio distribution: you have something else.
Answer: Hint: For any $a>0$ you have:
$$(a+x)^b
= \Big( a \Big( 1 + \frac{x}{a} \Big) \Big)^b
= a^b \Big( 1 + \frac{x}{a} \Big)^b.$$


What is the default minor scale?

Question: When I search for keys for various songs online I see that it's the minor scale. But they don't say which minor scale.
For example, if I search for "greensleeves key" in google I get back "E minor" https://www.google.com/search?q=greensleeves+key
So my question is what is the "default" minor scale? Is it the harmonic, the natural, or the melodic, or something else? When a website leaves out which type of minor scale, which one do I assume it to be?
Answer: It's not really correct to say that a song is in a "minor scale".  You can say it's in a "minor key".  But melodies in minor keys tend to use a mixture of minor and major sixths and sevenths (Greensleeves does, at least as I know it).  They don't necessarily stick to a single scale throughout.
For the purposes of reading and writing such melodies, you usually use a key signature that allows writing the natural minor without accidentals.  (So, in the case of E minor, the key signature with just F#.)
Also note songs don't necessarily have fixed keys--you can play Greensleeves in any (minor) key you'd like.  Sometimes a song is traditionally associated with one key, but even then individual performers might transpose the song, for example to make it fit the range of their voice better.
Comment: Greensleeves is actually in the Dorian mode. It generally has a raised sixth and lowered seventh. There are some old versions (one in Bukhofzer's book on Baroque music) which also have the ending tonic chord as major.
Comment: Huh.  My totally unscientific approach was to check the first few videos on youtube.  I think they all used a flatted sixth on the first phrase (do me, fa sol, se sol fa, re te).  Then a raised sixth in the B section (te, te, la so fa, re te).  And raised sevenths for leading tones at the end of phrases.  Kind of felt like "minor except that we like to borrow from the major V sometimes" which I thought was pretty standard for melodies in minor keys, but I dunno, maybe also raising the sixth to get a major IV is a more unusual?)
Comment: I like that you connected the 'default' minor scale with what key signature is used and that is the convention for *writing notation* on staff.
Comment: @foreyez - you can play any piece of tonally based music in any key -
 or in between any key for that matter, if you have an instrument capable of doing so, such as a violin. (although some pieces will sound better in certain keys) . The note names will change, but **the relationships between those notes** - that which gives a piece its unique characteristics, does not change across keys. Moving the key of a piece from one key to another is called _transposition_  . Very common for vocalists  to _transpose_  a song from one key to another to match their best range for singing it.
Answer: A minor key is just that - a minor key. Scales associated with a particular key have, unlike the major key, options. You are already aware that there are 4 distinct scales used in minor keys - natural, harmonic, classical melodic, and jazz melodic. All have changes from each other involving only the 6th and 7th notes. the reasons have been aired for a long time - plenty are on this site.
Often, a piece in a minor key will stick to notes from a particular minor scale, but others slide in and out of the available combinations. Bear in mind also that minor will include minor modes, which help muddy the waters.
So the writer cannot say which minor scale a piece is in, because a scale is not a key - in minor. Greensleeves is a particular example, and has two versions (at least!) of scales involved, both of which could maybe be pigeonholed as 'this is xyz minor'. But there's little point. In a way, it's like when a major piece modulates, there'a a non-diatonic note involved. Is it absolutely necessary to label everything? I think not!
Comment: @jdjazz - moot point! Yes, it's incorrect (imo) as a key is either major or minor. Even modes have keys! Em is Em. E Aeolian is a derivative of Em. E Phrygian...E Dorian... It appears that to be 'in E minor' needs only two key (excuse the pun) things. To be based on home=E, and to have G natural cropping up. I honestly don't know what's correct or not. Powers greater than me (that's most of you) will clarify...
Comment: Haha. I'm trying to figure out if there's a way to ask the question while eliminating the issue of scale vs. key. I can think of instances where the melody is written from a single minor scale. And in those contexts, I feel like the word "minor" does occasionally imply *one particular* minor scale. I can't narrow down those cases where a particular minor is implied though--I can't distill it enough to articulate an actual convention.
Comment: @jdjazz - I just feel that the minory bit is inferred by there being a minor 3rd. There really is nothing else. Aeolian, natural, harmonic, melodic, Dorian, et al all possess that golden  bit. If any of these are E based, then E minor comes to mind. E melodic minor only has one note different from E major - the defining minor third. Can't see how a 'key' can signify use of one specific set of notes in 'minor'.
Comment: I see the merit in your point. I'm going to try to articulate the other side and would appreciate your feedback. (Though you may not be swayed :)
Comment: @jdjazz - I am *always* open to other ideas, (on everything), even if I disagree. Must keep the remaining synapses active...   I think your use of the term 'tonality' is apposite.
Answer: First of all, as other people have already stated, a song is in a key, not a scale.  Also, many songs move to or at least allude to several different keys.  When a song is written in a minor key, it will often switch between harmonic, melodic, and even natural.  Melodic minor will sometimes be used on ascending scale passages, and natural minor is rather rare because its leading tone is not raised, which means that it doesn't naturally lead to tonic.  However, harmonic minor is the most-used form because generally speaking it sounds the best to most Western listeners. This is because the leading tone is raised but it is still distinct from major, and it remains the same whether ascending or descending.
Comment: Isn't the statement "harmonic minor ... sounds the best to modern ears" subjective?
Comment: @jdjazz - unless you stick to pure mathematical analysis, everything we say about what music sounds like is subjective - based on time (period/era etc), location, surrounding culture, personal taste,  experience.... If there is a problem with "sounds the best to modern ears" it's not because it's subjective, but because it's too great a generalization.
Comment: @jdjazz If you see something that can be improved in my answer, you're welcome to edit it.  I have tried to edit it based on your criticisms, but it might not be satisfactory still...  Thanks for your comments though; my statement was definitely too generalized.  I certainly did not mean to imply that anyone who does not prefer harmonic scales is "primitive" or anything of the sort.  I merely meant that in previous ages, the preference for a harmonic scale was not always as obvious as it is today, as Stinkfoot clarified.
Comment: @Mary, I assumed you didn't actually intend anything negative by it. I've removed my -1. I think the half step leading tone is a good point because it creates a stronger resolution toward the tonic. If you have any thoughts on why that evolution of preference occurred, I would be interested in hearing them.
Comment: You're right, but generally speaking it's most comfortable for Western music/listeners.  This is because the leading tone is raised but it is still distinct from major, and it remains the same whether ascending or descending.
Comment: @Stinkfoot, that statement contains an additional claim that goes beyond musical preference, I think. I think there's an implicit suggestion about what types of music do & don't qualify as "modern." For example, I don't know if Mary is suggesting that other listeners who don't share this preference for the harmonic minor scale are primitive. There is risk of using a musical preference to justify a cultural judgment relating to modernity.
Comment: @jdjazz - _an implicit suggestion about what types of music do & don't qualify as "modern."_    I don't see anything like that in her remarks - she mentioned "modern ears" - all that means is that today everyone in the western world has sensibilities about sound and music that are different than they were 100 years ago, for example. Hard to argue with that IMO. Whether one likes Brahms or hates him, whether one likes hip-hop or hates it,  everyone today hears things differently - if nothing else, it's a result of the environment itself.
Comment: @Stinkfoot, what you've said in your comment is much less objectionable. To put it to a point: there are plenty of examples of music/genres that exist today that don't favor harmonic minor. The post suggests that people who listen to that music don't have modern ears. But those music fans live in the modern age. This isn't a generic statement that preferences have changed over the last 100 years--it more specifically states that modern ears prefer harmonic minor in particular.
Comment: @jdjazz _the post suggests that people who listen to that music don't have modern ears_   Sorry - I just don't see it that way. As I said, I agree it's too a broad generalization,  but I don't see what you're reading into it.  There's no reason to imply anything negative from there, IMO. (I don't think I prefer harmonic minor myself...75% of my listening and playing is jazz and blues where dominant is always the prevailing tonality)
Comment: @Stinkfoot, this isn't something I'm reading into--she states that harmonic minor sounds best to people with modern ears. (Or equivalently, if you have modern ears, then you like harmonic minor the best.) By the contrapositive, if you don't think harmonic minor sounds best, then you don't have modern ears. This isn't an interpretation I'm taking; it is a logical extension of what she has written. I think it's an unfairly subjective judgment. I think we both agree that it would be fair to say "Most people prefer harmonic minor because of XYZ, and as a result, harmonic minor is the most used."
Answer: On "Key" vs. "Scale"
The phrasing of this question seems to be generating a lot of discussion about the difference between a key and a scale. First, I'll address that issue, and then I'll offer an answer with some references.
I think much of the discussion about key vs. scale is misguided because keys are based on scales. For example, Wikipedia states:

In music theory, the key of a piece is a group of pitches, or scale upon which a music composition is created in classical, Western art, and Western pop music.

If keys are based on scales, then a minor key must be based on a particular minor scale. So the question is valid in asking about the underlying scale on which the minor tonality is based. I see the question as being: is there a single minor scale that is implied when a song is stated to be in a "minor" key?
Answer: Natural Minor
The answer to this question is: in general, yes, a single minor scale is implied. Stating "E minor" implies E natural minor. For example, studybass.com states:

Similarly, a piece of music can be in a minor key and revolve around a natural minor scale. For example, a song in the 'key of D minor' uses the notes of the D minor scale – D, E, F, G, A, Bb, and C.

Furthermore, the same Wikipedia article from above states:

A key may be major or minor. Music can be described as being in the Dorian mode, or Phrygian, etc., and is thus usually thought of as in a specific mode rather than a key.

So even the Wikipedia article straightaway excludes Dorian minor as a key, implying that a different minor scale must serve as the basis for minor keys. This affirms the general position on studybass.com that a single minor scale is implied by a minor key.
Caveat
This approach might seem to leave no room for keys based on other minor scales--the Wikipedia article states as much. However, there is still a way to describe a song written in a Dorian mode, but that description shouldn't include the word "key." A statement along the lines of "the song is in the key of E minor" implies E natural minor. Perhaps a song written in E melodic minor would be best described this way: "the song is written using the E melodic minor scale."
Comment: I would like to disagree with Wiki on that definition. A scale is a set of pitches ordered by frequency. A key is a set of relations among chords. Some of these: tonic (major or minor), dominant chord with root a fifth above, sub-dominant chord with root a fifth below, etc. (including secondary dominants, augmented sixths, etc., cadential formulae....)
Comment: I haven't seen a definition as such. I just got this idea from Tovey and Schoenberg and other music commentators. I'll take a look around some references over the weekend and see what I can find. Note that one can establish a key by playing (for example) the chord progression ii6, V7, I but not necessarily playing a scale. Even a V7-I sequence is sufficient or even a French Sixth followed by a V, no I needed.
Comment: According to some music-psychologist (I don't remember who. This was commented on in a lecture I attended), a repeated chord with no other sonorities begins to sound like a dominant.  (I never experimented with the idea.) I think the lecturer's point was that chords get their identity (at least partly) from context.
Comment: @ttw, can you provide a reference or citation in support of this definition?
Answer: There isn't a default minor scale, but if we are looking for some kind of foundation idea for minor (mode, key, tonality, etc.) we could say a mediant that is a minor third above a tonic is the primary identifying characteristic of minor tonality.
Beside the tonic and mediant all the other scale degrees are flexible in their exact interval above the tonic. In actual practice minor key music will exploit several options for these flexible scale degrees. You could regard the natural minor scale as the default scale from which scale degrees are altered, but this might be misleading for two reasons: first, it seems to dodge the main issue about the fluid nature of minor tonality, second it doesn't seem to match history. Minor keys in the Baroque era used a key signature that would be equal to the dorian mode. Is dorian mode the default minor scale?
It may be best to embrace the fluid nature of minor tonality. A seven pitch default scale just won't give us a complete picture. Maybe an analogy from science would be useful. Compare theories of the atom: the theory of an electron cloud based on probability versus the old Bohr model of fixed electron shells. Sometimes we just deal with things that are indefinite.

What is the default minor scale?


Oracle: getting maximum value of a group?

Question: Given a table like this, what query will the most recent calibration information for each monitor?  In other words, I want to find the maximum date value for each of the monitors. Oracle-specific functionality is fine for my application.
monitor_id     calibration_date  value
----------     ----------------  -----
1              2011/10/22        15
1              2012/01/01        16
1              2012/01/20        17
2              2011/10/22        18
2              2012/01/02        19

The results for this example would look like this:
1  2012/01/20 17
2  2012/01/02 19

Answer: I'd tend to use analytic functions
SELECT monitor_id,
       host_name,
       calibration_date,
       value
  FROM (SELECT b.monitor_id,
               b.host_name,
               a.calibration_date,
               a.value,
               rank() over (partition by b.monitor_id order by a.calibration_date desc) rnk
          FROM table_name a,
               table_name2 b
         WHERE a.some_key = b.some_key)
 WHERE rnk = 1

You could also use correlated subqueries though that will be less efficient
SELECT monitor_id,
       calibration_date,
       value
  FROM table_name a
 WHERE a.calibration_date = (SELECT MAX(b.calibration_date)
                               FROM table_name b
                              WHERE a.monitor_id = b.monitor_id)

Comment: thanks justin.  If I had another table t2 which had monitor_id and host_name columns, where would I join the tables to add host_name to the output?
Comment: @MarkHarrison - In the analytic function query, you'd just join the two tables in the inline view.  Updated my example with that.
Answer: My personal preference is this:
SELECT DISTINCT
       monitor_id
      ,MAX(calibration_date)
       OVER (PARTITION BY monitor_id)
       AS latest_calibration_date
      ,FIRST_VALUE(value)
       OVER (PARTITION BY monitor_id
             ORDER BY calibration_date DESC)
       AS latest_value
FROM mytable;

A variation would be to use the FIRST_VALUE syntax for latest_calibration_date as well. Either way works.
Answer: The window functions solution should be the most efficient and result in only one table or index scan. The one I am posting here i think wins some points for being intuitive and easy to understand. I tested on SQL server and it performed 2nd to window functions, resulting in two index scans.
SELECT T1.monitor_id, T1.calibration_date, T1.value
FROM someTable AS T1
WHERE NOT EXISTS
(
    SELECT *
    FROM someTable AS T2
    WHERE T2.monitor_id = T1.monitor_id AND T2.value > T1.value
)
 GROUP BY T1.monitor_id, T1.calibration_date, T1.value

And just for the heck of it, here's another one along the same lines, but less performing (63% cost vs 37%) than the other (again in sql server). This one uses a Left Outer Join in the execution plan where as the first one uses an Anti-Semi Merge Join:
SELECT T1.monitor_id, T1.calibration_date, T1.value
FROM someTable AS T1
LEFT JOIN someTable AS T2 ON T2.monitor_id = T1.monitor_id AND T2.value > T1.value
WHERE T2.monitor_id IS NULL
GROUP BY T1.monitor_id, T1.calibration_date, T1.value

Comment: The second solution is amazingly slow on SQL Server :)
Answer: select monitor_id, calibration_date, value
from table
where calibration_date in(
  select max(calibration_date) as calibration_date
  from table
  group by monitor_id
  )

Comment: this is definitely wrong, when you have `monitor_id=1` with `max(calibration_date) = 10` then you may return row `(monitor_id=2, calibration_date=10)` even thouth `max(calibration_date) = 20` for `monitor_id=2`


Tensor product of a bimodule (projective as a right module) and a projective right module is projective

Question: Let R and S be rings. Let L be a projective R right module ($L_R$) and M be a R-S bimodule ($_RM_S$) such that M is projective as a S right module. I'm trying to prove that $$(L \otimes M)_S$$ is projective.
I've look the equivalent statements for a projective module but in all of them I can't see how $M_S$ being projective help me.
Do you have some ideas?
Thank you anyway.
Answer: Let's put the definition at the top for comparison:

Definition: Let $R$ be a ring. A right $R$-module $P$ is projective if, for each surjection $\pi : A \rightarrow B$ of right $R$-modules, and each map $f : P \rightarrow B$, there is a map $g : P \rightarrow A$ such that $\pi \circ g = f$.

Also, in problems like this, it is important to know the hom-tensor adjunction for bimodules, so I'll put that here too:

Theorem: Let $R$ and $S$. Let $M$ be a left $R$-module and a right $S$-module. Let $N$ be a left $R$-module and a right $S$-module. Let $L$ be a right $S$-module. Then there is an isomorphism of abelian groups
  $$ \text{Hom}_S ( M \otimes_R N, L) \cong \text{Hom}_R ( M, \text{Hom}_S (N, L))$$
  Which, fixing $N$, is natural in $M$ and $L$.

In your setup, we have a projective right $R$-module $L$ and and an $R$-$S$ bimodule $M$ which is projective as a right $S$-module. Put $P = L \otimes_R M$, which is a right $S$-module. Let $\pi : A \rightarrow B$ be a surjection of right $S$-modules, and let $f : P \rightarrow B$ be an $S$-linear map.
Since $M$ is projective, the map $\rho : \text{Hom}_S (M, A) \rightarrow \text{Hom}_S (M, B)$ is surjective. By the Hom-Tensor adjunction, $f$ induces a map of right $R$-modules $L \rightarrow \text{Hom}_{S} (M, B)$. This map lifts along the surjection $\rho$ to a map $L \rightarrow \text{Hom}_S (M, A)$. By the hom-tensor adjunction, this induces a map of right $S$-modules $g : L \otimes_R M \rightarrow A$. I will leave it to you to check that $g$ is a lift for $f$, so that the definition above is satisfied.


Are there reliable free/cheap software tools which will transcribe a sung melody/lyric?

Question: I am not after product recommendation but information on if this type of product exists outside of expensive dedicated music software.
For instance I sing a little melody line while strumming a 4-chord pattern on the guitar, but lack the musical ear to know what I'm singing. Or, I sing a song I know well to see what the melody line is rather than try to work it out note by note.
If such things exist, do they require careful singing - la-la-la rather than words for instance - and are they able to work around my imperfect relative pitch?
Where are we at technologically? Is it something any $0.99 app can do?
Comment: Unfortunately, asking for product recommendations is specifically what you seem to be doing here. There are transcription applications / plugins, but most of them are silly and unhelpful.  Many applications are embedded within larger, expensive programs like Finale or Band in a Box. Don't rely on something to do the work for you. Train you ears. Use your brain. Become a better musician.
Comment: Transcribing is a very basic music theory skill. This is something you really should be doing yourself.
Comment: No, it's not what I'm asking which is why I said it. Imagine I was a old-school pianist who never used computers and was wondering if there were tools which would auto-transcribe my playing, since I didn't know anything about computer capabilities. And I'm sorry but "train your ears" is not helpful advice, tools exist for a reason. Of course it would be nice to get to that point but I don't see people asking about time-slowing tools being described as pointless.
Comment: For instance "this is what such a tool would be called but cheap products don't work well" would be an answer. I don't know what to Google for to start investigating, and knowing if the thing even exists would save me searching for a tool which isn't out there :)
Answer: As far as I'm aware, there is no specific plugin that will transcribe what you sing in to it, I think that's probably too complex a task. You can however run an Autotune plugin that has a display of the note you are singing and write down the notes yourself, or pull up a piano vst and just find the notes you're singing.
Answer: However much money you are prepared to spend, the best - probably the only - computer for doing this is the wet one sitting between your ears, plus your musical skills and experience.
Answer: So anyway I came across this software after failing to get useful answers here: http://scorecloud.com/
I've had fairly poor results with it so far to be honest but that may be limitations of my technique. Someone else might find this useful so I'm sharing it... it'd be interesting to hear if trained singers get better accuracy than I do (post a comment if you like).
Answer: I'm jumping right into products, sorry in advance. These are some of the best around, but there are others in each product category that would do the same thing.
There are in fact programs that will do exactly what you're asking, but they aren't inexpensive. Steinberg's Cubase, a digital audio workstation, will record a mono track of your voice through a microphone, and then with the sample editor you can use a feature called "VariAudio" which plots your voice, note by note, on a vertical "keyboard" that extends the black and white "keys" across the page so that you can see where you're singing. You can also edit the pitch and timing, making notes longer or shorter, and with other edits you can change the amplitude of the note as well.
Cubase is a program in and of itself, but it and other digital audio workstations host third-party "plugins" and those can be even more powerful. Celemony's Melodyne will not only graph your voice according to pitch but will pop out the musical notation right above it given the time signature and key of the song. It works pretty well. Also, with Melodyne, you can strum chords on a guitar or play them on a piano and it will recognize the chord and display the notes on a staff in the very voicing you used, allowing you to then change, say, the root of the chord to the third or the fifth, what have you.
These are some of the tools that industry professionals use to record and to transpose. I have heard of many more but I wouldn't personally recommend something I haven't used before.


Make 'email@example.com' into 'flast' with JavaScript Regex

Question: I'm not an expert in regexes and was curious if there was a regex to turn this:
firstname.lastname@example.com
to
flast
And more importantly, how it actually works. Currently I am doing this and it does not seem ideal. Thanks!
var email = 'email@example.com';

email = email.substring(0, email.indexOf("@"));
email = email.split('.');
email = _.lowerCase(email[0].charAt(0) +   email[1]);

Comment: what about `email@example.com` or `firstname.lastname@example.com`?
Comment: and how do you think, by what principle are generated the last two characters `st` ? Also, show more similar examples
Comment: @rock321987, that's a valid concern. but it'll be safe to know that this is the only criteria. in this use case, it will always be firstname.lastname@example.com.
Comment: https://regex101.com/r/uX7eO8/1
Answer: As per your wishes, this will work
(.)[^.]*\.(.*)@.*

Regex Demo
JS Demo

var re = /(.)[^.]*\.(.*)@.*/;
var str = 'email@example.com';
var subst = '$1$2';
var result = str.replace(re, subst);
document.writeln(result.toLowerCase() + '
')

Make 'First.Last@example.com' into 'flast' with JavaScript Regex


Prove a function is uniformly continuous

Question:
Prove the function $f(x)=\sqrt{x^2+1}$     $ (x\in\mathbb{R})$ is uniformly continuous.

Now I understand the definition, I am just struggling on what to assign $x$ and $x_0$
Let $\epsilon>0$ we want $|x-x_0|<\delta$ so that $|f(x)-f(x_0)|<\epsilon$
Could anyone help fill in the missing bits? Thanks
Answer: You have $$\begin{aligned}\vert f(x)-f(y) \vert &= \left\vert \sqrt{x^2+1}-\sqrt{y^2+1} \right\vert \\
&= \left\vert (\sqrt{x^2+1}-\sqrt{y^2+1}) \frac{\sqrt{x^2+1}+\sqrt{y^2+1}}{\sqrt{x^2+1}+\sqrt{y^2+1}} \right\vert \\
&= \left\vert \frac{x^2-y^2}{\sqrt{x^2+1}+\sqrt{y^2+1}} \right\vert \\
&\le \frac{\vert x-y \vert (\vert x \vert + \vert y \vert )}{ \sqrt{x^2+1}+\sqrt{y^2+1}} \\
&\le \vert x-y \vert
\end{aligned}$$ hence choosing $\delta = \epsilon$ will work.
Answer: Note that $f'(x)= x/\sqrt {x^2+1}$ for all $x.$ We thus have $|f'(x)|<1$ everywhere. Suppose $x,y\in \mathbb R.$ Then the mean value theorem gives
$$f(y)-f(x) = f'(c)(y-x) \implies |f(y)-f(x)| \le |y-x|.$$
This easily gives the uniform continuity of $f$ on $\mathbb R.$


JSON objects returns undefined

Question: I'm returning a JSON object using a 3rd party API. When I print out the variable I get the following:
category:
{
    "sys":
    {
        "id":"44uyBvGjFmsmoU6uqiiSOq",
        "revision":1,
        "type":"Entry",
        "locale":"en-US",
        "contentType":
        {
            "sys":
            {
                "id":"2V5tBa4wf6cuMSIu4McuUc",
                "type":"Link",
                "linkType":"ContentType"
            }
        },
        "createdAt":"2014-09-13T22:40:39.901Z",
        "updatedAt":"2014-09-13T22:40:39.901Z",
        "space":
        {
            "sys":
            {
                "id":"t667fybp3v46",
                "type":"Link",
                "linkType":"Space"
            }
        }
    },
    "fields":
    {
        "name":"birth control"
    }
}

But when I try and access the variables using the following, I keep on getting "Possibly unhandled TypeError: Cannot read property 'name' of undefined" :
if (o.fields.category)
{
    var str = JSON.stringify(o.fields.category, undefined, 2);
    console.log(str);

    var json_category = JSON.parse(str);
    // console.log("--------------Category for the resource: " + o.fields.category);
    $.each(json_category, function(index, object){
        alert(10);
        var category = {};
        // console.log("--------------Category for the resource: " + object.sys);
        category.id = object.sys.id;
        // console.log("--------------Category for the resource: " + object.fields.name);
        category.name = object.fields.name;
        // console.log("--------------Category for the resource: " + object.sys.updatedAt);
        category.updatedAt = object.sys.updatedAt;
        categories.push(category);
    });
 }

Any help is greatly appreciated.
Comment: Well it's hard to say; it would be much more useful to debug from *inside* your callback to the `$.each()` loop. You don't have to stringify the object to log it; use `console.dir(object);` and you'll be able to inspect the object in the developer console.
Comment: Just replace that `alert(10)` call with `console.log("index: " + index + " object: ", object);` and have the browser developer console open. (The "Console" tab; the developer console has a lot of stuff in it nowadays.)
Comment: You can not access id directly use 'category.sys.id' instead of 'category.id', do the same for name.
Comment: What does your call to this API look like? The problem is very likely to be that your API is asynchronous and you're not properly waiting for the result.
Comment: I'm using Contentful and their Javascript library https://www.contentful.com/developers/documentation/content-delivery-api/
Comment: Oh I see what's happening.
Comment: I think I see what you mean. Do you think you can provide a bit of code. Sorry not the strongest with JSON.
Comment: Thanks guys, I've added the code that I used below
Answer: Changed my code to the following. Thanks to Pointy for providing the assistance, much appreciated.
if (o.fields.category)
{
    console.log(o.fields.category.fields.name);

    var category = {};
    category.id = o.fields.category.sys.id;
    category.name = o.fields.category.fields.name;
    category.updatedAt = o.fields.category.sys.updatedAt;
    categories.push(category);
}

record.categories = categories;
record.searchTags = search_tags;
records.push(record);

JSON objects returns undefined