Converter data dd-mm-aa para aaaa-mm-dd em Java

Question: Estou recebendo via formulário:
28-set-2018

e preciso salvar no banco
2019-09-29 00:00:00

Answer: Depende: o campo no banco de dados está como string (varchar)?
Pois geralmente datas são salvas nos bancos de dados em um campo com o tipo específico (date, datetime, timestamp, etc). Se esse for o caso, não deveria haver preocupação quanto ao formato salvo.
A sua preocupação, neste caso, seria apenas converter a string 28-set-2018 para uma data e salvá-la diretamente no banco.
Se você está usando Java >= 8, pode usar a API java.time:
Locale locale = new Locale("pt", "BR");
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd-MMM-uuuu", locale);
LocalDate date = LocalDate.parse("28-set-2018", parser);

O java.util.Locale é importante porque o mês está em Português, e se você não informá-lo, será usado o locale default da JVM (que pode ser outro idioma), então é melhor usar o locale correto.
O problema é que somente a partir do JDBC 4.2 é possível salvar as classes do java.time diretamente no banco, usando setObject:
preparedStatement.setObject(1, date);

Verifique se o driver do banco de dados que você está usando já é compatível com JDBC 4.2. E caso seja, verifique o respectivo tipo do campo, pois no java.time há várias classes diferentes para representar datas e horas (exemplo no PostreSQL - veja se e como o seu banco está mapeando estes tipos).
No seu caso, como você está querendo salvar também o horário, então você precisa de um LocalDateTime com o horário setado para meia-noite (as duas formas abaixo são equivalentes):
// use atStartOfDay (seta horário para meia-noite)
LocalDateTime datetime = date.atStartOfDay();

// Ou passe o valor do horário explicitamente
LocalDateTime datetime = date.atTime(0, 0);

Neste caso, passe o LocalDateTime para setObject. Caso precise de outros tipos (como ZonedDateTime, que também considera o fuso-horário), consulte esta pergunta que tem mais detalhes sobre o java.time e seus tipos. Veja também o tutorial da Oracle.
Digo isso porque datas não tem formato. Elas só possuem valores (dia, mês, ano, etc). Quando um tipo date, datetime, timestamp, etc, é salvo no banco, esses valores é que são salvos. Os formatos servem apenas para visualizar os valores de uma maneira inteligível: as strings 28-set-2018 e 2018-09-28 são apenas representações (formatos) diferentes para o mesmo valor (a mesma data).

Mas se você precisa de uma String naquele formato específico (e não um date, datetime, etc), basta criar outro DateTimeFormatter:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String dataFormatada = datetime.format(fmt); // 2018-09-28 00:00:00

Atenção quanto a diferença entre H e h: o maiúsculo representa as horas do dia (valores de 0 a 23) e o minúsculo representa a "hora AM/PM" (valores de 1 a 12) - veja diferença aqui. Ou seja, meia-noite será impresso como 00:00:00 se usar HH:mm:ss, e como 12:00:00 se usar hh:mm:ss (já que meia-noite também pode ser escrito como 12 AM).

Se o seu driver não é compatível com JDBC 4.2, não tem jeito, você deve gravar um java.sql.Date. Neste caso, basta converter o LocalDate que obtivemos acima:
import java.sql.Date;

// valueOf fica em java.sql.Date, não confundir com java.util.Date
Date sqlDate = Date.valueOf(date);

Mas no seu caso, como você precisa do horário, então converta o LocalDateTime para um java.sql.Timestamp:
Timestamp timestamp = Timestamp.valueOf(datetime);

Aí você pode salvar estes objetos diretamente no banco, usando os métodos específicos (setDate, setTimestamp, etc).
Lembrando que estas classes pegam a data/hora no timezone default da JVM e convertem para um timestamp (que é o valor guardado internamente por estas classes).

Java <= 7
Para Java <= 7, você pode usar o ThreeTen Backport, que possui praticamente as mesmas funcionalidades do java.time. A diferença é que elas estão no pacote org.threeten.bp, mas os nomes e métodos são os mesmos.
Outra diferença é a forma de converter para java.sql.Date e java.sql.Timestamp. Como os métodos valueOf(LocalDate) e valueOf(LocalDateTime) só foram adicionados no Java 8, o backport criou a classe org.threeten.bp.DateTimeUtils para fazer as conversões (veja na documentação).

Não tenho Java 8 e não quero usar outra API
Neste caso, o jeito é usar um java.text.SimpleDateFormat para gerar um java.util.Date, e em seguida usar java.util.Calendar para setar o horário para meia-noite:
Locale locale = new Locale("pt", "BR");
SimpleDateFormat sdfInput = new SimpleDateFormat("dd-MMM-yyyy", locale);
// converter String para java.util.Date
Date data = sdfInput.parse("28-set-2018");

// setar horário para meia-noite
Calendar cal = Calendar.getInstance();
cal.setTime(data);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// obter o novo valor do java.util.Date (com horário igual a meia-noite)
data = cal.getTime();

// criar java.sql.Date ou java.sql.Timestamp
java.sql.Date d = new java.sql.Date(cal.getTimeInMillis());
Timestamp ts = new Timestamp(cal.getTimeInMillis());

Novamente: se o campo no banco de dados é uma data (o tipo é date, datetime, timestamp, etc), salve o java.util.Date/java.sql.Date/java.sql.Timestamp diretamente. Mas caso você precise de uma string em outro formato, basta criar outro SimpleDateFormat:
SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dataFormatada = sdfOutput.format(cal.getTime()); // 2018-09-28 00:00:00

OBS: neste caso específico, setar a data para meia-noite não seria necessário, pois SimpleDateFormat já faz isso quando os campos de horário não estão presentes. De qualquer forma, deixo o código como referência caso você precise mudar para outros valores.

Observação quanto ao nome do mês
Muitas informações de localização foram alteradas no JDK 8 e no JDK 9, conforme discutido aqui.
E para o JDK 11, também foram feitas mais alterações referentes à localização. Ou seja, pode ser que, dependendo do locale, as Strings resultantes sejam diferentes – os detalhes podem ser encontrados no OpenJDK Bug System.
Isso significa que, dependendo da versão do Java, pode ser que ele não consiga interpretar o mês com letra minúscula (set). Neste caso, basta criar um DateTimeFormatter case insensitive:
Locale locale = new Locale("pt", "BR");
DateTimeFormatter parser = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .appendPattern("dd-MMM-uuuu")
    .toFormatter(locale);

E ainda há uma outra alternativa, caso o horário deva ser sempre meia-noite. Você pode usar o método parseDefaulting para setar valores predefinidos para o horário, caso este não esteja presente na String de entrada. Basta passar um java.time.temporal.ChronoField correspondente ao campo e o respectivo valor:
DateTimeFormatter parser = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .appendPattern("dd-MMM-uuuu")
    // setar hora e minuto para zero
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
    .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
    .toFormatter(new Locale("pt", "BR"));
LocalDateTime datetime = LocalDateTime.parse("28-set-2018", parser);

Ao setar hora e minuto para zero, os segundos e frações de segundo também serão setados automaticamente para zero (caso o horário não esteja na entrada).
Com isso, você pode fazer o parsing diretamente para LocalDateTime. Como a String só possui dia, mês e ano, o horário será setado automaticamente para meia-noite e a partir daí você usa a data como precisar.
Answer: Algo assim deve funcionar, só se atente com relação ao mes da sua data.. ele deve estar com a abreviação em inglês (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec)
DateTimeFormatter formatterInput = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
DateTimeFormatter formatterOutput = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

//entrada
String date = "28-set-2018";

//criando objeto data a partir da sua string
LocalDateTime localDate = LocalDateTime.parse(date, formatter);

//saída 2019-09-29 00:00:00
localDate.format(formatterOutput);

Se quiser usar os meses em português, use:
Locale locale = new Locale("pt", "BR");
DateTimeFormatter formatterInput = DateTimeFormatter.ofPattern("dd-MMM-yyyy", locale);

Comment: eu obtenho as datas tipo cell e converto para String
Comment: String date = row.getCell(5);
Comment: Se a entrada só tem dia, mês e ano, fazer um `parse` diretamente para um `LocalDateTime` [**dará erro**](https://repl.it/repls/HastyDrearyMetadata). Outro detalhe é que `hh` imprime meia-noite como `12` - para ter `00`, use `HH`- veja [aqui](https://ideone.com/1yCkFc). E *"deve estar com a abreviação em inglês"* só é válido se o locale *default* da JVM for inglês. No meu caso o *default* é pt_BR e funciona sem precisar setar o locale (apesar de ser recomendado setar um específico para não depender da configuração *default* da JVM)


How to get properties of items in IEnumerable when that IEnumerable is in a model

Question: I have the following model which has an IEnumerable where T is another object/model:
public class Employee
{

    public ApplicationUser PayrollAdmin { get; set; }

    [Required]
    public int EmployeeId { get; set; }

    [Required]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    public virtual ICollection<Dependant> Dependants { get; set; }

}

The Dependant class is essentially this:
public class Dependant
{

    public int DependantId { get; set; }

    [Required]
    [DisplayName("First Name")]
    public string FirstName { get; set; }
    [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [ForeignKey("Employee_EmployeeId")]
    public virtual Employee Employee { get; set; }

    public int? Employee_EmployeeId { get; set; }
}

I am unable to access the Dependant properties from the Employee model.  Razor does not expose those properties.  I essentially want to do something like @Model.Employee.Dependant.FirstName but can't drill into those properties.  Is this not possible or is there something I need to do to get there?
Answer: The Dependants property is a collection, so you need to iterate over it in order to access the elements of this collection separately:
@foreach (var dependent in Model.Employee.Dependants)
{

@dependant.FirstName

@dependant.LastName

}

Answer: Dependants is a collection.  You will either have to iterate over:
@foreach (var item in Model.Employee.Dependants)
{
    @item.FirstName @item.LastName

}

or use LINQ
@if(Model.Employee.Dependants.Any())
{
    Model.Employeee.Dependants.FirstOrDefault().FirstName
}


Limit of $\lim_{x\to 0^+} (1+x)^{\ln x}$

Question: This is what i did:
$\lim_{x\to 0^+} (1+x)^{\ln x}=\lim_{x\to \infty}(1+\frac1x)^{\ln \frac1x}$
Then
$(1+\frac1x)^{\ln \frac1x}=(1+\frac1x)^{-\ln x}=(1+\frac1x)^{\frac xx(-\ln x)}=(1+\frac1x)^{\frac xx(-\ln x)}=[(1+\frac1x)^x]^{-\frac{\ln x}{x}}$
  Then
$\lim_{x\to \infty}[(1+\frac1x)^x]^{-x\ln x}=\lim_{x \to \infty}e^{-\frac{\ln x}{x}}$
Then
$\lim_{x \to \infty}{-\frac{\ln x}{x}}=L'Hospital=\lim_{x\to\infty}\frac{-1}{x}=0$
Then
$\lim_{x \to \infty}e^{-\frac{\ln x}{x}}=e^0=1$
Is this process ok? Is there an easier way of doing this limit?
Answer: That is very complicated. You can have something much simpler using only basic limits and equivalents. First note it is enough to find the limit of $\ln(1+x)^{\ln x}$: as $\;\ln(1+x)\sim_0 x$, we have:
$$\ln\bigl((1+x)^{\ln x}\bigr)=\ln x\ln(1+x)\sim_0x\ln x\xrightarrow[x\to 0+]{}0,$$
hence $\;\lim\limits_{x\to 0+}\ln(1+x)^{\ln x}=\mathrm e^0=1$.
Comment: Sorry, i cant understand how $\lim_{x\to 0^+} (1+x)^{\ln x}=\lim_{x\to0^+}\ln (1+x)^{\ln x}=e^0=1$
Comment: $\mathrm e^x$ is a continuous function.
Comment: $\lim_{x\rightarrow 0^+} (1+x)^{\ln(x)}$ is not equal to $\lim_{x\rightarrow 0^+}\ln\left((1+x)^{\ln(x)}\right)$, it's equal to $e^x$ of that. That's what Bernard's solution is using.
Comment: I get it now, thanks a lot for your time both of you
Comment: You're welcome!


Google Charts Update Category Filter based on other Category Filter

Question: I have these two filters below, both are implemented into google charts. When I change filter1, the data changes in the visualization, but the values in filter2 do not change. I was wondering if that was possible with Google Charts.

filter1 has: 1 and 2 for options
filter2 has: A,B,C,D,E,F for options

Selecting 1 from filter1 needs to trigger the data-source of filter2 to filter to A,B,C.
Selecting 2 from filter1 needs to trigger the data-source of filter2 to filter to D,E,F.
Filters for google charts:
var filter_1 = new google.visualization.ControlWrapper({
                'controlType': 'CategoryFilter',
                'containerId': 'filter1',
                'options': {
                    'filterColumnIndex': 0,
                    'ui': {
                    'allowTyping': false,
                    'allowMultiple': false,
                    'selectedValuesLayout': 'belowStacked',
                    'label': 'Filter 1:'
                }
                }
            });

var filter_2= new google.visualization.ControlWrapper({
            'controlType': 'CategoryFilter',
            'containerId': 'filter2',
            'options': {
                'filterColumnIndex': 1,
                'ui': {
                'allowTyping': false,
                'allowMultiple': false,
                'selectedValuesLayout': 'belowStacked',
                'label': 'Filter 2:'
            }
            }
        });

Answer: bind(filter_1, filter_2)

This will make any filter_2 change its options based on filter_1. Change the order to have the reverse effect. Once that is done, to get both filters to your chart...
bind([filter_1, filter_2], chart)
draw(chart)


Where does MongoDB store its documents?

Question: I have inserted and fetched data using MongoDB, in PHP. Is there an actual copy of this data in a document somewhere?
Answer: By default Mongo stores its data in the directory /data/db.
You can specify a different directory using the --dbpath option.
If you're running Mongo on Windows then the directory will be C:\data\db, where C is the drive letter of the working directory in which Mongo was started. This is quite confusing, so on Windows I'd recommend that you always specify a data directory using --dbpath.
Comment: I am using v4.0.2, I installed the Mongo to C:\apps\Mongo.
I didn't specify any path and the db path is located under c:\apps\Mongo\Server\4.0\data
Comment: For a deeper understanding: Where are the documents saved in? The only files that are large enough to contain my saved documents are the files in `/data/db/journal`, namely the `WiredTigerLog` and `WiredTigerPreplog` files. Are the documents encoded in there?
Answer: MongoDB stores it's data in the data directory specified by --dbpath. It uses a database format so it's not actual documents, but there are multiple documents in each file and you cannot easily extract the data from this format yourself.
To read and/or update a document you need to use a MongoDB client, in the same way that you send SQL queries to MySQL through a MySQL client. You probably want to do it programmatically by using one of the client libraries for your programming language, but there is also a command-line client if you need to do manual updates.
Comment: If you are using MongoDB on Ubuntu, you can check --dbpath and other configuration options inside file /etc/mongodb.conf
Comment: The best way is to update it through a MongoDB client (for example the Mongo class in PHP), in the same way that you send SQL queries to MySQL through a MySQL client. Otherwise you will have to implement their file format yourself, including such stuff as key generation and special datatypes, and you need to stop the MongoDB server before doing the update - this is obviously an insane solution.
Comment: --dbpath is specified when you start the server, or in the configuration file specified by the -f or --config flag. Otherwise it have the default setting which is `/data/db`
Comment: Oh I see, So say if I wanted to view the file and make an amend how could I do this ? Also where is my --dbpath defined ?
Comment: Ahh I see so any update, delete etc should only be done via code in your chosen language ?
Comment: OliverBS, that's right. There's also a command-line client if you need to do manual updates. You use the same language for updates in that client. You should read the developer manual to understand more about both the language used and data conventions: http://www.mongodb.org/display/DOCS/Developer+Zone

Where does MongoDB store its documents?


Writing Output of Console to a file in C#?

Question: I'm trying to write the output of the command window to a file, I can get the output correctly, and display it using console. However, it doesn't seem to get logged into the file that I want to write to?
 using (StreamWriter sw = new StreamWriter(CopyingLocation, true))
   {
    Process cmd = new Process();

    cmd.StartInfo.FileName = "cmd.exe";
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.StartInfo.CreateNoWindow = false;
    cmd.StartInfo.UseShellExecute = false;

    cmd.Start();

    string strCmdText = "Some Command";
    string cmdtwo = "Some Other Command";

    cmd.StandardInput.WriteLine(cmdtwo);
    cmd.StandardInput.WriteLine(strCmdText);
    cmd.StandardInput.Flush();
    cmd.StandardInput.Close();

    //Writes Output of the command window to the console properly
    Console.WriteLine(cmd.StandardOutput.ReadToEnd());

    //Doesn't write the output of the command window to a file
    sw.WriteLine(cmd.StandardOutput.ReadToEnd());
   }

Answer: When you call ReadToEnd() it will read everything and all the output has been consumed. You can't call it again.
You have to store the output in a variable and output that to the console and write to a file.
string result = cmd.StandardOutput.ReadToEnd();
Console.WriteLine(result);
 sw.WriteLine(result);


Does there exist on compact metric space an uncountable set of measure zero?

Question: Let $X$ be metric compact space and $\mu$ be a positive, finite, atomless, regular measure on $\sigma$-algebra of Borel subsets of $X$. Does  there exist a set $C\subset X$ such that $C$ is uncountable and of $\mu$-measure zero?
Thanks.
Comment: This is a duplicate of http://math.stackexchange.com/questions/109380/a-uncountable-thus-mua0
Comment: I imagine you want to start with an uncountable metric space?
Comment: Yes. For countable $X$ the measure $\mu$ would have an atom.
Comment: Ah, silly me...
Comment: @CarlMummert. This is a bit different since the other does not assume any regularity conditions on the measure.
Comment: @azarel: I put an answer below which I think shows the parallel between the answer to the other question and the answer to this one.
Comment: Every finite measure on the Borel sets of a metric space is automatically regular.
Answer: There is a subset $A$ of the Cantor set $C$ of cardinality $\aleph_1$ so that $\mu(A)=0$ for all non-atmoic Borel measure on the Cantor set. On the other hand, since $X$ is uncountable, there is a homeomorphic copy of the Cantor set inside $X$ hence the copy of $A$ inside $X$ must have measure zero.
Comment: @JonasMeyer. Lemma 2.1.21 in Walks on ordinals and their characteristics by Stevo Todorcevic
Comment: Could you please provide a reference for the first sentence?
Answer: An uncountable compact metric space contains a homeomorphic copy $C$ of the Cantor space, and $C$ is Borel in the original space. The Cantor space can be decomposed into uncountably many disjoint, uncountable, Borel subsets (because $C \cong C\times C$). If all of these had positive measure, some infinite number would all have measure larger than $1/n$ for some fixed $n$, which is impossible because the original measure was finite.
(This is similar to the answer by azarel but easier.)
Comment: I believe azarel answered first, so really the credit should be his.


Linear map : Matrix of transformation

Question: We have the matrices \begin{equation*}A_1:=\begin{pmatrix}2 & 0 \\ 0 & 1\end{pmatrix}, \ \ A_2:=\begin{pmatrix}\frac{\sqrt{2}}{2} & -\frac{\sqrt{2}}{2} \\ \frac{\sqrt{2}}{2} & \frac{\sqrt{2}}{2}\end{pmatrix}\end{equation*}
We consider the linear maps $F_i:\mathbb{R}^2\rightarrow \mathbb{R}^2$, $\vec{x}\mapsto A_i\vec{x}$ for $i=1,2$.
The maps $F_2\circ F_1$ and $F_1\circ F_2$ aren't equal, are they?
To define the matrix of the correspondig map do we multiply the two matrices?
Answer: For
$F_i:\mathbb{R}^2\rightarrow \mathbb{R}^2$ ,
$F_1 \circ F_2$ and $F_2 \circ F_1$ are different.
Matrix is a shorthand(/representation) of linear transformation, so I'll suggest you to multiply both matrices in respective orders and compute where they send $(x,y)$ so that you can observe that composition of linear transformation is multiplication of respective matrices!
Comment: So for $F_1\circ F_2$ do we consider the matrix $A_1A_2$ and for $F_2\circ F_1$ do we consider the matrix $A_2A_1$ ?
Comment: Does it hold the following? \begin{equation*}F_1\circ F_2(\vec{x})=F_1\left (F_2(\vec{x}\right )=F_1\left (A_2\vec{x}\right )=A_1\left (A_2\vec{x}\right )=\left (A_1A_2\right )\vec{x}\end{equation*}
Comment: Instead of doing this, you can think about it in more generalised way! Write the matrix representation of linear transformation with respect to standard basis and try prove a more generalised result rather than checking if this particular question is true or not!
Answer: That's correct.
A point worth noting:
$$\begin{bmatrix}
\color{red}{\lambda_1} & 0 \\
0 & \color{blue}{\lambda2}
\end{bmatrix}\cdot
\begin{bmatrix}
a & b \\
c & d
\end{bmatrix}=
\begin{bmatrix}
\color{red}{\lambda_1} a & \color{red}{\lambda_1} b \\
\color{blue}{\lambda_2} c & \color{blue}{\lambda_2} d
\end{bmatrix}$$
$$
\begin{bmatrix}
a & b \\
c & d
\end{bmatrix}\cdot
\begin{bmatrix}
\color{red}{\lambda_1} & 0 \\
0 & \color{blue}{\lambda2}
\end{bmatrix}=
\begin{bmatrix}
\color{red}{\lambda_1} a & \color{blue}{\lambda_2} b \\
\color{red}{\lambda_1} c & \color{blue}{\lambda_2} d
\end{bmatrix}$$
Note how rows are multiplied by $\lambda_1, \lambda_2$ when you multiply by a diagonal matrix on the left, while columns are multiplied $\lambda_1, \lambda_2$ when you multiply by a diagonal matrix on the right.

Linear map : Matrix of transformation


A Radiant, Gradient Problem Find The Equation.

Question: Determine whether or not the vector function
is a gradient. If so, find all the functions with that gradient.
$xy^2 i + x^2 y j$
What I first do is find the gradients for each problem thus finding the partial derivatives.
$\frac{∂f}{∂y}$ = $2yx$
$\frac{∂f}{∂x}$ = $ 2xy$
They are equal so we can say they are gradient.
Then we take
$\int\frac{∂f}{∂x}dx$ = $\frac{x^2}{2}$$y^2$ +$B(y)$
$\int\frac{∂f}{∂y}dy$ = $\frac{y^2}{2}$$x^2$ + $A(x)$
This is where I get lost in the problem I know the answer is $f(x,y)$ = $\frac{1}{2}x^2y^2 +C$ because the gradients are equal I feel that there is some step I missed for getting the final answer. Can anyone show me what that step is?
Comment: When you compute the indefinite integral with respect to, say, $x$, you also get a 'constant' that however depends on $y$, and vice versa. Thus, you actually have $x^2y^2/2+A(x) = x^2y^2/2+B(y)$, hence... I think that's what you feel is missing from the final step of your calculation.
Comment: Also, strictly speaking, the partial derivatives being equal is only a necessary condition for the vector field to be a gradient of a function. For the field to be a gradient, you need it to be path-independent. Thus, you can say that the vector field is a gradient only after you've exhibited the anti-derivative, not before that.
Comment: Also, fixed vector field notations. You can't label both components as $f$, better $u$ and $v$ or something.
Comment: I fixed the integrals, the constants were swapped: when you integrate with respect to $x$, you get a "constant" depending on $y$ and vice versa.
Answer: You left out the "arbitrary constant" in your two integrals, and messed up on your notation. So a more complete answer is
$$f(x,y)=\frac 12x^2y^2+g(y)\quad\text{from integrating $\frac{\partial f}{\partial x}$: where $g(y)$ depends only on $y$}$$
$$f(x,y)=\frac 12x^2y^2+h(x)\quad\text{from integrating $\frac{\partial f}{\partial y}$: where $h(x)$ depends only on $x$}$$
Equating those two, you finally get
$$f(x,y)=\frac 12x^2y^2+C$$
where $C$ is a constant, independent of both $x$ and $y$.
Comment: Kind of a dumb question but what does it mean when you say equating those two did you set them equal to each other?
Comment: @LittleJon: Yes, and subtracting $\frac 12x^2y^2$ from each side we get $g(y)=h(x)$, which can happen for all $x$ and $y$ in an interval only if both $g$ and $h$ are the same real constant. Do I need to justify that last statement?
Comment: No I  think I see what you mean you are left with g(y) = h(x) which means that they are equal to each other.
Answer: To prevent confusion, I am posting this as a separate answer. It is important to understand that the condition $\frac{\partial f}{\partial y}=\frac{\partial g}{\partial x}$ is in general only necessary but not sufficient for a field to be the gradient of a function, as shown by the standard example $\frac{x}{x^2+y^2}e_1-\frac{y}{x^2+y^2}e_2$.
Using the naive method, you can compute two different "anti-derivatives" which won't agree everywhere, even though the respective partial derivatives agree.


How to render a returned function value in Vue 3

Question: I am pretty new to vue js. I need to render the value returned by the following function to the row in the table:
The function is:
getGroup(id){
        this.users.forEach(element =>{
            if(element.id===id)
                return element.group.group_name;
        });
}

The html tag in template is:
{{ getGroup(ticket.assignee.assignee_id) }}

However, nothing is rendered in that column respective rows.
How can I show the value returned in those rows?
The full code is here:
<template>

                Subject
                Requester
                Requested
                Type
                Priority
                Group
                Updated
                Assignee
                Cause of suspention

                {{ ticket.subject }}
                {{ ticket.requester }}
                {{ ticket.requested }}
                {{ ticket.type }}
                {{ ticket.priority }}

                {{ getGroup(ticket.assignee.assignee_id) }}

                {{ ticket.updated }}
                {{ ticket.assignee.assignee_name }}
                {{ ticket.suspension_cause }}

A screenshot of what is rendered:
click here
Comment: Can you try to debug `getGroup` method and check if it is rendering properly based on the condition you apply. As looks like this is a data issue.
Answer: Try to find and return user group:
getGroup(id){
  return this.users.find(u => u.id === id).group.group_name
}


How to draw rectangular shapes canvas view using CustomPainter

Question: I'm trying to draw a canvas rectangular lines for the call recording. How do I draw it using customPainter? Is there a better approach?
Comment:  You can use the touchable library https://github.com/nateshmbhat/touchable , to add gestures to each individual rectangles you draw on your canvas.
Answer: You need to create a CustomPainter
class YourRect extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(
      new Rect.fromLTRB(0.0, 0.0, 100.0, 50.0),
      new Paint()..color = new Color(0xFF0099FF),
    );
  }

  @override
  bool shouldRepaint(YourRect oldDelegate) {
    return false;
  }
}

then use it like this:
new GestureDetector(
  onTap: () {
    debugPrint("hello");
  },
  child: Container(
    width: 50,
    height: 50,
    child: CustomPaint(
      painter: (YourdrawRect()),
    ),
  ),
),


Java to Scala type conversion - collection of reflected classes

Question: I use org.reflections to scan a package in my project and get all classes that extend a certain trait, like so:
val reflections = new Reflections("classpath")

val classSet = reflections.getSubTypesOf(classOf[Validation])

I end up with a util.Set[Class[_ : Validation]]
If i do classSet.toSet.map(x => x.getName -> x).toMap using JavaConversions i get a 'missing parameter type' error.
If i do classSet.toSet.map(x => Map(x.getName -> x)).reduce(_ ++ _) i get the same error.If i replace the toSet to toList i get a 'type mismatch' error.
if i do classSet.toList.map(x => (x.getName, x)).toMap, i get the following error:  Cannot prove that (String, Class[?O]) forSome { type ?O <: com.common.Validation } <:< (T,U). not enough arguments for method toMap: (implicit ev: <:<[(String, Class[?0]) forSome { type ?0 <: com.common.Validation },(T,U)])scala.collection.immutable.Map[T,U]. Unspecified value parameter ev.

I want to convert this set to a map of the class name as key and the reflected class as value.
Note - when i build a map like:var classMap = Map[String, Class[_ <: Validation]]() and then pushing every element into this map, by iterating over the Set. I can't access the class's methods i implemented from the Trait.
Answer: What helps in such cases in to explicity specify the types when using the toSet and toMap conversions:
import org.reflections.Reflections
import scala.collection.JavaConversions._

trait Validation

val reflections = new Reflections("classpath")
val javaClassSet = reflections.getSubTypesOf(classOf[Validation])
val scalaClassSet = javaClassSet.toSet[Class[_ <: Validation]]
scalaClassSet.map(x => x.getName -> x).toMap[String, Class[_ <: Validation]]

Comment: Thanks! works like a charm. i didn't know you can explicitly specify types that way.


Question about significance in glm and plotting effects model

Question: Okays I have a quick question that I'm a little confused about.
During my glm model selection, the AIC from my most complicated model (model with say 7 predictors) and then the dredge function indicated which predictors were the most significant. I then ran the new model (with 4 predictors) to now only include those significant predictors. Now that i have ran this new model, 1 of those 4 previous predictors are now no longer significant. My question is, when plotting these effect plots, would I only plot the now 3 significant predictors, or would i still plot that 4th predictor as it was significant in the original beginning model?
Hopefully this isn't a complicated worded question, I am just confused about the change in significance
I understand dredging is not the best practice, however, my statistical abilities are not that great and I got it checked by my supervisor who said I would not be penalised for doing so.
Answer: To be consistent with your final model, only plot the effects for the variables that are actually in it.
However I must caution you that this kind of stepwise variable selection procedure is very, very bad and it is extremely depressing that your supervisor seems to think it is OK. Is there no underlying theory to which you can appeal ? You seems
to be interested in inference rather than prediction, so you you to pay very careful attention to which variables are potential confounders, mediators, instruments and competing exposures.
Comment: Does this answer your question ? If so, please consider marking it as the accepted answer, and if not please let us know why.


Recurrence relation - simple question. Homework. Permutations with a twist,

Question: I think I solved it but I would love someone to tell me if I'm wrong.
the question is as follows:
$n$ people are sitting on a bench with $n$ seats. Find a recursive equation that calculates how many different combinations are there to change the sitting order where every person can only move to the adjacent seat.
For example, if I'm sitting in chair number 4, I can only move to chair number 3, number 2, or stay where I am.
Next question: Same thing, but instead of on a bench, they are sitting around a round table.
My solution:
let $f(n)$ be the number of ways to rearrange the sitting as required. the first person has 2 options, either stay in his seat, or move to the sit next to him (he has only 1 sit next to him if its a bench), and the other people on the bench have $f(n-1)$ options. So overall : $f(n)=f(n-1)+2$
And if they are sitting at a round table: Same idea. the first person has $3$ options now. move right, move left, or stay where he is. overall: $f(n)=f(n-1)+3$
Comment: How come you can move from chair number 4 to number 2? They aren't adjacent, are they?
Comment: Why don't you work out the values of f(n) for the first values of n, by direct count? Then you would have something to test your recurrence equation on. I tried that and I don't think your equation works. For the bench problem I get f(1)=1 and f(2)=2.
Answer: Let's give it a try.
$f(1) = 1$ as the only option is not to move. $f(2) = 2$ as the two people can exchange seats, or not move. Note that these are true for both bench and circle. $f(3) = 3$ for bench ($123 \to 213$ or $\to 132$ or $\to 123$) and $6$ for circle (new ones are $123 \to 321$ and $\to 231$ and $\to 312$).
In other words, you didn't get it right. Try again.
Hint. On a bench, if $1$ wants to go to $2$, $2$ must go to $1$. Otherwise the seat would stay empty.
Comment: Yes it seems  I was wrong...But for the love of god, I just can't figure out what the formula is. In either case. I thought maybe for the bench its $f(n)=1+f(n-1)$ but it's not. The numbers fit fibonnaci (at least up to n=5) but i don't know how to show it.
Comment: @OriaGruber, either $1$ doesn't move and you have $f(n-1)$ options left or $1$ moves to $2$ and $2$ moves to $1$ and you have $f(n-2)$ options left.


Prove the equality of the determinants

Question: Let A be square matrix with dimesions of: $3\leqslant n$, prove the equality of the determinants.
$\begin{vmatrix}
1 & n & n & \cdots & n \\
n & 2 & n & \cdots & n \\
n & n & 3 & \cdots  & n \\
\vdots  & \vdots  & \vdots  &  \ddots  & \vdots \\
n & n & n & \cdots  & n \\
\end{vmatrix} = (-1)^{n+1}n!$
My solution so far is:
I subtracted the last row from all other rows: $\begin{vmatrix}
1 - n & 0 & 0 & \cdots & 0 \\
0 & 2-n & 0 & \cdots & 0 \\
0 & 0 & 3-n & \cdots  & 0 \\
\vdots  & \vdots  & \vdots  &  \ddots  & \vdots \\
n & n & n & \cdots  & n \\
\end{vmatrix} $
I took common divisor from each line:
$(1-n)*(2-n)*(3-n)*...*n*\begin{vmatrix}
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
0 & 0 & 1 & \cdots  & 0 \\
\vdots  & \vdots  & \vdots  &  \ddots  & \vdots \\
1 & 1 & 1 & \cdots  & 1 \\
\end{vmatrix}$
Then I subtracted all the rows from the last row: $(1-n)*(2-n)*(3-n)*...*n*\begin{vmatrix}
1 & 0 & 0 & \cdots & n \\
0 & 1 & 0 & \cdots & n \\
0 & 0 & 1 & \cdots  & n \\
\vdots  & \vdots  & \vdots  &  \ddots  & \vdots \\
0 & 0 & 0 & \cdots  & 1 \\
\end{vmatrix}
 $
And so the determinant I got is: $det(A) = (1-n)*(2-n)*(3-n)*...*n \neq (-1)^{n+1}n!$
I would like to get your help to find my mistake
Comment: $n \cdot \prod\limits_{i = 1}^{n-1} (i-n) = n \cdot (-1)^{n-1} \prod\limits_{I = 1}^{n-1} (n-i) = (-1)^{n-1} \cdot n \cdot (n-1) \cdot \ldots \cdot 1$
Answer: If $n=1$, your method doesn't work because its first step makes no sense. Otherwise, it is correct. Note that $k-n=-(n-k)$ for each $k\in\{1,2,\ldots,n-1\}$. Therefore, what you got is equal to$$(-1)^{n-1}(n-1)\times(n-2)\times\cdots\times1\times n=(-1)^{n-1}n!=(-1)^{n+1}n!$$

Prove the equality of the determinants


Can anybody concate this A[] and B[] to array C[]?

Question: I did mistake in writing below code but I am not getting the result of C[] as I want to see both A[] and B[] values in C[] ! As you can see in below code that i have try but not succeed.
public class ascending {

/**
 * @param args
 */
//@SuppressWarnings("null")
public static void main(String[] args) {
    // TODO Auto-generated method stub

    int A [] = {1,2,3,4,5};
    int B [] = {6,7,8,9,10};
    int C[] = null;

    int la = A.length;
    int lb = B.length;
    int lc = A.length + B.length;

    System.out.print("ARRAYS in A: ");

    for(int x = 0; x<la;x++){
        System.out.print("  "+A[x]);
    }

    System.out.println(" ");

    System.out.print
    ("ARRAYS in B: ");

    for(int y=0;y<lb;y++){
        System.out.print(" "+B[y]);
    }

    System.out.println(" ");

    System.out.print("Arrays in C: ");

    for(int z = 0; z<lc; z++){
        System.out.print(" "+C[z]);
    }

    }

}

Comment: You never fill out your `C array`.
Comment: `@SuppressWarnings("null")` yeah, definitely don't do that.
Comment: Or indeed initialize the `C` variable to have a non-null value at all...
Comment: you need to initialize c = new int[lc]; and fill it up
Answer: You neither

allocate the C array with int[] C = new int[size]
copy elements in C through C[x] = A[y] or C[x] = B[y]

Actually you never use C at all, that's why you don't get any exception: if you would have tried accessing the array you would have got a NullPointerException (since C in your current snippet is null)
Answer:
to see both A[] and B[] values in C[]

To see those values in C[], you have to do two things:

Allocate memory for C[].
Copy the elements of A[] and B[] into C[].

Since this looks very much like homework, I won't spell out the solution and let you figure it out on your own.
Answer: One simple solution can be:
int[] c = ArrayUtils.addAll(a, b);

using Apache Commons Lang library.
Answer: As another alternative, by making C a 2D array, you can iterate easier and no extra space will be spent.
int[][] C = {A,B};

for(int i=0; i < C.length; i++)
{
   for( int j=0; j < C[i].length; j++)
        System.out.println(C[i][j]);
}


For Intel Core 2 Duo, should I upgrade my x32 with x64 Linux?

Question: I understand that the Core 2 Duo is a 64-bit processor, while Core Duo is a 32-bit processor.  Let me know if my understanding is wrong. My Linux server, with the Core 2 Duo E8400, is currently running Fedora 9 x32. This machine has 4 Gig of RAM and I don't foresee the need to add any more memory any time soon.
Is there any real advantage to changing from x32 to x64?  If so, should I upgrade from Fedora 9 x32 to Fedora 11 x64 (if this form of upgrade is even supported) or should I reinstall? Do I lose anything of value by sticking to x32?  From what I have read, it sounds like I don't lose much of anything by sticking with x32, and that performance increases when going from x32 to x64 only for certain special workloads.
This question is similar to but more specific than "Which linux version to install: i386 or x64?," which in fact reminded me that I wanted to ask this question.  That question is general, this question is specific to Core 2 Duo since I already have the hardware.
The workload for this server is: light web and EMail server, full NAT for home network, plus light usage NFS/SMB for the home network for music, family photos, and so on.
I think the answer I get will be close to: "Since you've already installed x32 and an in-place upgrade to x64 will be difficult ... and because the gains for x64 are so small for general purpose computing ... wait until your next full install and at that time certainly change to x64."  However, this is an area where my knowledge is very incomplete.  I won't be surprised if the answer is, "Don't bother," and I won't be surprised if the answer is, "Hey, you should do this at your earliest chance."
Comment: Not really... according to Wikipedia (http://en.wikipedia.org/wiki/X64) "The terms x86-64 and x64 are often used as vendor-neutral terms to collectively refer to x86-64 processors from any company."
Comment: I think you answered your own question :)
Comment: aaah. please stop calling 32-bit as "x32" , and "x64" is just microsoft marketspeak.
Comment: Well, while x64 feels like a valid term, shorthand for x86_64 the x32 should probably just be called x86 to avoid confusion with airplanes and thinkpads :)
Answer: In my experience using a 32 and 64 bit variants of FreeBSD on the same hardware, I have seen a measurable (but not huge) benefit to running 64 bit.  64 bit has been around long enough that active projects don't have issues.  The one area this is not necessarily true is for compiled commercial apps (doesn't sound like an issue for your workload).
If you were installing from scratch, I'd recommend 64 bit for your workload, but if you've got a working solution in place, I don't think it's worth changing it.
Answer: The x86_64 architecture has a few other advantages than just the memory space.
The most imporant one is the increased number of registers, which allows the compiler to generate more efficient code.
It's unlikely to make a big difference in the performance of your system though.
Answer: Unless you are in need of the full 4gig memory, you probably don't need to go through the pain of performing a full reinstall of your OS. Everything would need to be recompiled to receive the benefit.
Answer: The only advantage to moving to 64bit is the ability to address greater than 4GB memory.  AFAIK, there aren't any performance benefits to moving to 64bit when working with 4GB or less.
In addition to this, 64bit is still relatively new in the sense that it has not achieved mainstream adoption. (relative compared to the long history of 32bit systems)  You could/can run into compatibility issues running 64bit.
Answer: Keep in mind there are a few closed-source plugins that don't play very nice with 64-bit. The 64-bit flash plugin beta has been unstable in my experience, and nspluginwrapper with the 32-bit plugin has some interesting quirks (but is livable). I've never managed to get Java applets working with a 64-bit browser...
Answer: Performance increase is of 1-3% on calculation intensive applications. The real advantage of 64-bit system is possibility to address more then 4GB of RAM.
On the other hand, the problem is, that there are many closed-source packages available for Linux only in 32-bit packages with 32-bit dependencies. Sometimes can be real pain in the backside.
Answer: It depends.
As mentioned by others, some applications work better on 32bit OS vs. 64bit OS. The reverse is also true
As mentioned by others, 64bit OS allows for more RAM access than even 32bit with PAE enabled, although PAE enabled OS can general access a lot of RAM.
What I have found, much to my dismay, is that the chipset/BIOS puts a limit on the maximum memory I can use. Even with 64bit Ubuntu, my system still can only access 3.2GB of RAM.
Answer: Hm.
This could be done, provided you've taken the time to separate your data out from the rest of the system.
Do a fresh 64-bit install on a separate hard drive.  Then boot the 64-bit install with your old hard drive attached.  Mount the old drive somewhere in /mnt, then glom your data into the new install.  Be sure to pick up settings for various services along the way, as well as little bits and pieces in /var/spool/mail, /root, /home, etc.  Reboot when finished.  If it doesn't work as expected, you lose nothing, your old install is still there.
2009-12-07 Update:
Look at ways you can use background jobs, cron/at scheduling, etc. to help with the transition.  Moving bulk data should be something that occurs in a batch job while you get a good night's sleep; and if that isn't a viable option, then you might have to re-think this, or forgo it altogether.  Remember, you want the system to work for you - not the other way around.
Comment: "you lose nothing" - except 6 hours of your time, which in business speak is a lot of time for no gain ;)
Comment: If you are expecting to take 6 hours of "on the clock" time to do this, then there is something terribly wrong with how you are managing the transition; that, or you shouldn't bother with it at all.  I've migrated live mail systems with less time spent, and that was a paltry 2.5 million messages.  Real time taken: 48 hours.  My work time taken: about 45 minutes.  Plan on backgrounding a job or two, and using the cron/at facilities to help manage this.
Answer: If you want your OS to be able to use more than 3.5Gb of that ram (possibly a bit less depending on what PCI hardware you have), then yes. Because of the memory layout of 32bit systems some of that physical ram will shadowed by PCI devices and bios memory areas.
Comment: I thought that the shadowing was only a problem in a virtual address space, meaning no one process could use all 4 GiB.  However, since the physical memory is mapped to wherever it needs to go, I thought that all 4 GiB could be used.
Comment: On some os's you can use almost all of the 2^32 address space (OS X Leopard comes to mind), however linux always maps some of the virtual address space to the kernel. That is, the kernel takes up some memory in the processes address range. This speeds up context switches, but reduces the amount of memory available to the process


Why I'm having fatal error when adding PHP code to my text format?

Question: So I set the text format to "PHP code" and add the following code:
<?php
function f($x) { return $x; }
?>

When I hit Preview, the page dies with Fatal error: Cannot redeclare f(). I have tried this on two separate Drupal 7 sites, one more or less brand new, with the same result.
Is there a step I'm missing to use D7's PHP filter?
Comment: Did you put this in a node, a block, or somewhere else? Using the PHP input format is often the wrong way to solve a problem. Can you tell us what you're trying to accomplish?
Comment: This was in a new node. I'm generating some nodes using a data set that I have in a text file. Would have used Feeds, but it's a one-off task and Feeds was giving me pain.
Comment: Does it work if you change the name?
Comment: @JoeS You mean like `function very_weird_name($x) { return $x; }`? Sadly, nope, same error. I originally came upon this when I noticed my node_save calls were making two nodes each run.
Answer: I just tracked this down.
What happens is that previewing a node will invoke both the teaser display and full node display, and both of those invoke the PHP code.
My solution was to set the teaser to hidden for the content type (at Structure > Content Types > [your node type] > Manage Fields > Teaser). However, I didn't want to do this for default types like Basic Page, so I created a new type "PHP Tests" and only made the change there.
So I think this shows how PHP in nodes can get ugly, but for people like me who basically want to eval code in the Drupal environment without making a module sometimes, the above is an okay solution.
Answer: Nodes are meant for content, not for custom code. To me, your question looks like "I want to drive my car in reverse, but the steering wheel is on the wrong side. Please help my fix my car." I'd rather teach you how to drive forward :-)
The "Drupal way" to run your own code in your site is to create a custom module. That may sound difficult, but it's not.
First, you create a folder in sites/all/modules. Use the name of your module as folder name, I will use 'mymodule' as example.
Second, you create two files in that folder, called 'mymodule.info' and 'mymodule.module'. In mymodule.info, you enter:
name = My module
description = This is an awesome module.
core = 7.x

Adjust the name and description as you like. See the documentation to learn more about .info files.
Third, enter the following in mymodule.module:
<?php
/**
 * Implement hook_module.
 */
function mymodule_menu() {
  $items['my-module'] = array(
    'title' => 'RSS feed',
    'page callback' => '_mymodule_run_import',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function _mymodule_run_import() {
  // Place your custom code here.
}

This code registers the 'my-module' path using hook_menu, which means that Drupal now "knows" that when you navigate to http://example.com/my-module, it needs to run the mymodule_run_import() function.
If you decide to use another name instead of 'mymodule', make sure you replace all occurrences of 'mymodule' (both in file/filder names and in the code) with the new name.
As a final step, you need to enable your module.
I hope that helps.
Comment: I'm sorry but I can't understand why people are upvoting this. I've written dozens of modules, but this is not the question I asked, which was a very specific phenomenon I was trying to understand.
Comment: First of all, my apologies for mistaking you for an unexperienced Drupal user. I have been active in community support for years, and I've seen many new users who tried to solve problems with php code in nodes. Because that is [not recomended](http://2bits.com/articles/free-your-content-php-moving-php-code-out-blocks-views-and-nodes.html), I usually answer those questions like I did here. I do not know the answer to your specific question. People upvote answers if they find them useful, but you do not have to mark it as accepted if my answer did not satisfy your curiosity.
Comment: I do agree, code in nodes is usually bad. My bad, though, for making a stink about an answer others found useful. Thanks for all your work here.
Answer: <?php
  if (!function_exists('f')) {
    function f($x) { return $x; }
  }
?>

"should" make everyone happy :-)  If not, maybe include_once(FILE.php);
Comment: I would only add the note that *all* code must go inside the `if (function_exists('f'))` block, or else it will still run twice. Otherwise good, simple solution; I will accept.
Comment: I thought about that, but, that would be true only if your php was doing something you did't want run twice.  If, however, it was doing something display oriented, eg, 'today's secret word is ' . f(), there would be no harm done by f() running twice.  Of course, you could put some code in and some code out depending.
Comment: That will solve the fatal errors, but please consider implementing a solution which lets you move away from PHP input filter. Agreed, it's available in Drupal 7, but hopefully not for long: http://drupal.org/node/1203886


GNU Parted and Small Spaces Between Partitions

Question: I wanted to install Slackware on my MacBook Pro (6,2).  Because MBP's use GPT instead of MBR, I need to use parted prior to running the installer.  I wanted to use LVM, but I cannot even get that far.  When creating a partition, I get small bits of space between partitions, commonly 0.28MB.  I have tried switching units to mb, then b, in order to get it really fine-grained and make sure it was just sloppy math using units like gb and mb.  When I align I neatly fit the partitions in bytes (b), I get the following error:
(parted) print free
Model:
Disk /dev/sda: 320072933376B
Sector size (logical/physical): 512B/512B
      Number   Start        End           Size           File System
Name  2        209735680B   50209734655B  49999998976B   hfs+ OSX
(parted) mkpart primary ext2 50209734656 50209837056
Warning: The resulting partition is not properly aligned for the best
performance. Ignore / Cancel?

(I would make that a code block, but it looks uglier and more illegiable than before.) So, is there supposed to be space?  Judging all the installs from more automated installations, like Fedora and/or Ubuntu, there is never free space.  So am I missing something here?
Comment: @Dennis Williamson, thanks so much for cleaning that up!  I realize how ugly it was to read.  Haha.
Answer: The easiest way to install Linux on OS X is to run the Boot Camp Assistant to resize your hard drive, and then use a Linux disk instead of Windows once your system reboots. I have not used Slackware, but generally the Linux installer will then allow you to repartition the FAT32 partition that OS X made for Windows, and you can choose swap and ext4 (or whatever). When installing your Linux bootloader (grub/lilo) don't install to the MBR but rather to the first Linux partition.
Once you have Linux installed, check out rEFIt to get a slick EFI bootloader (you still need grub/lilo to load in the correct Linux kernel, rEFIt will not boot Linux on its own).
Comment: Thanks, @alanthing.  I have done all that already (a la BootCamp and rEFIt).  You would need to do that to get this far.  The problem is I do not want to have one giant partition.  I want to have one primary partition (`/boot`) and a logical partition, LVM (logical volume manager) with different groups and volumes (the usual suspects: `/usr`; `/var`; `/root`;) that use ext4/jfs/xfs, what have you, that are expandable or maybe even snapshottable (word?). I cannot figure out disk geometry, and I assumed it to be a n00bish question. Any help? If not, I will go to the SW IRC and report back.
Comment: After getting your large slice from the Boot Camp Assistant, you could boot into a GParted Live CD [http://gparted.sourceforge.net/livecd.php] and create your partitions with the GUI so you don't have to calculate geometry by hand. You can choose all ext3 and then format them later during your Slackware install process.
Answer: It appears the answer is two-fold, according to more the Arch forums.  I need to use parted --align and use the ArchBoot iso, not the generic install disk, to get all the extra goodies with GPT disk support.  I am not sure if both are connected, or it is the he mentions this ISO because the grub version is old in the default installer and will screw things up for me later.  Still, thanks for all the help and suggestions.  Apparently I was not being so silly after all.


How to play E major first inversion smoothly with the right hand on the piano/keyboard

Question: I am a beginner keyboardist and I am facing some issues when I play the first inversion E major chord:

With my right hand I play the chord using the thumb (finger number 1) for the G♯, finger n. 2 for B and n. 5 for E (the circles represent approximately where each finger hits each key).
The problem is that very often instead of hitting B, I hit the black key B♭/A♯, and more rarely I hit D♯ instead of E.
Is there a proper way to play this chord so that I decrease the chances of hitting A♯ and/or D♯. What am I doing wrong?
Maybe I'm not hitting each key where I should? Or maybe the position
of my hand is not correct?
How do you guys deal with this chord?
Answer: Chances are that you will someday encounter music requiring the right hand to play the larger chord E G# B E. Any fingering but 1 2 3 5 for that chord would be very unusual regardless of hand size and shape. There's your clue: try 2 3 5 here.
You could also encounter the larger chord G# B E G#. Here the normal fingering would be 1 2 4 5. That means 1 2 4 is also possible, and if you can play B and E with 2 and 4, you can also play them with 2 and 5.
Trying these larger chords might help to point you in the right direction by forcing your hand into a position that works. Programming the spacings of chords into your hand is essential but takes time.
Comment: I disagree that G#BEG# should be played 1245. I believe it should be 1235. The stretch from 4-5 in the first is too big and over time will cause injury.
Comment: For me, 1235 is almost unplayable: B and E with 2 and 3 is a large stretch. However 1245 is effortless for me. It's the same old adage: we all have hands of different shapes and sizes, and it's seldom that one fingering fits all.
Answer: It's not always possible to avoid using thumb on a black key, but try to do so if you can. The thumb is way shorter than the other digits, so you'll have to push the whole hand further into the keys. This then puts the fingers 2, 3, 4 and 5 too far, making them press between the black keys to play the white ones.
Or, you can turn the whole hand sideways - again, not ideal.
You can probably play E G# B and the next E in one go, using 1, 2, 3 and 5 with r.h. Stick with it, and play the first inversion with 2, 3 and 5.
Answer: 1,2,5 is a very commonly-used fingering for this chord, and the contact points you mark on your diagram are about right. Maybe 2 should be a little more forward. Yes, there are circumstances where 2,3,5 would be appropriate, but you need to be able to cope with fingering this chord shape 1,2,5 as a basic piano-playing skill, even if it DOES put the thumb on a black note.
If you're hitting Bb instead of B, your hand is positioned wrong. You are not placing your fingers over the right notes.  Correct it.
Answer: Most likely the position of your ARM is not correct. These are things you need to work on with your teacher because they need to see if you are doing something wrong or not doing something right. So, don't try any of this on your own since they are isolated movements which MUST be coalesced with all the others simultaneously.  Isolate them and you can run into trouble.  This is presuming your teacher knows what they are doing. If not, get a new teacher because they will cripple you in years to come. Here is a quick video to give you ideas:
Comment: I don't lock in fingering.  Fingering is contingent upon where you are coming from and where you are going. Whenever possible I group notes or patters together to get a physical shape to the phrase.  Since this is a stand alone phrase, I would want to minimize stretching as much as possible and 2 to 5 is a much smaller stretch than 3 to 5.  Again, it would depend on what notes lead up to this phrase and where the arm is going after.
Comment: Thank you very much for the video and for your explanation and care! When you play the chord fast, e.g. quarter notes, do you use 2, 3 and 5 like the others suggested, or do you use 1, 2 and 5?
Answer: I just tried playing this on the piano. The only way I can get my thumb in that far on this inversion is if I turn my wrist, which is not something that should be done. Make sure your wrist is completely straight then kind of "insert" your fingers forward onto the keys. Pay careful attention to what your fingers are doing (really look at the side of your hand where the pinky is) and make sure it is not tilting down toward the wrist.


lim sup inequality (with infinite sum)

Question: Question: If $\limsup_{n\to\infty} a_n\leq l$, how do we show that $\limsup_{n\to\infty}\sum_{i=1}^n a_i/n\leq l$?
Is this question even valid? Consider the constant sequence $a_n\equiv 1$, then we may take $l=1$.
However $\limsup_{n\to\infty}\sum_{i=1}^n 1/n$ is the harmonic series which diverges.
Just to check if there is anything wrong with the question? (It is a PhD qualifying exam of a certain school.) I may have made a mistake on my part too.
Thanks a lot.
Comment: It's $\frac{1}{n}$, not $\frac{1}{i}$. Maybe it's better to write $\frac{1}{n} \sum_{i = 1}^n a_i$.
Comment: Oh i see... Thanks a lot
Answer: Hint:
For any $\epsilon > 0$ there exists $N$ such that $a_i < l + \epsilon$ for all $i > N$. Then take $\limsup$ of both sides of
$$\frac1{n}\sum_{i=1}^n a_i = \frac1{n}\sum_{i=1}^N a_i+ \frac1{n}\sum_{i=N+1}^n a_i< \frac1{n}\sum_{i=1}^N a_i+ \frac{n-N}{n}(l+\epsilon)$$

lim sup inequality (with infinite sum)


How to convert this map reduce in aggregate framework?

Question: i've still done this map/reduce/finalize function using mongoDB.
This is how i need that mongoDB executes that aggregation:
db.house_results.mapReduce(function(){
    emit(this.house_name.toLowerCase(),this);
    },function(key,values){
        var house = {name:key,address:"",description:"",photo:[],lat:0,lng:0,rooms:[]};
        values.forEach(function(house_val) {
           /*Address*/
            if(house.address=="")
              house.address = house_val.house_address;

           /*Photo*/
           if(!house_val.photo in house.photo)
              house.photo.push(house_val.house_photo);

           /*Description*/
           if(house.description=="")
              house.description = house_val.house_description;

           /*LAT - LNG*/
           if(house.lat==0 || house.lng==0){
              var house_position = house_val.house_position;
              if(house_position && house_position.lat && house_position.lng){
                 house.lat = house_position.lat;
                 house.lng = house_position.lng;
              }
           }
           if(house.lat==0 || house.lng==0){
              if(house_val.house_lat && house_val.house_lng){
                 house.lat = house_val.house_lat;
                 house.lng = house_val.house_lng;
              }
           }

           if(house_val.rooms)
                house.rooms.push(house_val.rooms);
        });

        return house;
    },
    {
        out   : "map_reduce_house_test",
        finalize:function(key,house_val){
            if(house_val.address==undefined){ // JUST ONE RESULT IN MAP FUNCTION -> REDUCE FUNCTION IS IGNORED -> FINALIZE IS SOLUTION
               var house = {name:key,address:"",description:"",photo:[],lat:0,lng:0,rooms:[]};
               /*Address*/
               if(house.address=="")
                 house.address = house_val.house_address;

               /*Photo*/
               if(!house_val.photo in house.photo)
                  house.photo.push(house_val.house_photo);

               /*Description*/
               if(house.description=="")
                  house.description = house_val.house_description;

               /*LAT - LNG*/
               if(house.lat==0 || house.lng==0){
                  var house_position = house_val.house_position;
                  if(house_position && house_position.lat && house_position.lng){
                     house.lat = house_position.lat;
                     house.lng = house_position.lng;
                  }
               }
               if(house.lat==0 || house.lng==0){
                  if(house_val.house_lat && house_val.house_lng){
                     house.lat = house_val.house_lat;
                     house.lng = house_val.house_lng;
                  }
               }

               if(house_val.rooms)
                  house.rooms.push(house_val.rooms);

               return house;
            }else
               return house_val;

        }
    }
);

Is there a way to simplify that functions and/or is better to do the same with aggregation mongodb's function?
Which could be the fastest and simplier method?
Thanks!
Answer:
There isn't really much going on in this mapReduce other than taking the first values from various fields for the common grouping key and otherwise pushing some other values onto arrays.
Therefore everything is very much the same for aggregation:
db.house_results.aggregate([
    { "$group": {
        "_id": { "$toLower": "$house_name" },
        "name": { "$first": { "$toLower": "$house_name" } },
        "photo": { "$push": "$house_photo" },
        "address": { "$first": "$house_address" },
        "description": { "$first": "$house_description" },
        "lat": {
            "$max": {
                "$cond": [
                   { "$gt": [ "$house_lat", "$house_position.lat" } },
                   "$house_lat",
                   "$house_position.lat"
            }
        },
        "lng": {
            "$max": {
                "$cond": [
                   { "$gt": [ "$house_lng", "$house_position.lng" } },
                   "$house_lng",
                   "$house_position.lng"
            }
        },
        "rooms": { "$push": "$house_rooms" }
    }}
])

The only real difference there is the conditional handling of the "lat" and "lng" output using primarily the $cond operator.
Noting that "_id" and "name" have the same thing in them, but that is what the map reduce is doing.
Take a good look at the aggregation operators for reference, but really your data should look like this rather than it's present form, which appears to be a de-normalized dump from somewhere.
Also for reference, It probably isn't affecting you in this case, but this is the wrong way to write a mapReduce. The output from the "map" function is different to that from the "reduce" function, notably the arrays.
Even though these will only have one element in them they "should" be emitted as an array element from the "map" function as well and treated as if they where already an array element by the "reduce" function.
This is because with larger "grouping", not all matching key values are sent into the reduce function at once, and the reducer can be called to combine other values emitted by "map" to the "reduce" function with previously reduced output. That is how large data is handling, and with arrays you run the risk of output like this, with the un-expected embedding of an array within an array:
[ [4,5,6], 7, 8, 9 ]

But this is covered in the documentation where you read carefully.
At any rate, the aggregation pipeline ( one stage) will perform much faster than the present operation. But really change your data as soon as possible.


hibernate3-maven-plugin generates java.lang.ClassNotFoundException: org.hibernate.util.ReflectHelper

Question: I am trying to generate a schema (ddl) from my orm.xml file.  I'm using hibernate3-maven-plugin.  I'm using JPA with hibernate as the implementation, but am open to other implementations or maven plugins.  The code in my pom.xml is:
<code> <build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>hibernate3-maven-plugin</artifactId>
            <version>3.0</version>

            <configuration>
                <hibernatetool>
                    <jpaconfiguration persistenceunit="unitname" />

                    <hbm2ddl export="false" create="true"
                 update="true" format="true" outputfilename="schemaDiff.ddl" />

                </hibernatetool>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>
The command I run is:

mvn hibernate3:hbm2ddl -e

The error I received is:

Caused by: java.lang.NoClassDefFoundError: org/hibernate/util/ReflectHelper
          at org.hibernate.tool.ant.JPAConfigurationTask.createConfiguration(JPAConfigurationTask.java:32)
          at org.hibernate.tool.ant.ConfigurationTask.getConfiguration(ConfigurationTask.java:54)
          at org.hibernate.tool.ant.HibernateToolTask.getConfiguration(HibernateToolTask.java:302)
          at org.hibernate.tool.ant.Hbm2DDLExporterTask.createExporter(Hbm2DDLExporterTask.java:51)
          at org.hibernate.tool.ant.ExporterTask.execute(ExporterTask.java:39)
          at org.hibernate.tool.ant.HibernateToolTask.execute(HibernateToolTask.java:186)
          at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
          at java.lang.reflect.Method.invoke(Method.java:597)
          at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
          ... 28 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.util.ReflectHelper
          at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
          at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244)
          at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230)
          ... 40 more
Comment: See that answer for JPA 2.1 full solution :
http://stackoverflow.com/questions/27314165/generate-ddl-script-at-maven-build-with-hibernate4-jpa-2-1/27314166#27314166
Answer: George Herolyants presents a solution here.
http://doingenterprise.blogspot.com/2012/05/schema-generation-with-hibernate-4-jpa.html


utilizing Grönwall's inequality to prove a property of two solutions of a differential equation

Question: Consider the differential equation $\dot{x} = f(t, x)$ with $f$ being a continuously differentiable function from $G \to \mathbb{R}^n$, with $G \subset \mathbb{R} \times \mathbb{R}^n$ an open subset. Let $f$ be (globally) Lipschitz on $G$ with respect to $x$, with a Lipschitz constant $L > 0$.
I want to prove: if $x_1$ and $x_2$ are two solutions of the differential equation $\dot{x} = f(t, x)$ that are defined on an interval $[a, b] \subset \mathbb{R}$, then we have that:
$$||x_1(t) - x_2(t)|| ≤ ||x_1(a) - x_2(a)||e^{L(t-a)}$$
for all $t \in [a, b]$.
I was looking at using the Grönwall's inequality to solve this.
I see that, in order to use Grönwall's inequality, I need to show that
$$ ||x_1(t) - x_2(t)|| ≤ ||x_1(a) - x_2(a)|| + L\left\lvert\int_a^t ||x_1(t) - x_2(t)||ds\right\rvert$$
for all $t \in [a, b]$. However, that's where I got stuck. This inequality is obviously true for $t = a$, but how can I show this for $t > 0$? I know that I need to somehow use the fact that $f(t, x)$ is Lipschitz continuous with the constant $L > 0$; but why does that tell me that the integral on the RHS always "grows fast enough"?
Answer: First, the absolute value around the integral in unnecessary, since norms are nonnegative, the integral will be nonnegative.
Let's start by creatively adding $0$ and using the Triangle Inequality:
$$\|x_1(t) - x_2(t)\| = \|x_1(t) - x_1(a) + x_1(a) -x_2(a) - (x_2(t) - x_2(a))\|$$
$$ \leq \|x_1(a) - x_2(a)\| + \|x_1(t) - x_1(a) - (x_2(t) - x_2(a))\| $$
By the Fundamental Theorem of Calculus:
$$ = \|x_1(a) - x_2(a)\| + \left\| \int_a^t x_1'(s) - x_2'(s)\,ds \right\| $$
Since $x_1$ and $x_2$ are solutions to the ODE:
$$= \|x_1(a) - x_2(a)\| + \left\| \int_a^t f(s,x_1(s)) - f(s,x_2(s)) \,ds \right\|$$
Now we use the fact given here and we get
$$\leq \|x_1(a) - x_2(a)\| + \int_a^t \|f(s,x_1(s)) - f(s,x_2(s))\| \,ds$$
By the Lipschitz condition and monotonicity of the integral:
$$  \leq \|x_1(a) - x_2(a)\| + \int_a^t L \|x_1(s) - x_2(s)\|\,ds $$
and the result follows.


how to generate documentation on parse server application

Question: I was wondering if we can generate documentation based on our schema/classes in our parse server powered express application.
Also I have around 15 cloud functions which need to have specific post body. It'd be great to have documentation generator
Comment: What you have tried so far? Show some code.
Comment: + Ataur Rahman Munna, I believe there's no reference pointing how to generate documentation in the parse documentation and searched on google as well. how do I "try" coding out of nothing
Comment: So can you used `swagger-ui` https://swagger.io/ ?
Answer: I don't know of any APIDOC generator for Parse class schemas. A good starting point, however, might be the Schema APIs which allow you to fetch a JSON description of the class schemas in your app. They return a simple format which you can transform and feed into a documentation tool of your choice.
For Cloud Code functions, there's no way to do anything automated IMO: the parameters to and the results from a function are not defined explicitly anywhere, the function just gets and returns plain JavaScript objects -- as long as it can handle the request params and the client can handle the response, it works. As a workaround -- again -- you could write your Cloud Code functions as plain functions, annotate them with one of the many JS type information systems (or even use TypeScript), thus enabling the use of APIDOC tools; these plain functions are expose to Parse via a simple wrapper which handles the translation from the request object to the function's input parameters and from the function's result (or error) to the response object.


how to build vocal stamina

Question: I have good technique. I'm self taught but I know all about singing and its techniques. I can use head voice and I'm comfortable with it. The problem I have is that I can't go through two or three songs without my voice starting to crack or just feeling tired. I don't force notes just so you know I try to sing as comfortably as I can.
How can I build up my voice's strength so I can last through a whole concert?
Answer: I think I know what you mean, I've faced the same issues from time to time.
As I understand you're not a professional singer. Yes, a voice should become stronger over time as you train more. The muscles that control your voice will indeed get a bit stronger but to be honest I don't think singing should be compared to weightlifting for example. It's more about mental training and proper coordination.
There's still a big warning sign. When somebody sings the voice should not deteriorate but instead it should improve and get warmed up over time. That alone tells me that it's likely that there's something wrong with your technique...it could be anything. It's common when someone overuses their voice that it feels "tired" for a sort amount of time afterwards. After all, if you're still not a pro singer you can't really know if you're singing right unless you sound good and face no problems. Until then you're just guessing.
Comment: I'm guessing you're trying to sing hard songs right? For a male that might include songs with lots of notes in the mid/upper 4th octave. Try not to push or reach up to the notes. Visualizing it as if you're landing on top of them might be more helpful. Also at first try to hit them by thinning out your voice and making it light and slightly whiney and THEN build on top of that more power. Think Bee gees, Axl rose or something along those lines. Sing as high as youre comfortable.Be careful..when I say "light" it doesnt mean letting go of your diaphragmatic support. You must adjust it as needed.
Comment: I sing and play guitar with my friends so yeah I'm not a professional. So with training I'll get better I guess thanks for answering
Answer: Singing is of course something requiring training and/or endurance.  If you ask "how do I get to run a marathon", the answer will involve lots of running.
That being said, if you are hoarse/strained after two or three songs, that's comparable about being shot after going up two stories of stairs.
If that's your starting point of doing a marathon, either you are doing something quite wrong and/or you are woefully out of shape.
"Just do more and it will come naturally", just like with the running analogy, would appear to be reckless advice then without looking closer.  Try getting some actual supervision for a while.  It does not necessarily need to be one-on-one voice training: some choral work or basic singing courses might be enough to have somebody have an ear on you and have you avoid doing staggeringly counterproductive things.
Answer: I have the same issue. A friend of mine gave me a tip which helped me. Try to sing from deeper down your throat. It is hard to explain, but basically, by doing so, you will stress your upper part of the throat less.
Answer: This might help, in my experience I've sang my heart out for a very long time and my vocal endurance slowly built up. I've always heard you need to workout to be a good singer but I had lifted weights for a while too but my progress to build vocal endurance was still slow. I've recently (7 months ago) injured my wrists and I'm still recovering. The doctor told me to I need to do aerobic exercise to help my healing. This was the key for my singing. After heavy endurance running and biking I started to see a large improvement in my vocal endurance. I've heard from my vocal teacher in college that when the body gets tired, the voice is the first to be affected. Having high arobic endurance means it takes much longer to get tired. Also check your diet. There are certain foods that seem to produce mucus on the vocal cords. If you are eating these foods before you sing it would cause mucus build up. Singing with extra mucus is a sure way to wear your vocal chords out quicker. I hope this helps everyone out
Comment: Do you know which foods specifically, or can you link a reference?
Comment: @MatthewRead - Dairy is the one I know of.
Answer: Of course it takes time for your voice to get used to a lot of singing, but you can't compare it to running a marathon. You just don't get better by doing it. You get better by knowing what you do, discover mistakes in your technique and directly working on those problems.
If your voice is strained after a few songs, you propably have a problem with your breathing, which is propably the most important aspect in singing. You may feel that you don't push or force the notes, but the fact that your voice starts to crack that fast tells me otherwise.
We could exchange a lot of tipps and how to do it right in theory, but in my opinion you won't get the results you want from a board on the internet. If you really want to sing and don't want to ruin your voice, go get a vocal coach. I know, they cost a lot of money, but it's worth it. The right teacher can help you improve your voice and your overall singing experience a lot, so it's worth the money, even if you are no professional.
Answer: You feel tired because you aren't using your voice properly. Do you use correct breath support? Are your muscles trained and strong? Are you singing according to your physical region (bass, baritone, tenor?).
To answer all these questions, and to reach your objectives, I recommend you to search for a good teacher. I found a great singing teacher and it changed my life forever.
We can only get what we want if we dedicate and practice a lot (with correct supervision, of course).
Hope this helps. No shortcut is good in the case of voices. You can damage your own if you don't practice correctly. Believe me.

how to build vocal stamina


How can I display custom data from the database in a View?

Question: I'm working to create a new website in Drupal 8 and cannot figure out how to reference custom table data within a View.
Specifically, I have a script that is taking data from an external DB and populating it into my Drupal DB into custom tables. How can I allow Views to see this data?
In Drupal 7 I have experience using the Forena module and the Data and Schema modules to accomplish same DB and external DB references, but what I'm finding is that support for these three modules in Drupal 8 appears to be lacking, making me think that there is a better way to do this in D8 that everyone knows about but me. :)
I'm not sure if I'm just not researching correctly, but I'm unable to find a clear answer about how to go about obtaining this functionality in Drupal 8. Drupal 8 is so different and I'm not sure if I should be looking for a contributed module or if this is something I would code directly.
Hopefully someone can point me in the correct direction?
Comment: Maybe [Views Custom Table](https://www.drupal.org/project/view_custom_table) can help.
Answer: Ok, yeah, I feel a bit silly now and was making this too difficult. There is a module for this for Drupal 8!
I was able to accomplish what I needed with Views Custom Table.
Thank you prkos for the comment.


$\mathbb{S}^2/{\sim} \simeq \mathbb{S}^2\vee\mathbb{S}^1$ where $(0,0,1)\sim (0,0,-1)$

Question: I am trying to understand the example $0.8$ of Hatcher's book (pag $11$), I only know singular homology and I do not know anything about CW-complex, so it is difficult to interpret what it says there. How can I get to that $\mathbb{S}^2/{\sim} \simeq \mathbb{S}^2\vee\mathbb{S}^1$ where $(0,0,1)\sim (0,0,-1)$ without using CW-complex structures, only with basic knowledge of singular homology?
Thank you!
Comment: You could try reading the material prior to the example on the basics of CW complexes.  It's only a few pages.
Comment: LaTeX pro tip: use `{\sim}` instead of `\sim` after $/$ (or in any other context where $\sim$ is not being used as a connective), e.g. $\mathbb{S}^2/{\sim} \simeq \mathbb{S}^2 \vee \mathbb{S}^1$ vs. $\mathbb{S}^2/\sim \simeq \mathbb{S}^2 \vee \mathbb{S}^1$. [I fix'd it in your question.]
Answer: Here is a sketch of a more direct proof.  As in Hatcher's argument, we just need to show the quotient maps $X\to X/A$ and $X\to X/B$ are homotopy equivalences, to get a homotopy equivalence between $X/A\cong S^2/S^0$ and $X/B\cong S^2\vee S^1$.  I will sketch this for the quotient map $f:X\to X/A$; the map $X\to X/B$ works similarly.
To show $f$ is a homotopy equivalence, we need to find a homotopy inverse.  We can map $X/A$ to $X$ by collapsing each of the two vertical circles in the picture of $X/A$ to a point and then similarly collapsing each vertical cross-section to the right of them in the picture to two points (one on top and one on bottom).  This turns the entire right half of the picture into an arc, which we can then map to the arc $A$ in $X$,  This thus defines a map $g:X/A\to X$.
To show $g$ is a homotopy inverse of $f$, we must show $gf$ and $fg$ are homotopic to the identity.  What does $gf$ do?  It collapses $A$ to a point, and then shrinks bits of the sphere that were around the endpoints of $A$ to arcs and maps them to $A$ (with $A$ itself all mapping to the midpoint of $A$), stretching out the rest of the sphere to cover the whole sphere.  Intuitively, this is homotopic to the identity because we can start with the identity and gradually shrink $A$ down towards the midpoint, while stretching more and more of the sphere surrounding its endpoints to map to the rest of $A$ and stretching the rest of the sphere to fill out the sphere.
How about $fg$?  It collapses the right half of $X/A$ down to an arc, and then shrinks that arc back down to a single point and stretches the left half of $X/A$ to cover all of $X/A$.  Again, this is homotopic to the identity because you can do this process gradually, shrinking more and more of the right half to a point and gradually stretching the left half to cover more and more of the space.
Now of course, none of this is a rigorous proof; I've just given rough geometric descriptions of all the maps involved.  Actually writing them down explicitly can be done but is quite a pain.  This is the value of the basic facts about CW complexes that Hatcher is using.  In particular, using the general result of Proposition 0.17 and some general facts about extending homotopies over CW complexes (specifically, Proposition 0.16), he can conclude that $f$ is a homotopy equivalence without needing to find all the relevant maps explicitly, using just the fact that $A$ is contractible and is a subcomplex of $X$.
Answer: I don't think this example refers to any background in homology. The point is, by introducing the intermediate picture of $X$, it is clear $X/A$ and $X/B$ are both homotopy equivalent to $X$. Thusly $X/A$ and $X/B$ are homotopy equivalent. Since $X/A$ is $S^1/\sim$, where the relation is north and south poles being glued together, and $X/B$ is $S^2 \wedge S^1$, they are homotopy equivalent.
Sorry for the format, but I am writing on phone.
Comment: The step that you call "clear" is hiding all the work, and in particular is relying on a technical result that is what OP seems to want to avoid.
Answer: I agree with the previous answer that this is nothing to do with homology. It is about the homotopy type of adjunction spaces.
7.5.5 (Corollary 1) of Topology and Groupoids says that if $(X,A)$ is cofibred and $f \simeq g: A \to B$ then there is a homotopy equivalence of adjunction spaces $B \cup _f X  \simeq B \cup_g X \; \text{rel}\; B$.
So in your picture the space $X$ is obtained by attaching an internal $I= [0,1]$ joining the North and South poles and in what is called $X/B$ is also obtained by mapping $0,1$ to the South pole.


$L^1(\mathbb{R}^n)$ functions not in $\mathcal{H}^1(\mathbb{R}^n)$

Question: I am wondering how to imagine the Hardy space on $\mathcal{H}^1(\mathbb{R}^n)$ and in particular what sort of functions are in $L^1(\mathbb{R}^n)\backslash\mathcal{H}^1(\mathbb{R}^n)$. Furthermore, is it possible to find explicit examples of functions in $\partial (L^1(\mathbb{R}^n)\backslash\mathcal{H}^1(\mathbb{R}^n))$?
$\mathcal{H}^p(\mathbb{R}^n)=L^p(\mathbb{R}^n)$ for $p>1$, but what is the "problem"/ difference when $p=1$ ( or $p\leq 1)$?
Thanks!
Answer: Let $f(x) \in L^1(\mathbb R^n)$ satisfy $\int_{\mathbb R^n} f(x) \, dx = C \ne 0$.  If you are using the maximal characterization of $H^1$, then
$$ Mf(x) := \sup_{r>0} \frac1{w_nr^n} \int_{y\in B(x,r)} f(y) \, dy \ge \frac1{2^nw_n|x|^n} \int_{B(x,2|x|)} f(y) \, dy \sim \frac C{|2x|^n} \text{ as $x \to \infty$}.$$
Here $w_n = |B(0,1)|$.  Hence $Mf \notin H^1$.
The problem is that the inequality $\|Mf\|_p \le c_p \|f\|_p$ is only true if $p>1$.
Also $\partial(L^1\setminus H^1) = L^1$ because $L^1\setminus H^1$ is dense in $L^1$.  This isn't really a meaningful question, because $L^1$ and $H^1$ have different topologies.
Comment: Thanks for your answer. So $\mathcal{H}^1$ is quite a "small" space...
Comment: Professor Montgomery-Smith: Although any $f\in L^{1}(\mathbb{R}^{n})$ which satisfies $\int_{\mathbb{R}^{n}}f\neq 0$ clearly doesn't belong to $H^{1}(\mathbb{R}^{n})$ by the moment requirement, I don't see why your post answers the OP's question. It's my understanding that $H^{1}(\mathbb{R}^{n})$ isn't characterized by the Hardy-Littlewood maximal function as $Mf\notin L^{1}(\mathbb{R}^{n})$ if $f\neq 0$ a.e.
Comment: @MattRosenzweig I think you are correct.  Perhaps I should have used $Mf(x) \sup_{t>0} |P_t*f(x)|$ where $P_t$ is the Poisson kernel, or some other suitably smooth sequence of functions satisfying $P_t(x) = |t|^n P_1(t x)$.


Android sqlite column sum?

Question: First Of All i am new to programming currently learning Android .And also this is my first Question over here so pardon if any mistake. The thing is i am stucked in how to get total of database column.
here's my code to retrieve the data from the sqlite helper.
private void GetColumnTotal() {
    SQLHelper ColumnTOtal = new SQLHelper(this);
    try {
        ColumnTOtal.open();
        int total = ColumnTOtal.Total();
        ColumnTOtal.close();
        RemainingAmount.setText(""+total);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

`And heres the code of my sqlite helper . i am posting it all hope you guys help.
public class SQLHelper {
public static final String KEY_ROWID = "_id";
public static final String KEY_MONEY = "SpendedMoney";

private static final String DATABASE_NAME = "BudgetDB";
private static final String DATABASE_TABLE = "BudgetTable";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private SQLiteDatabase ourDATABSE;
private DBHelper ourHelper;

public SQLHelper(Context context) {
    ourContext = context;

}

public SQLHelper open() throws SQLException {

    ourHelper = new DBHelper(ourContext);
    ourDATABSE = ourHelper.getWritableDatabase();
    return this;
}

public void close() {
    ourHelper.close();
}

public long createEntry(String money) {
    ContentValues cv = new ContentValues();
    cv.put(KEY_MONEY, money);

    return ourDATABSE.insert(DATABASE_TABLE, null, cv);
}

public String getData() {
    String[] columns = new String[]{KEY_ROWID, KEY_MONEY};
    Cursor c = ourDATABSE.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_MONEY);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        result = result + c.getString(iRow) + " :- " + c.getString(iName) + "\n";
    }
    return result;
}

public int Total() {
    Cursor cur = ourDATABSE.rawQuery("SELECT SUM(SpendedMoney) FROM BudgetTable", null);
    if (cur.moveToFirst()) {
    }
return cur.getInt(0);
}

private static class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + "(" +
                        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        KEY_MONEY + " TEXT NOT NULL);"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }
}

Solved!! Thanx everyone. And also the one who downvoted my question.. :)
Comment: `public Cursor Total()` should be `public int Total()`, since you're not returning the whole cursor, but only an integer value.
Comment: If you get an error message, you must show it.
Answer: This error message is not related to SQLite. Somewhere else you are using 0 where a string resource id is expected. One example could be that you display the result using setText(int) on a TextView instead of setText(CharSequence). The stacktrace should tell you where.
Comment: Thanx! it helped . But the sum i get is 0 dont know why can you help ?
Comment: Are you sure that the table contains data ? What is the result if you replace `SUM(SpendedMoney)` whith `count(*)` ?

Android sqlite column sum?


Terminology for an element of a partition?

Question: Suppose I'm dividing some region $\Theta \in \mathbb{R}^n$ into subregions $\theta_i, i=1,2,3$ such that $\theta_i \cap \theta_j = \varnothing, i\ne j$ and $\bigcup_i \theta_i = \Theta$.  I might say (perhaps loosely, even technically incorrectly) that I am partitioning the region $\Theta$.
Thus, a "partition" would be a particular configuration of $\{\theta_1,\theta_2,\theta_3\}$ that satisfies the aforementioned conditions.  But what would an element of a partition be referred to as?
Since I am partitioning a "region", it makes sense to say that I am partitioning a region into "subregions", but at a higher level, what is a correct term for an element of a partition?
Comment: Your definition of *partition* is the standard one: http://en.wikipedia.org/wiki/Partition_of_a_set.
Answer: The terms cells, or classes, or blocks, even parts of a partition are often used to describe the "sub-regions" of a given partition, depending on the nature and/or context of the partition.
See for example, Partition of a Set.
Comment: I would say "cell", or "block" in your example. "Class" is used particularly when referring to the partition of a set determined by an equivalence relation: elements in the same "equivalence class" are related by the relation.
Comment: Would "cell" or "class" or "block" be more appropriate in the type of partition I described?
Comment: @amWhy: Nice to feel like you helped! +1
Comment: I just remember my own first encounter with the notion of a partition, and I kept confusing "partition" with one of it's classes/cells: So, e.g., I wanted to say "partition of even integers union partition of odd integers = integers"...For lack of a handy term to call one of the "subdivisions" created by a partition.
Comment: What about "coset"? Is that ever used for elements of an abstract partition, or is it only used for groups?
Answer: I have usually seen them referred to as parts or blocks of the partition. Partition of a Set


Configure Apache so it doesn't display a site for IP based vhosts

Question: I have a CentOS LAMP server. It has several vhosts configured. If I navigate to:
<code>http://xxx.xxx.xxx.xxx/  (server IP)
</code>
Apache displays one of the sites. How can I configure Apache to show nothing or perhaps a 403 Forbidden? If it could show a forbidden before checking for malformed requests that would be even better.
Answer: The first vhost that Apache picks up from your configuration is the default one picked when the name that the client sends doesn't match any configured vhost, so you'll have to make a vhost that sends 403 errors and ensure that it's picked up first in the httpd config.
Comment: `Order Allow,Deny`, `Deny from all`.  Put it in a `` block in the default (first) vhost.
Comment: Will this show the 403 even if it's a malformed request where a 400 would normally be served? Also what's the syntax in the vhost directive to issue the 403?
Comment: Thanks, the 403 can also be done by removing the `DocumentRoot` in the first vhost.


Calculate $\lim_{(x,y)\to(0,2)} (1+x)^{y/x}$

Question: Calculate $\lim_{(x,y)\to(0,2)} (1+x)^{y/x}$
I have strong belief that this limit exists as I tried some basic lines ($y=2,y=x+2$), and they both gave me the form $1^\infty$
So I tried doing this.
$$\lim_{(x,y)\to(0,2)} (1+x)^{y/x}=\lim_{(x,y)\to(0,2)} e^{(y/x)\ln(1+x)}$$
and here I am stuck. Evaluating the limit directly would give something like $e^{(2/0)\ln(1)}=e^{(\infty)(0)}$ which is still intederminate.
Comment: $\lim_\limits {x\to 0} (1+x)^{\frac 1x} = e$
Answer: You can compute
$$
\lim_{(x,y)\to(0,2)}\frac{y\ln(1+x)}{x}
$$
which is easy, because by standard theorems on limits
$$
\lim_{(x,y)\to(0,2)}\frac{y\ln(1+x)}{x}=
\Bigl(\lim_{(x,y)\to(0,2)}y\Bigr)
\Bigl(\lim_{(x,y)\to(0,2)}\frac{\ln(1+x)}{x}\Bigr)=
2\lim_{x\to0}\frac{\ln(1+x)}{x}=2
$$
Then your limit is $e^2$, because the exponential is continuous.
Comment: Can you conclude this? $$\lim_{(x,y)\to(0,2)}\frac{y\ln(1+x)}{x} = 2\lim_{x\to0}\frac{\ln(1+x)}{x}$$ You're just taking the limit along the line $y= 2$, which is not the only way you can approach $(0,2)$.
Comment: @mechanodroid Multiplication is continuous. I added the steps.
Comment: I get it, thanks. But then since exponentiation is also continuous, we could have calculated it directly: $$\lim_{(x,y)\to(0,2)} (1+x)^{\frac yx} = \left(\lim_{(x,y)\to(0,2)} (1+x)^{\frac1x}\right)^{\lim_{(x,y)\to(0,2)} y} = \left(\lim_{x\to 0}\, (1+x)^{\frac1x}\right)^{2}= e^2$$
Comment: @mechanodroid Yes, but I prefer to avoid those complications.


in python what's the relation between the loop variable and the elements in list when we do for loop?

Question: Here are several list: a, b, etc
I want to make some change of them respectively, but I'm confused with the behavier of for loop.
for example:
if we do
a, b = range(5), range(5,10)
for x in [a, b]: x += [0]
print(a,b)

we get
([0, 1, 2, 3, 4, 0], [5, 6, 7, 8, 9, 0])

a,b are modified.
but if we do
a, b = range(5), range(5,10)
for x in [a, b]: x = x + [0]
print(a,b)

we get
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])

a,b aren't modified.
I'm confused, what's the relation between x and a? When or how I can modify the value of a with x?
And by the way, what's the difference between a+=b and a=a+b?
Anyway, I find a solution that we can do like this
a, b = range(5), range(5,10)
lis = [a, b]
for i, x in enumerate(lis):
    lis[i] = ...

then we can modify values of a & b. But this method need make a extra list.
And there's anther solution
for x in ['a', 'b']:
    exec(x + '=' + x + '+ ...')

And an easier solution
a, b = range(5), range(5,10)
for x in [a, b]: x[:] = x + [0]
print(a,b)

We will find a,b are modified :)
Answer: The relation is the same as with all variable binding in Python.  The name is bound to the value.  The differences you are seeing are because you are doing different things, sometimes, operating on the value and sometimes on the name.
For lists, += extends the list in-place --- that is, it modifies the original list.  Thus the modifications are visible everywhere that list is used.
When you do x = x + [0], you rebind the name x to a new list (formed by adding the old list plus [0]).  This does not modify the original list, so other places that use that list will not see the change.
If you search around for Python questions on "variables", "names", "values", "call by refernce" and the like you will find other discussions of this.  Here is a question discussing a similar issue in the context of function-parameter binding.  The principles are the same in for-loop variable binding.
Comment: See this [related answer](http://stackoverflow.com/a/2022044/1988505) explaining more about creating a new list by adding to it vs. inserting into an original list.
Comment: Thanks a lot for your answer, it's much clearer for me now. It seems that I should learn more basics about python:)
Answer: The line:
x += something

changes a list in place, while:
x = x + something

creates a brand new list by joining x and something.
It's no different to the following simplified demonstration:
>>> a = [7]      # The object is [7], name a is connected to it.
>>> x = a        # Now name x is also connected.
>>> x += [2]     # Here we change the backing object (behind a AND x).
>>> a            # So that both names seem to change.
[7, 2]
>>> x
[7, 2]

>>> a = [7]      # The object is [7], name a is connected to it.
>>> x = a        # Now name x is also connected.
>>> x = x + [2]  # Here we create a NEW object from the old one, and connect x.
>>> a            # So a is unchanged.
[7]
>>> x            # But x IS changed.
[7, 2]

This was the hardest thing I had to get used to in Python, the fact that names and the objects that names refer to are quite disparate, and can often act in surprising ways. It's also one of its most beautiful features once you nut it out.
I eventually just started thinking that names were C pointers and all objects were on the heap (since that was where I have my expertise). There may be better ways to think of it, though I've never found any for me.
Comment: You are right, names and objects are different. Names are like *labels* put on an object; assigning a label to an object is done through `name = …` (this is called binding the object to the name). An single object can have many labels (like when doing `name2 = name`). A difficulty is that `name` represents a label, in `name = …`, but an *object* in `name2 = name` (or `name += [0]`).
Comment: So list are similar to array in C, we can use the slice to change the value. Ah, I find an other solution, for x in [a, b]: x[:] = x + [0], python is intersting.


Fingerstyle - Alternating Bass, Pinch or Bass Alone?

Question: In this arrangement it seems the creator, Mark Hanson, sometimes plays the alternating bass with the melody note (in a pinch) and sometimes, randomly it seems, he plays the bass note then the melody using eight notes as highlighted in red below.
My question is, does he choose the pinch versus bass then melody arbitrarily or is there another reason?
Answer: Traditionally, alternating bass is played in quarter notes, as in the example in your question. So, if the melody note happens to fall on the beat, it will be played simultaneously with the bass note, otherwise it will be played in between bass notes. It's as simple as that.
Comment: I would add that fingerpickers do alter the rhythm of the melody sometimes so they can keep a consistent right hand pattern, or at least to make it fit the general rhythmic lilt of the pattern. Check out [Chet Atkins' take on Autumn Leaves](https://www.youtube.com/watch?v=Ao1VOMrEuS4), for instance.