Does $F$ is an isomorphism $\implies F^{-1}$ is an isomorphism?

Question: Does $F$ is an isomorphism $\implies F^{-1}$ is an isomorphism?
Let $\mathfrak{D, E} $ be some algebraic structures of the same 'kind' (say, groups, graphs, fields, vector spaces, etc.), and $F:\mathfrak D \to \mathfrak E$ is an isomorphism, is there any way to prove that $F^{-1}:\mathfrak E \to \mathfrak D$ is an isomorphism?
By isomorphism I mean a bijection that preserves whatever structure $\mathfrak D$ and $\mathfrak E$ have, clearly $F^{-1}$ is a bijection, so the important part is if it is a structure preserving map.
Comment: [There are continuous bijections whose inverse is not continuous.](http://math.stackexchange.com/questions/378717/finding-counterexamples-bijective-continuous-functions-that-are-not-homeomorphi) So if topological spaces are within the realm of what you consider "algebraic structures", then that's a case where it's possible that $F^{-1}$ is not structure-preserving even if $F$ is. (That said, the answer to the question in your title is "yes, tautologically"; if $F$ is structure-preserving but $F^{-1}$ is not, we would define isomorphism in such a way as to exclude $F$.)
Comment: In the category-theoretic sense, which is the sense you are asking, an isomorphism is a morphism $f:C \to D$ with a two-sided inverse $g:D \to C$. In particular, $g$ is also an isomorphism. In short: yes.
Comment: @Micah There are examples when they have the same topology too. For example [here](http://math.stackexchange.com/questions/20913/are-continuous-self-bijections-of-connected-spaces-homeomorphisms?rq=1) and [here](http://math.stackexchange.com/questions/1190168/if-fx-to-x-is-a-continuous-bijection-and-every-point-has-finite-orbit-is-f). For groups you can have surjective homomorphism, $G \to G$, which are not isomorphism, and you can have groups with injective homomorphism, $G \to G$, which are not isomorphism too.
Answer: The short answer is, "Yes, $F^{-1}$ will also be an isomorphism." This will be true for any sensible definition of isomorphism. Of course, in order to have a general proof, we will need a more precise definition of "algebraic structures" and "structure-preserving map". There are multiple ways to try to view this.
One way is "categories". These are collections of objects together with some "morphisms" between them. For example, in the category of groups, the morphisms are the group homomorphisms. The morphisms in a category are required to satisfy a few sensible axioms. In particular, it is possible to compose morphisms, and "identity" morphisms are required to exist. An isomorphism is a morphism $F: A \longrightarrow B$ that possesses an inverse morphism $F^{-1} : B \longrightarrow A$. By definition, this means that $F^{-1} \circ F$ and $F \circ F^{-1}$ are identity morphisms. From this it follows easily that $F^{-1}$ is also an isomorphism (with inverse $F$). Note that an isomorphism  in category theory is not defined as a bijective morphism. Indeed, "bijective" is not even a meaningful concept in all categories, and even in those where it is, "bijective morphism" is not necessarily the right definition of isomorphism.
However, the category definition of isomorphism may seem rather distant from the notion of "bijection that preserves whatever structure". Another way, closer to this, is using "varieties" from universal algebra. These generalize the notion of a group and ring to define a collection of sets that are required to satisfy certain axioms (such as the group axioms) for all members of the set.  However, these aren't as general as we'd like. (For instance, this doesn't cover fields, because in a field $0^{-1}$ doesn't exist.) We can generalize by considering structures in first order logic. However, this still doesn't cover topological spaces, an important example.
I am now going to present informally a rather general notion of structure. (This is based on Bourbaki's idea of a structure, which has not caught on and is not worth studying in detail unless you're rather curious. Most of what Bourbaki tried to do with structures should be done with categories instead. Here I just present enough of the idea in order to describe the notion of isomorphism.) The idea here is that given a set $A$, a structure on $A$ is a subset, satisfying the right rules (say, the group axioms), of a suitable set defined in terms of $A$. For example, a group on $A$ may be defined in terms of a subset of $A \times A \times A$, consisting of elements of the form $(g, h, g \cdot h)$, where $g \cdot h$ is the product of $g$ and $h$ in the group. And a topological space on a set $A$ is defined in terms of a subset of $\mathcal{P}(A)$ (the power set of $A$) satisfying the axioms for the open sets of a topological space.
Now it is possible to define "isomorphism". Consider the case of groups. Let $(A, \cdot_1)$ be a group. Then the set associated to $A$ is $S = \{(g, h, g \cdot_1 h) \mid g, h \in A\} \subseteq A \times A \times A$. And for another group $(B, \cdot_2)$, we have the set $T = \{(g, h, g \cdot_2 h) \mid g, h \in B\} \subseteq B \times B \times B$.  Given a function $F : A \longrightarrow B$, we obtain a function $F_0$ from $A \times A \times A$ to $B \times B \times B$, which maps $(g, h, k)$ to $(F(g), F(h), F(k))$. Then $F$ defined to be an isomorphism if it is a bijection and

$x \in S$ if and only if $F_0(x) \in T\quad\quad\qquad(*)$

holds. This latter condition is equivalent to asserting "$g \cdot_1 h = k$ if and only if $F(g) \cdot_2 F(h) = F(k)$".
This definition works for fairly general kinds of structures. The main thing is how to define $F_0$ from $F$. For example, if $F: A \longrightarrow B$ is a function between topological spaces, then $F_0: \mathcal{P}(A) \longrightarrow \mathcal{P}(B)$ is defined as $F_0(X) = \{F(x)\mid x \in X\}$ for $X \in \mathcal{P}(A)$ (the image of the set $X$ under $F$). If we define $S$ as the set of open sets in $A$ and $T$ as the set of open sets in $B$, an isomorphism is then defined as a bijection that satisfies the same condition $(*)$ above as for groups, and this definition is equivalent to "$F$ is a bijection, and $X$ is an open set in $A$ if and only if $F_0(X)$ is an open set in $B$".
In the general setup, there will always be a set $S$ that defines the structure of $A$ and a set $T$ that defines the structure of $B$. Then, an isomorphism $F$ will have an inverse that is also an isomorphism. This is because, by applying the function $F_0^{-1}$ to both sides of $(*)$, we see that $(*)$ implies

$F_0^{-1}(x) \in S$ if and only if $x \in T$

which is the condition for $F^{-1}$ to be an isomorphism.
Answer: yes. as you have stated, the map is bijective. The only thing left to prove is that it is a homomorphism, which shouldn't be to hard.
this is a duplicate
$F:G\to B$ is an isomorphism between groups implies $F^{-1}$ is an isomorphism
Comment: I disagree with the possible duplicate, if my definition for isomorphism is a structure preserving map that is bijective, the answers in that thread don't suffice.
Comment: "...This means that...F−1(a⋅b)=...=F−1(a)⋅F−1(b)..."
Answer: An isomorphism is just a relabeling with distinct labels, such that all the axioms hold after relabeling. So obviously the inverse is an isomorphism too, because the labeling can be undone.
For example, a group $(G,\circ,1_G)$ obeys:

$\forall x \in G\ \exists y \in G\ ( x \circ y = 1_G )$.

An isomorphism $f$ is essentially a relabeling of everything in $(G,\circ,1_G)$, meaning every member $x$ in $G$ becomes $f(x)$, and $\circ$ becomes $f(\circ)$, and $1_G$ becomes $f(1_G)$. So the axiom when relabeled becomes:

$\forall x \in f(G)\ \exists y \in f(G)\ ( x \operatorname{f(\circ)} y = f(1_G) )$.

If $f$ is an isomorphism from $(G,\circ,1_G)$ to $(H,\bullet,1_H)$, then we are effectively saying $f(G) = H$ and $f(\circ) = \bullet$ and $f(1_G) = 1_H$, so the axiom reduces to:

$\forall x \in H\ \exists y \in H\ ( x \bullet y = 1_H )$.

Similarly you can easily see that undoing the labeling gives the inverse isomorphism.
Answer: Suppose $f:D\to E$ is an isomorphism where $f(d_1)=e_1$ and $f(d_2)=e_2$.
Then we know $f(d_1d_2)=f(d_1)f(d_2)=e_1e_2$
Applying the inverse to both sides (which as you mentioned, must exist since $f$ is a bijection), we have
$(f^{-1}\circ f)(d_1d_2)=f^{-1}(e_1e_2)$
$d_1d_2=f^{-1}(e_1e_2)$
That is $f^{-1}(e_1e_2)=f^{-1}(e_1)f^{-1}(e_2)$ so $f^{-1}$ also preserves multiplication.
Answer: Isomorphic means two algebraic structures that are merely same and they have same property but different in naming or in some other perspective.
To prove two structures are isomorphic, we define a function in such a way to say that both structures are isomorphic, if they are isomorphic, naturally the domain and the codomain can be interchanged, thereby arriving your result.
Since $F$ is isomorphism, it is one-one and onto, so naturally inverse $F^{-1}$ exists, since $F$ is one-one and onto, $F^{-1}$ is also one-one and onto. It remains to prove homomorphism part alone. $F^{-1}(a+b) = F^{-1}(a)+F^{-1}(b).$(For groups with addition operation)


What's the difference between harmony and polyphony?

Question: What's the difference between harmony and polyphony? Is it a matter of perspective or is there a qualitative difference?
Answer: Harmony refers to the "vertical" relationship between simultaneous pitches in a musical texture (usually, but not always, chords - see below for the exception). However, it also refers to the "horizontal" relationships between successive vertical relationships of pitches; it's probably easiest to think of these as chord progressions. The exception, mentioned above, is that even a single melodic line will create a series of implied harmonies: sometimes this is very obvious, for instance a series of arpeggios; sometimes it is ambiguous, as the single line could suggest a number of harmonies. Also, a single line or two-part counterpoint can easily imply a series of chords containing three and four (or more!) note chords. (@Pat Muchmore mentions this in his comments.)
Harmony can be thought of as the framework of pitch relationships between any number of simultaneous elements in a musical texture, be they: melody, bass-line, block chords, multiple melodic lines, counter-melodies etc.
It is important not to confuse the concepts of harmony and accompaniment; harmony is not simply "padding" between the main melody (if there is one) and the bass part. However, the term harmony is often used informally to mean just this: parts of the musical texture that accompany a main melody part. (When writing arrangements I'll often mark parts as Melody, Harmony and Bass parts.) But, strictly speaking, all of these parts, accompanimental or not, define the overall harmony.
Polyphony is a related, but quite different concept. Polyphony refers to a texture containing a number of independent melodic lines (or voices, if you like). A polyphonic texture does not rely upon a series of "block-chords" (a homophonic texture) to reveal the harmonic progression of the music, but it still has a harmonic framework. Although independent to a certain degree (for instance, in terms of rhythm, contour, motif, intervallic character) these lines are still tied together by the overall harmonic framework. (A polyphonic texture still "has harmony".)
Although a polyphonic texture is to a large extent conceived and perceived as layers of simultaneous "horizontal" melodic lines, good contrapuntal writing must take account of the vertical relationships between parts, in other words, they must all fit within the ongoing harmonic framework of the piece.
Arguably, it is this very tension between horizontal melodic impetus and vertical harmonic relationships, that makes great contrapuntal (or polyphonic, if you like) music so satisfying to compose, perform and listen to.
As a closing point (and maybe one for others to comment or respond to): arguably the harmonic relationship between parts breaks down in certain types of polyphonic modern music, where intervallic/motivic relationships in individual melodic parts can override the relationships between parts. (Even so, it is usually the case that there is a significant amount of pitch organisation between simultaneous contrapuntal parts, even if they do not fit within a "traditional" harmonic framework.)
Comment: This answer is very good, but I think it could be improved by clarifying that 'harmony' and 'polyphony' are terms in different categories and not easily contrasted (especially since, as you correctly point out, there is harmony in polyphonic music).
Answer: Harmony supports the melody. Polyphony is when there is more than one independent melody.
The basic idea is that in polyphony is that each melody can stand on its own independent of the other melody. Common examples of this are rounds, fuges, and counterpoint.
In the case of harmony, everything supports the melody. Their may be secondary melodies or the melody might switch between instruments, but there is not two independent melodies at the same time.
Comment: This is more a description of the difference between polyphony and homophony, which does sound more like what the OP was asking about. Technically, "harmony" is a more general term useful for discussions of homophony, polyphony and heterophony. It's even possible to talk about harmonic implications in monophony.
Comment: @PatMuchmore, I've "borrowed" your ideas and expanded them in my answer - hope you don't mind...


Spring Boot @Autowired não funciona com o repository

Question: Tenho o seguinte erro:
Description:

Field categoriaRepository in
com.algaworks.algamoneyapi.resource.CategoriaResource
required a bean named 'entityManagerFactory' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

Código da classe principal do projeto:
package com.algaworks.algamoneyapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableJpaRepositories
public class AlgamoneyApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(AlgamoneyApiApplication.class, args);
    }

}

Código da Entidade:
package com.algaworks.algamoneyapi.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;

@Entity
@Table(name = "categoria")
public class Categoria {

    @Id
    @GeneratedValue
    private Long codigo;
    private String nome;

    public Long getCodigo() {
        return codigo;
    }

    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Categoria categoria = (Categoria) o;
        return Objects.equals(codigo, categoria.codigo);
    }

    @Override
    public int hashCode() {
        return Objects.hash(codigo);
    }
}

Código do Repository:
package com.algaworks.algamoneyapi.repository;

import com.algaworks.algamoneyapi.model.Categoria;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CategoriaRepository extends JpaRepository<Categoria, Long> {
}

Código do Controller:
package com.algaworks.algamoneyapi.resource;

import com.algaworks.algamoneyapi.model.Categoria;
import com.algaworks.algamoneyapi.repository.CategoriaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/categorias")
public class CategoriaResource {

    @Autowired
    private CategoriaRepository categoriaRepository;

    @GetMapping
    public List<Categoria> listar() {
        return categoriaRepository.findAll();
    }
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath />
    </parent>

    <groupId>com.algaworks</groupId>
    <artifactId>algamoney-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>algamoney-api</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Estrutura do projeto:

Já tentei:

@EnableJpaRepositories(basePackages = "com.algaworks.algamoney.repository")
@ComponentScan(basePackages = "com.algaworks")
@SpringBootApplication(scanBasePackages = {"com.algaworks"})

mas nada funciona.
Comment: Vamos ver se eu entendi corretamente:
Trocar na CategoriaResource a anotação @Autowired por @Repository? Porém dá erro de sintaxe: ```@Repository' not applicable to field```.

Acredito sim ser correto sobre instanciar a implementação de um repository quem diz para que o spring faça isso é a anotação ```@Autowired```.
Comment: Olá, não é certeza mas experimente trocar a anotação `@Autowired` por `@Repository` e remover esta última da declaração da interface `CategoriaRepository`. Acho que a anotação `@Repository` deve ser aplicada a variáveis não-locais, já subentende a `@Autowired`, e produz (instancia) uma implementação default de repositório para qualquer variável do tipo `JpaRepository` ou do de alguma sub-interface da mesma. Será que chutei certo?
Comment: Você está certa, eu me enganei. Não entendo muito de Spring. `@Repository` subentende `@Component` e não `@Autowired`. Entendi o que quis dizer com erro de sintaxe, mas creio que o erro é semântico.
Comment: Sim, semântico! kk
Answer: Aparentemente o repositório não está sendo carregado no contexto do Spring. Para fazer isso, é utilizada a anotação @EnableJpaRepositories. Existem algumas formas de se fazer isso, acredito que no seu caso as mais simples são:

Adicionar @EnableJpaRepositories em AlgamoneyApiApplication. Por convenção, o SpringBoot vai escanear todas as classes por @Repository ao iniciar sua aplicação, e vai incluí-la no contexto do Spring;

A sua tentativa: de adicionar @EnableJpaRepositories(basePackages = "com.algaworks.algamoneyapi.repository") em AlgamoneyApiApplication. Porém, repare no pacote: o seu repositório está em com.algaworks.algamoneyapi.repository e vc tentou com com.algaworks.algamoney.repository. Provavelmente por isso que não funcionou.
Comment: Também me pareceu estranho não funcionar sem necessidade de modificações adicionais, porque, pelo que sei, para fim de mapeamento de repositórios é escaneada toda a árvore de subdiretórios/subpackages a partir do que possui a classe anotada com `@SpringBootApplication`.
Comment: @AlineAvila Se resolveu o primeiro problema, acho que é conveniente aceitar a resposta dada (e, quando tiver mais pontos, positivar). Aqui é um problema por vez (isto é, por pergunta). Vi que não fez o [tour], recomendo fazer.
Comment: Continurou dando erro, porém diferente agora.

```
Description:

Field categoriaRepository in com.algaworks.algamoneyapi.resource.CategoriaResource required a bean named 'entityManagerFactory' that could not be found.

The injection point has the following annotations:
 - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

Disconnected from the target VM, address: '127.0.0.1:53194', transport: 'socket'

Process finished with exit code 0
```
Comment: @Piovezan resposta aceita.
Comment: @AlineAvila Agradeço se você puder acrescentar seu arquivo `pom.xml` à pergunta para torná-la reproduzível, foi falha minha não pedir. Aí para o seu próximo problema eu penso que para economizar copia-e-cola você pode linkar esta pergunta na nova que eventualmente for fazer.
Comment: @Piovezan pelo que eu entendi, não foi utilizado o `@EnableJpaRepositories` sem o `basePackages`, o erro foi que foi forçado um package errado
Answer: Quando o model está na dependencia, é necessario colocar
@EnableJpaRepositories(basePackages = { "teupacote })
@EntityScan(basePackages = { "teupacote" })
junto como o @SpringBootApplication


Forcing to append text to the end of a file name with .htaccess

Question: Currently i have this directory:

example.com/curriculums/34-william.pdf
example.com/curriculums/168-romina.pdf

34-william.pdf and 168.romina.pdf are actual files, and they do exist, but they should only be accesible if accessed using these urls:

example.com/curriculums/34-william-cv.pdf
example.com/curriculums/168-romina-cv.pdf

So that:

If a visitor opens example.com/curriculums/34-william.pdf it should return a 404 response code
If a visitor opens example.com/curriculums/34-william-cv.pdf the server should return the contents of example.com/curriculums/34-william.pdf

Any ideas? Thanks!
Answer: Assuming you don't have any .htacecss inside curriculums directory, you may use these rules inside your site root .htaccess:
RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^curriculums/[\w-]+(?<!-cv)\.\w+$ $1$2 [L,NC,R=404]

RewriteRule ^(curriculums/[\w-]+)-cv(\.\w+)$ $1$2 [L,NC]

Comment: Worked fine. Thanks!


android how to finish an activity from other activity

Question: In my app i have 3 activities.
From 1st activity it goes to 2nd and from 2nd it goes to 3rd.  From 3rd it is coming to 1st again. and if I press back key from the 1st then it should go to home screen (App will stop).
If I press back key of 1st its goes to 2nd activity again and if I press 2nd's back key, then it goes to the 1st . Then if I press back key of 1st then app stops.
What I want , when I am in 3rd activity and press the back button then it should go to 1st and simultaneously finish the 2nd activity.
How can I do that?
Comment: Make sure you're calling super.finish() in your finish() functions.
Comment: finish()? how to write finish(). If i ll write then same activity ll finish na?
Comment: If you don't already have finish() functions, then don't worry; my suggestion won't solve your problem.
Comment: Here is a great answer: http://stackoverflow.com/a/10379507/478162
Answer: just finish the second activity when you open third activity
suppose in second activity on some button click you are opening third activity using start activity;
startActivity(intent);
finish();//this will finish second activity and open third activity so when you press back from third activity it will open first activity.

if you want depended on some condition then on activity
setResult(123);

something code like this
now when override onActivityResult in second activity
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==123){
            //finish
        }
    }

also make sure one thing you need to use startActivityForResult(intent, requestCode); for result in second activity to start third activity.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity2 extends Activity{

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(new Intent(Activity2.this,Activity3.class)), 12);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode==123 && requestCode==12){
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity3 extends Activity{

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                setResult(123);
            }
        });
    }
}

Comment: I dont want that. I want to finish 2nd activity for particular condition happen within 3rd activity.
Comment: Within which activity i should write this?
Comment: Bcz i want to start 1st activity and at the same time i want to finish 2nd activity  from the 3rd.
Comment: check code it should be like this in 3 rd activity you can set different result code for different conditions.
Comment: I did like this but no effect.
Answer: When you start your third activity you should call in your 2nd acitivity like this:
startActivityForResult(intent, 0)
When you finish your 3rd activity, you should include:
setResult(RESULT_OK);
finish();

It sends a signal from the 3rd activity to the 2nd.
In the 2nd put:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     finish();
}

It receives this signal and finishes the 2nd activity.
Comment: how to set result? I am not getting
Answer: You should launch the 1st activity in 3rd activity with the cleartop flag when you need to finish the 2nd activity.
class ThirdActivity extends Activity {
    ....
    if (somecondition) {
         /* directly go to FirstActivity, finish all intermediate ones.*/
        Intent intent = new Intent(this, FirstActivity.Class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    } else {
        finish(); // to simply return to 2nd activity.
    }
    .....
    ....
 }

Comment: but is this gonna finish thee 2nd activity ?
Comment: Why do you need to keep the 2nd activity alive until 3rd activity is finished?
Comment: Do you call finish just after launching 3rd activity? Where are you calling `finish`?I think u are do it in 3rd activity now.thats why 3rd activity is exiting.
Comment: actualy i am working with server. so for some particular condition only the 2nd activity ll finish. Not for every time.
Comment: then you should use @beni ansnwer.
Comment: when i am starting 1st activity from 3rd at that time only 2nd activity ll finish.
Comment: Use `intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)` while launching the 1st activity from 3rd.  http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP
Comment: Didi it work? I suggested a cleaner method.. check out. Definite improvement.
Answer: Alternatively, you could set an intent flag called FLAG_ACTIVITY_NO_HISTORY on the 2nd Activity.  This way it is not kept in the history stack so when you navigate back from the 3rd activity it will go straight to the 1st.
E.g.
Intent intent = new Intent(this, SecondActivity.Class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

This means that when you launch an activity from the SecondActivity the SecondActivity will be finished automatically.
Comment: but i donot want that every time 2nd activity ll finish . I want for some particular condition
Comment: that means when control comes from 3rd activity to 1st at time it should finish the 2nd.
Answer: Using this way: In your first activity, declare one Activity object like this,
public static Activity fa;
onCreate()
{
    fa = this;
}

now use that object in another Activity to finish first-activity like this,
onCreate()
{
    FirstActivity.fa.finish();
}

More information : Finish an activity from another activity


Limit Equality Proof

Question: I need to prove that $\lim_{x \to 0}f(x^3)=\lim_{x \to 0}f(x)$. Then give an example of a function f for which $\lim_{x \to 0}f(x^2)$ exists but $\lim_{x \to 0}f(x)$ does not exist
Thank you in advance
Comment: The limit of $f(x^3)$ and the limit of $f(x)$ both exist therefore the limit of the difference of the two functions exist as well
Answer: Hint: For the first part, do you know that $x\mapsto x^3$ is invertible on $\mathbb{R}$?
For the second part consider the function $$f(x)=\operatorname{sign}(x)=\left\{ \begin{array}{cc} 1 & x>0\\ 0 & x=0\\ -1 & x<1\end{array}\right.$$
Answer: Hint: Can you show: If $g$ is continuous around $a$ and $g(a)=b$ and $\lim_{x\to b} f(x)$ exists, then $\lim_{x\to a} f(g(x))=\lim_{x\to b} f(x)$.
Comment: Ok I proofed that. Could you help me now with the second part of the question

Limit Equality Proof


Peavey SP-2A Speaker Repair

Question: I'm taking a shot in the dark here but I have these old Peavey Sp-2A speakers that I'm looking at fixing. They were a gift to me a long time ago and since then the main loudspeaker, or sub-woofer, has gone out. Or at least I think. I'm getting sound out of the tweeter, which is the top part, but I'm not getting any sound out of the lower speaker. I've seen what looks to be replacement speakers on Amazon. I have two of these bad boys and I love their look so I want to keep them. These are used for vocals, guitars, and keys so I want to make sure they sound good. The cabinets are in good shape but since the paint is chipping I am considering sanding them down and covering them in black carpet. I'm just curious to see if I'm approaching this repair the right way or if there are better speaker replacement options that would not go over $400 for the pair to repair.
Answer: The replacements would appear to be black widows, 15", 8 ohms, with more power capacity than the originals, which should also be black widows. Good speakers ! First check the drivers out of circuit, using a small battery. 9v will do. When it's connected to the speaker, the cone should move out or in. If not, it needs changing. If it moves, it should either be the crossover circuit or the wiring 'twixt it, the input on the cab., and the speaker.
Answer: Take the front grille off and do a visual.  Ancient speakers often have the rubber "surround" (which holds the cone to the internal faceplate) crumble into dust.  Luckily, it's easy to get replacements in kits which include detailed instructions, matching glue, etc.  I fixed my Advent speakers this way.
Answer: Chances are that if the speakers are blown, there maybe damage in the filtering coils in the crossovers, examine to see if there are melted or deformed spools on these coils. You can order needed parts from peavey or rebuild the coils yourself by counting the coils as you unwrap them and then rewinding the coils using the same type and gauge of wire. I've always been amazed at what overpowering can do to a speaker system.
Answer: SP2a peavey speakers came with 18" "black widow" speakers.Replacement cones (spiders) come from Peavey,the only way to go
Imagine what kind of idiot could blow a 300 watt speaker.
Answer: Chances are that if the speakers are blown, there maybe damage in the filtering coils in the crossovers, examine to see if there are melted or deformed spools on these coils. You can order needed parts from peavey or rebuild the coils yourself by counting the coils as you unwrap them and then rewinding the coils using the same type and gauge of wire. I've always been amazed at what overpowering can do to a speaker system. Also, it appears that the phone jacks on the crossover panel are dirty and corroded. The crossover is wired so that the signal passes through the Bi-Amp phone jacks when they have nothing plugged into them, but dirt and corrosion can block the signal making the speaker silent. If you check this, you might find no need to replace the speaker. Just saying...

Peavey SP-2A Speaker Repair


In my exame of discrete math there was a question "Let $X$ be a set (finite or not finite). Prove that $|X| < |P(X)|$, $P(X)$ is the set of parts of X

Question: I used induction to make that proof
$|X| = n$, $|P(X)| = 2^n$
For $n = 0$, $1 > 0$, true.
Induction hypothesis: $2^n > n$
Induction thesis: $2^{n+1} > n + 1$. We have $2^{n+1} = 2 * 2^n > 2n = n + n > n + 1$ for $n \ge 1$.
At the beginning, I prove that it works for $n = 0$ and at the end for $n \ge 1$ if I put it together I get
that it works for $n \ge 0$.
I got it wrong at the exam, then someone told me that I was supposed to use the Cantor theorem.
Comment: Your argument only works for finite sets but the question concerns both finite and infinite sets.  The problem statement is exactly [Cantor's Theorem](https://en.wikipedia.org/wiki/Cantor%27s_theorem).
Comment: Do you know Cantor's proof?
Answer: Clearly there is an one-to-one map from $X$ to $P(X)$ so $|X| \leq |P(X)|$. Now we will prove there is no surjective map from $X$ to $P(X)$ for any $X$ which will prove that this inequality is strict.
Suppose, there is a surjective map $f: X \rightarrow P(X)$. Consider the set $Y=\{x \in X : x \notin f(x) \}$. Let us consider $f^{-1}(Y)$, let us say $z\in f^{-1}(Y)$. So $f(z)=Y$, now let us see if $z \in Y$, if so then $z \notin f(z) =Y$, if $z \notin Y$ then $z \in f(z)=Y$ in both these cases we find contradictions. So our assumption that there is a surjective map from $X$ to $P(X)$ is wrong.


Time Complexity Analysis in the following relation

Question: Can the recurrence :
T(N)= SUM T(N-i)  //i=1 to N

be solved as:
    T(N)<= N*T(N-1)
which finally comes O(N^(N-1)) ?

By solving iteratively it comes:
    T(N)=N*(N-1)T(N-2).... , T(N)=N....(N-k+1)T(1), k=N-1.
so finally O(N!)
Answer: Note that O gives you an upper bound on the execution time, which means that if a certain algorithm, for example, is linear, then it is O(n), but it is also O(n^2) and O(n!) and it is also O of any superlinear function.
Your inference is correct, however on both steps you overestimated your function complexity. The recurrent relation T(N) = sum(T(N-i)) is  O(2^N) (and I suspect it is also o(2^N)). It is easy to show, since 2^n = sum(2^i) + 1 for 1 <= i <= n - 1.
On your first step you used a higher bound, which is perfectly fine for the O. However, even with your bound of T(N) <= N*T(N-1) the complexity you ended up with is too high. O(N!), which is less than what you estimated, also satisfies T(N) <= N*T(N-1).
Comment: Yup , I made a mistake while mentally deducing it ! It should be like T(N)=N*(N-1)*T(N-2).... , T(N)=N*....(N-k+1)T(1), k=N-1. so finally O(N!)
Comment: But also, as I pointed out, it can be improved to `2^n`, which is the lowest complexity.


Django Drop-down fields for foreign key to another database field

Question: I am a Django beginner and I am having trouble using bootstrap drop-downs for foreign key use.
I have an input form for adding Providers (supplier, manufacturer, or both) for my purchasing website that has the following data structure:
class Provider(models.Model):
    provider_id = models.AutoField(primary_key=True)
    provider_name = models.CharField(max_length=255, unique=True)
    provider_address = models.CharField(max_length=255, null=True, blank=True)
    provider_email = models.EmailField(null=True, blank=True)
    provider_contact_01 = models.CharField(max_length=20, null=True, blank=True)
    provider_contact_02 = models.CharField(max_length=20, null=True, blank=True)
    provider_type = models.ForeignKey(ProviderType, on_delete=models.CASCADE)

in which provider_type is a foreign key for table ProviderType that has the following data structure:
class ProviderType(models.Model):
    providertype_id = models.AutoField(primary_key=True)
    providertype_desc = models.CharField(max_length=50, null=True, blank=True)

    def __str__(self):
        return self.providertype_desc

Dataset for ProviderType:
| providertype_id |    providertype_desc    |
---------------------------------------------
|       1         |         Supplier        |
|       2         |       Manufacturer      |
|       3         | Supplier & Manufacturer |

The problem is that I have used providertype_desc as the text in the drop down field, because it is more user friendly and has context, rather than providertype_Id, Code segment in html:

  Type of Provider
  <select class="custom-select" id="provider_type" name="provider_type" aria-label="Example select with button addon">
    <option selected>Choose...</option>
    {% for prov_types in provider_types %}
      <option>{{prov_types.providertype_desc}}</option>
    {% endfor %}
  </select>

But the POST sequence fails because the providertype_id needs to be returned instead of providertype_desc.
Looking for suggestions, please try to keep simple as I am still a beginner in Django.
Thank you.
Answer: This is really an HTML issue, you want to add a value to your options:
<option value="{{prov_types.pk}}>{{prov_types.providertype_desc}}</option>


Logistic Regression - Binning - Interpretting p values

Question: My name is Abhi and I am trying to teach myself regression by solving some practice problems available on the internet. I am using RStudio as my development environment.
Problem Statement

Given the age, sex, class(first,second,third), ticket_id for each passenger can you predict if he survived or died when the titanic sank.
I did some initial data analysis and it seems passenger class and ticket id are fairly predictive. Here are the results from my first model
<code>Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.4431  -0.8649  -0.6772   0.9332   1.7806

Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   1.1713     0.2171   5.396 6.80e-08 ***
Pclass       -0.5654     0.1110  -5.094 3.50e-07 ***
Ticket2      -0.4361     0.2421  -1.801   0.0716 .
Ticket3      -0.8311     0.2033  -4.089 4.33e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1186.7  on 890  degrees of freedom
Residual deviance: 1067.8  on 887  degrees of freedom
AIC: 1075.8

Number of Fisher Scoring iterations: 4
</code>
My question is why do I get poor p values for Ticket2? Does this mean Ticket1 and Ticket2 should be merged? Not enough samples for Ticket2?
Any help would be much appreciated.
Comment: In addition to my answer, I have a suggestion for learning. While practice problems are absolutely essential, you should also study some of the basic theory behind regression and statistics in general from a cohesive source such as a textbook. Being able to carry out a regression analysis in R won't mean much if you can't identify the appropriate times to apply each method and interpret the output.
Answer: An insignificant p-value indicates that the estimated coefficient (first column) is not significantly different from zero. In interpretation, there's insufficient evidence to conclude that having ticket level 2 changes your odds of survival versus having ticket level 1.
This is not necessarily a problem with the analysis at all, it's just telling you what the data show. If for some reason you think people with ticket level 2 should have different survival odds from those with ticket level 1, a larger sample size for Ticket2 might detect a difference, but of course that difference might be close to zero, anyway.


Continuous variable vs. Nominal variables

Question: I have a file with a continuous variable Y, and a set of 20 binary variables (yes/no). I wish to do the following two tasks:

To find which of the 20 variables are related to the variable Y, i.e., which values of "yes" are related to high scores of Y.
To find if there are "subgroups" among the 20 variables (i.e., if for example variables 1, 3 and 7 are related).

Which method should I use, and if you can, how do I perform this in either R or SPSS ? Thank you in advance !
Comment: Was my answer below useful? If so, would you mind accepting/upvoting it? If not, let me know if you need any clarification.
Answer:
Convert the binary fields such that YES is encoded as 1 and NO as 0. In other words, convert them from character to numeric form.
In order to identify variables that are correlate with Y, perform a correlation test between each variable and Y. Variables that have a positive correlation coefficient with a significant p-value, are the ones that you're looking for. (i.e., These are the variables for which "yes" values are related to high scores of Y.) Here's how you can do this in SPSS: http://www.spss-tutorials.com/spss-correlation-test/ (You can skip to step 2: Assumptions Correlation Test)
To identify groups of variables based on their correlation with each other, you can perform cluster analysis on the variables themselves.
Refer to 'Clustering Variables' section on page #371 in the following document: http://www.norusis.com/pdf/SPC_v13.pdf


Extraction of substrings from a string on the basis of multiple conditions in R

Question: I have a string str from which multiple substrings are to be extracted.
str <- "Nucleotide transport and metabolism,Secondary metabolites biosynthesis, transport, and catabolism / Chromatin structure and dynamics,Coenzyme metabolism,"

The conditions for extraction are:

Extract everything till the first occurrence of a , only if the next character is a capital letter
If the character next to a , is not a capital letter, then proceed till

the next occurrence of , which is followed by a capital letter OR
the occurrence of  /  OR
the end of string

The output should look like this
>output
[1] "Nucleotide transport and metabolism"                           "Secondary metabolites biosynthesis, transport, and catabolism"
[3] "Chromatin structure and dynamics"                              "Coenzyme metabolism"

Answer: You can use str_split from the stringr package.
library(stringr)

str_split(str, ",(?=[:upper:])|\\s\\/\\s") %>% unlist() %>% gsub(",$", "", .)
[1] "Nucleotide transport and metabolism"
[2] "Secondary metabolites biosynthesis, transport, and catabolism"
[3] "Chromatin structure and dynamics"
[4] "Coenzyme metabolism,"

Comment: We can use `gsub()` to get rid of the comma
Comment: Thanks. The last substring however has a comma at the end. How to get rid of it?


Spring Cloud DataFlow run Composed Task multiple times

Question: Is there any way to tell Composed task runner (CTR) to run composed task multiple times?
For now, in SCDF 1.2.3.RELEASE and CTR 1.0.0.RELEASE, if particular task in composed task has been completed, CTR doesn't execute it again.
Comment: Do you mean launching the composed task again? or, restarting the stopped/failed composed task. Did you see this doc: http://docs.spring.io/spring-cloud-dataflow/docs/1.2.0.BUILD-SNAPSHOT/reference/htmlsingle/#spring-cloud-dataflow-composed-tasks

  [1]:
Comment: I mean launching the same composed task again.
Answer: A composed-task is a graph (represented in a DSL) defining a series of steps where each step can be a task or a batch-job. Once the composed-task is launched, it will execute all the steps and its transitions as defined by the DSL.
Unless you schedule the composed-task to launch on the desired frequency (e.g., "every 1hr"; "every day at 11p" etc.), it won't automatically re-execute it. Please consider using a scheduler for this purpose.
Comment: Thanks for your answer.
What I need is when some event raises - my code should launch the same composed task again.
Probably, I would launch it with different args, but for now it seems `--composed-task-arguments` doesn't work, so I have to use DB to share data between tasks in composed task.


How to include vendor library in load path?

Question: I have a vendor library that has its own directories and many files (js and css a.o.). I have placed this as a folder in my_app/vendor/assets/external_library/. How can I refer to files from this directory, for example in my views?
For example, there are the following two files:

my_app/vendor/assets/external_library/editor.js
my_app/vendor/assets/external_library/contents.css

To use these I have added:

In application.js: //= require editor
In application.css.scss: @import "contents";
In my view:

It does load the view page in development. But when I go to the page's source code and click on the link to the js file, it is unable to find that file. Am I doing something wrong?
Answer: Add this to your application.rb file:
config.assets.paths << Rails.root.join('vendor', 'assets')

and then require these in your application.js:
//= require external_library/editor.js

and application.css.scss:
@import "external_library/contents";

In your view you should only need to have the following:
= stylesheet_link_tag    "application", media: "all"
= javascript_include_tag "application"

Comment: Thanks! What if I only want the files included in 1 specific view (since it's only relevant for one specific view, so why load it for all views...)? I also found this post: http://stackoverflow.com/a/25985318. One of the answers also suggests editing `config.assets.paths` but a different answer got a lot more votes. Which would be the better solution?
Comment: No problem. Usually I wouldn't worry about having a different CSS file for each view. Use good class names (you can use the `flutie` gem to automatically give each page a different class) and Rails will just generate one large application.css file for you. Because of the way HTTP works this large css file can be downloaded once and then cached and reused on every page so it actually works out quicker. See this SO answer: http://stackoverflow.com/questions/2336302/single-huge-css-file-vs-multiple-smaller-specific-css-files
Comment: Thanks again Lewis. I was particularly referring to the js file. This file is only needed in one specific view. I was also wondering about the line that adds to assets.paths. Is this really necessary? Particularly, since the answer in the post I referred to doesn't seem to need to make this change to the assets path.\
Comment: If you really want to I suppose you could bypass the asset pipeline and just put the JS file in your `public` directory but I really wouldn't recommend it. and then use `` in your view.


slidespercolumns doesn't work in swiper slider

Question: I try to show columns base slider using swiper ver 6.5.8.
HTML:

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

Slide 10

JS:
var swiper = new Swiper('.swiper-container', {
  slidesPerView: 3,
  slidesPerColumn: 2,
  slidesPerGroup: 6,
  spaceBetween: 30,
  pagination: {
    el: '.swiper-pagination',
    clickable: true,
  },
});

But in action slidesPerColumn and slidesPerGroup doesn't work. howdo can I fix this problem?
In need like this:

DEMO HERE
Answer: You have working exemple here, take care how you customise it

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Swiper demo</title>
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"
    />

    <link
      rel="stylesheet"
      href="https://unpkg.com/swiper/swiper-bundle.min.css"
    />

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9


R Shiny selectInput selector doesn's change the map output when the input chnages

Question: When I change the input in the selectInput selector to show various groupings on the map, the full dataset shows up and doesn't change when the input changes.
ui <- dashboardPage(
  dashboardHeader(title = "Businesses in South Bend"),
  dashboardSidebar(),
  dashboardBody(
  fluidPage(
    titlePanel("Business by Type"),
    sidebarLayout(
        sidebarPanel(
            selectInput(inputId = 'Classifi_1',
                        label = 'Choose Business Type',
                        choices = unique(df_tidy$Classifi_1),
                        selected = 'TAXI VEHICLE')
        ),

        mainPanel(
          tabsetPanel(
            tabPanel(title = 'Map',
                     leafletOutput(outputId = 'mymap'))
          )
        )
    )
)))

server <- function(input, output) {

    output$mymap <- renderLeaflet({
      leaflet()%>%
        addTiles()%>%
        addMarkers(data = df_tidy, popup = df_tidy$Business_N)

    })
}

I tried adding a selected part of the selectInput and it still showed all the data points and still nothing changed when input changed.
Answer: I don't see that you've used the inputID of "Classifi_1" to filter your data on server side. You will want to create a reactive for your filtered data set. Try something like this:
df_tidy_r <- reactive({df_tidy %>% filter(Classifi_1 == input$Classifi_1) })

And then in output$mymap be sure to use data = df_tidy_r()
output$mymap <- renderLeaflet({
      leaflet()%>%
        addTiles()%>%
        addMarkers(data = df_tidy_r(), popup = df_tidy_r()$Business_N)

And use ObserveEvent to trigger refreshing output$mymap when you change input$Classifi_1.
ObserveEvent(input$Classifi_1,{
output$mymap <- renderLeaflet({
      leaflet()%>%
        addTiles()%>%
        addMarkers(data = df_tidy_r(), popup = df_tidy_r()$Business_N)
})


How to fail ASP.NET Web API deserialization when types do not match

Question: I am having a problem with silently failing deserialization in ASP.NET Web API (version 5.1.2). I would like the deserialization to raise an error instead but I am unable to find a configuration for it.
My specific (simplified) case is this. A client application (AngularJS) sends a HTTP POST request to the ASP.NET Web API backend. As a payload there are a bunch of strings:
["ABC100", "ABC200", "ABC300"]

However, the server is expecting a list of integers:
List<int> Ids { get; set; }

What ends up happening is that the deserialization fails, the Ids list will be empty and there are no errors.
Ids: []

Of course the mismatch needs to be fixed as well, but it seems obvious to me that the POST request should fail in this case. How can I make it the default?
Comment: In your API method, you can do any kinds of checks you want on the data (although this is happening after the deserialization) and manually return an HTTP 500: http://www.asp.net/web-api/overview/error-handling/exception-handling
Comment: JavaScript will always return an `array`, it doesn't understand `List`. List is a `C#` thing. And you are expecting `int`, whereas the values send by client are not.
Comment: @modal_dialog of course I can make checks against the Ids list, but it is quite valid that it is empty. Just not in the case when the client sends data but the types do not match.
Comment: as a work around, create a custom media type formatter, handle the serialization/deserialization manually.
Answer: One solution to this problem seems to be checking the ModelState.IsValid property right at the start of the controller method:
[HttpPost]
[Route("Stuff/Ids/")]
public void PostStuff(List<int> Ids)
{
    if(!ModelState.IsValid)
        throw new Exception("ModelState is not valid.");

    // Carry on...
}

The ModelState.IsValid is indeed false in the case described by my question.
The check can be made global by creating an action filter out of it. Instructions for this can be found for example in this article: Model Validation in ASP.NET Web API


Probabilistic interpretation of Thin Plate Smoothing Splines

Question: TLDR: Do thin plate regression splines have a probabilistic/Bayesian interpretation?
Given input-output pairs $(x_i,y_i)$, $i=1,...,n$; I want to estimate a function $f(\cdot)$ as follows
\begin{equation}f(x)\approx u(x)=\phi(x_i)^T\beta +\sum_{i=1}^n \alpha_i k(x,x_i),\end{equation}
where $k(\cdot,\cdot)$ is a kernel function and $\phi(x_i)$ is a feature vector of size $m<n$. The coefficients $\alpha_i$ and $\beta_i$ can be found by  solving
\begin{equation}
 {\displaystyle \min _{\alpha\in R^{n},\beta \in R^{m}}{\frac {1}{n}}\|Y-\Phi\beta -K\alpha\|_{R^{n}}^{2}+\lambda \alpha^{T}K\alpha},\end{equation}
where the rows of $\Phi$ are given by $\phi(x_i)^T$ and, with some abuse of notation, the $i,j$'th entry of the kernel matrix $K$ is ${\displaystyle k(x_{i},x_{j})} $. This gives
\begin{equation}
\alpha^*=\lambda^{-1}(I+\lambda^{-1}K)^{-1}(Y-\Phi\beta^*)
\end{equation}
\begin{equation}
\beta^*=\{\Phi^T(I+\lambda^{-1}K)^{-1}\Phi\}^{-1}\Phi^T(I+\lambda^{-1}K)^{-1}Y.
\end{equation}
Assuming that $k(\cdot,\cdot)$ is a positive definite kernel function, this solution can be seen as the Best Linear Unbiased Predictor for the following Bayesian model:
\begin{equation}
y~\vert~(\beta,h(\cdot))~\sim~N(\phi(x)\beta+h(x),\sigma^2),
\end{equation}
\begin{equation}
h(\cdot)~\sim~GP(0,\tau k(\cdot,\cdot)),
\end{equation}
\begin{equation}
\beta\propto1,
\end{equation}
where $\sigma^2/\tau=\lambda$ and $GP$ denotes a Gaussian process. See for example https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2665800/
My question is as follows. Suppose that I let $k(x,x'):=|x-x'|^2 \ln(|x-x'|)$ and $\phi(x)^T=(1,x)$, i.e. thin plate spline regression. Now, $k(\cdot,\cdot)$ is not a positive semidefinite function and the above interpretation doesn't work. Does the above model and its solution still have a probabilistic interpretation as for the case the $k(\cdot,\cdot)$ is positive semidefinite?
Comment: This was just a side remark because in the question one may think that
$x_i$ are scalars. But in this case Duchon's kernel has the form
$|x - x'|^{2m-1}$ with $m$ integer, and $m=2$ for the usual smoothing
spline. I think that the probabilistic interpretation remains
nearly unchanged but the GP is non-stationary: it is an *Intrinsic Random
Function*. For the usual smoothing spline, this turns out to be an
integrated Wiener process.
Comment: @Yves that sounds interesting. You may want to expand your comment to an answer, explaining a bit more what an intrinsic random function is, and adding the classic example of the smoothing spline. If you worry about _proving_ that the TPS kernel gives rise to a non-stationary GP, maybe a simulation could be a useful compromise, especially if you add a non parametric estimate of the variance of the posterior predictive distribution.
Comment: You seem to assume the $x$ is in a $d$-dimensional space with $d=2$ or at least that the integer $d$ is even.
Comment: Ok, so what are the implications?
Comment: @DeltaIV. Thank you. I will try to do it, not an easy task yet. I am quite sure this holds when the functions $\phi_j$ are suitable polynomials related to the kernel, but this might no longer be true with arbitrary $\phi_j$ as in the more classical GP context.
Answer: Let the model of the question be written as
\begin{equation}
   \tag{1}
   Y_i = \boldsymbol{\phi}(\mathbf{x}_i)^\top\boldsymbol{\beta} +
   h(\mathbf{x}_i) + \varepsilon_i
\end{equation}
where $h(\mathbf{x})$ is an unobserved GP with index
$\mathbf{x} \in \mathbb{R}^d$ and $\varepsilon_i$ is a normal noise
term with variance $\sigma^2$. The GP is usually assumed to be
centered, stationary and non-deterministic. Note that the term
$\boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\beta}$ can be
regarded as a (deterministic) GP with kernel
$\boldsymbol{\phi}(\mathbf{x})^\top \mathbf{B}\,
\boldsymbol{\phi}(\mathbf{x})$ where $\mathbf{B}$ is a ``infinite-valued''
covariance matrix. Indeed, by taking $\mathbf{B} := \rho \, \mathbf{I}$
with $\rho \to \infty$ we get the kriging equations of the
question. This is often named the diffuse prior for
$\boldsymbol{\beta}$. A proper posterior for $\boldsymbol{\beta}$
results only when the matrix $\boldsymbol{\Phi}$ has full rank. So the
model writes as well as
\begin{equation}
   \tag{2}
    Y_i  = \zeta(\mathbf{x}_i) + \varepsilon_i
\end{equation}
where $\zeta(\mathbf{x})$ is a GP. The same Bayes interpretation can
be used with restrictions when $\zeta(\mathbf{x})$ is no longer a GP
but rather is an Intrinsic Random Function (IRF). The derivation can
be found in the book of G. Wahba.  Readable presentations
of the concept of IRF are e.g. in the book by N. Cressie and the
article by Mardia et al cited below. IRFs are similar to the
well-known integrated processes in the discrete-time context (such as
ARIMA): an IRF is transformed into a classical GP by a kind of
differencing operation.
Here are two examples of IRF for $d=1$. Firstly, consider a Wiener
process $\zeta(x)$ with its initial condition $\zeta(0) = 0$ replaced
by a diffuse initial condition: $\zeta(0)$ is normal with an
infinite variance. Once a value $\zeta(x)$ is known, the IRF can be
predicted as is the Wiener GP. Secondly, consider an integrated
Wiener process given by the equation $$ \text{d}^2 \zeta(x) /
\text{d}x^2 = \text{d} W(x)/\text{d}x $$ where $W(x)$ is a Wiener
process. To get a GP we now need two scalar parameters: two values
$\zeta(x)$ and $\zeta(x')$ for $x \neq x'$, or the values $\zeta(x)$
and $\text{d}\zeta(x) / \text{d}x$ at some chosen $x$.  We may
consider that the two extra parameters are jointly Gaussian with an
infinite $2 \times 2$ covariance matrix. In both examples, as soon as
a suitable finite set of observations is available, the IRF is nearly
coped with as a GP. Moreover we used a differential operator: $L :=
\text{d}/ \text{d}x$ and $L := \text{d}^2/ \text{d}x^2$ respectively.
The nullspace is a  linear space $\mathcal{F}$ of functions $\phi(x)$
such that $L \phi = 0$. It contains the constant function
$\phi_1(x)=1$ in the first case and the functions $\phi_1(x)=1$ and
$\phi_2(x) = x$ in the second case. Note that in the first example
$\zeta(x) - \zeta(x + \delta)$ is GP for any fixed $\delta$ in the
first example and similarly $\zeta(x-\delta) - 2 \zeta(x) + \zeta(x +
\delta)$ is a GP in the second case.
For a general dimension $d$, consider a linear space $\mathcal{F}$ of functions
defined on $\mathbb{R}^d$. We call an increment
relative to $\mathcal{F}$ a finite collection of $s$ locations
$\mathbf{x}_i \in \mathbb{R}^d$ and $s$ real weights $\nu_i$ such that
$$
    \sum_{i=1}^s \, \nu_i \,\phi(\mathbf{x}_i) = 0
    \text{ for all } \phi \in \mathcal{F}.
$$
Consider $\mathcal{F}$ as being the nullspace of our examples. For the first example we can take e.g. $s=2$ with $x_1$ and $x_2$
arbitrary and $[1, \, -1]$. For the second example we can take $s = 3$
equally spaced $x_i$s and $\boldsymbol{\nu} = [1,\,-2,\,1]$. The
definition of an IRF involves a space of functions $\mathcal{F}$ and a
function $g(\mathbf{x}, \, \mathbf{x}')$ which is conditionally
positive w.r.t. $\mathcal{F}$, which means that
$$
     \sum_{i=1}^s \sum_{j=1}^s \nu_i \nu_j \, g(\mathbf{x}_i,
     \, \mathbf{x}'_j) \geq 0
$$
holds as soon as $[\nu_i,\,\mathbf{x}_i]_{i=1}^s$ is an increment
w.r.t. $\mathcal{F}$. From $\mathcal{F}$ and $g(\mathbf{x},\,\mathbf{x}')$
we can make a covariance kernel hence a GP as in Mardia et al. We can
start from a linear differential operator $L$ and use the nullspace as $\mathcal{F}$; the IRF will then have connection with the equation $L \zeta =$ a Gaussian noise.
The computation of the prediction of the IRF is nearly the same as in
the question, with $k(\mathbf{x},\,\mathbf{x}')$ replaced by
$g(\mathbf{x},\,\mathbf{x}')$, but with the $\phi_i(\mathbf{x})$ now
forming a basis of $\mathcal{F}$. The extra constraint
$\boldsymbol{\Phi}^\top \boldsymbol{\alpha} = \mathbf{0}$ must be
added in the optimisation problem, which will grant that
$\boldsymbol{\alpha}^\top \mathbf{K} \boldsymbol{\alpha} \geq
0$. We still can add more basis functions which are not in
$\mathcal{F}$ if needed; this will have the effect of adding a
deterministic GP, say
$\boldsymbol{\psi}(\mathbf{x})^\top\boldsymbol{\gamma}$ to the IRF
$\zeta(\mathbf{x})$ in (2).
The thin-plate spline depends on an integer $m$ such that $2m> d$, the
space $\mathcal{F}$ contains polynomials with low degree, with
dimension $p(m)$ depending on $m$ and $d$.  It can be shown that if
$E(r)$ is the following function for $r \geq 0$ $$ E(r) :=
\begin{cases} (-1)^{m + 1 + d /2} \, r^{2m-d} \log r & d \text{
even},\\ r^{2m-d} & d \text{ odd,} \end{cases} $$ then
$g(\mathbf{x},\,\mathbf{x}') := E(\|\mathbf{x} - \mathbf{x}'\|)$
defines a conditionally positive w.r.t. $\mathcal{F}$. The
construction relates to a differential operator $L$. It turns out
that for $d=1$ and $m=2$ the thin plate spline is nothing than the
usual natural cubic spline, which relates to the integrated Wiener
example above, with $g(x,\,x') = |x - x'|^3$. So
(2) is nothing then than the usual smoothing spline model.
When $d=2$ and $m=2$ the nullspace has dimension $p(m)=3$
and is generated by the functions $1$, $x_1$ and $x_2$.
Cressie N Statistics for Spatial Data. Wiley 1993.
Mardia KV, Kent JT, Goodall CR and Little JA. Kriging and splines with derivative information. Biometrika  (1996), 83,1, pp. 207-221.
Wahba G Spline Models for Observational Data. SIAM 1990.
Wang, Y Smoothing Splines, Methods and Applications. Chapman and Hall, 2011.
Comment: Probably mean $m \ge 2d$ given the cubic spline example?
Comment: Thanks a lot for the effort that you put in. Extremely useful. I have a one additional question. So adding additional basis functions to $\boldsymbol{\phi}(\cdot)$ (on top of the basis functions of $\mathcal{F}$)  does not change the interpretation of  $\zeta(\cdot)$. What I did notice, however, is that the solution $\alpha^*$ given in my question above, always satisfies $\boldsymbol{\Phi}^\top \boldsymbol{\alpha} = \mathbf{0}$, not only if $\boldsymbol{\phi}(\cdot)\in \mathcal{F}$. How can this be interpreted?
Comment: Yes. In both cases there are $n+p$ basis functions in the
approximation of $f(x)$, while only $n$ observations are used. So we
have something like a rank-deficient regression with coefficients
$\beta_i$ and $\alpha_j$. Since the $\beta$ part is not penalised, it
tends to 'absorb' more of the variation of $y$ than does the $\alpha$
part which brings $p$ linear constraints.  Note that nothing forbids
the use of some of the $n$ "kernel shifts" functions $x \mapsto k(x,
x_i)$ as $\phi_j(x)$. If we use all of them then all $\alpha_j^\star$
are zero, which seems sensible.
Comment: @mathtick Thank you for pointing out this problem: the condition is $2m > d$.


Como criar getter de variavel Local Date?

Question: Eu tenho uma classe chamada Hospede, onde possuo o método getData_entrada(), que retorna uma variável LocalDate(nova API java8). Porém, quando tento capturar este método, ele me retorna sempre 'null'.
Detalhe: quando tento capturar os outros getters funciona normalmente.
//conteudo getData_entrada:

public LocalDate getData_entrada() {

        return data_entrada;
   }

     Hospede hospede = (Hospede) mStrings.get(position);

     textView_nome.setText(hospede.getNome());

     LocalDate data_Entrada = hospede.getData_entrada();

Comment: Tem como você colocar o conteúdo do `getData_entrada()` na pergunta?
Comment: public LocalDate getData_entrada() {
        return data_entrada;
    }
Comment: Ha varias formas de como resolver esse problema, nos explique melhor o contexto do seu aplicativo para que possamos lhe ajudar com a melhor opção.
Answer: Você pode definir o getData_entrada() desta forma abaixo:
public LocalDate getData_entrada() {
    return LocalDate.now();
}

Veja os métodos estáticos da classe pública LocalDate para obtenção da hora atual:

now(): Obtém a data atual do relógio do sistema no fuso horário padrão.
now(Clock clock): Obtém a data atual do relógio especificado.
now(ZoneId zone): Obtém a data atual do relógio do sistema no fuso horário especificado.

Veja mais detalhes na documentação.


Prove that a Series Converges without the Integral Test

Question: I am trying to prove that the series $$\sum_1^\infty \frac{1}{(k+1)\ln^\alpha(k+1)}$$ converges for $\alpha >1$ and diverges for $\alpha  <1$
I understand the proof using the integral test, but we haven't built the integral yet. We do have the p-test, Cauchy condensation, and the ratio test. I'm not totally sure where to start without the integral test.
Intuitively, using the comparison and p-tests, $\lim_{k \to \infty} \frac{1}{(k+1)\ln^\alpha(k+1)}$ approaches $0$ more quickly than $\lim_{k \to \infty} \frac{1}{k^p}$ with p = 1 if $\ln^\alpha(k+1) > 1$, but that seems to indicate convergence for $\alpha > 0$, rather than $1$
Comment: Cauchy condensation is specially designed for this one...
Comment: My edit was extra backets, as $ \ln (k+1)^a$ could be read as $\ln ((k+1)^a)$
Answer: Exercise: Let $D\subset \Bbb R$. Let $f:D\to [0,\infty)$ and $g:D\to [0,\infty)$ be increasing (i.e. for $a, b\in D,$ if $a<b$ then $f(a)\leq f(b)$ and $g(a)\leq g(b)$. And let $a>0.$ then (I)...$h(x)=f(x)g(x)$ is increasing, and (II)...$j(x)=g(x)^a$ is increasing.
Applying (II) with $D=[1,\infty)$ and $g(x)=\ln x,$ the function $j(x)=(\ln x)^a$ is increasing on $[1,\infty)$  when $a>0$. Applying (I) with $D=[1,\infty)$ and $f(x)=x$ and $g(x)=(\ln x)^a,$ with $a>0 ,$ the function $h(x)=x(\ln x)^a$ is increasing  on $[1,\infty).$
So  apply the Cauchy Condensation test. With $a(n)=[ n(\ln n )^a]^{-1}$ for $a>1,$ we have $2^na(2^n)=2^n[ 2^n\cdot (n\ln 2)^a)]^{-1}= [n\ln 2]^{-a}=b(n) $ which is decreasing if $a>0.$
So apply the Cauchy test again, to $b(n)=[n\ln 2]^{-a}.$ We have $2^n b(2^n)=2^n[2^n\ln 2]^{-a} =(\ln 2)^{-a} \cdot (2^{a-1})^n=c(n).$
Now $\sum_n c(n)$ is a geometric series. It converges iff   $2^{a-1}>1$ iff $a>1.$
Comment: Thanks, this makes perfect sense!
Comment: Thank you.  Note that the Cauchy Condensation Test for convergence of $\sum_n x_n$ works if $x_n$ is monotonic for all sufficiently large n, not necessarily for all $n$.... You may want to search this site for answered Q's about various convergent tests  & theorems.
Comment: Awesome, thanks, I am doing that as I go, any suggestions for good resources/practice sets beyond just variations of like "convergent(ce) test for series" or "prove series converges/diverges"
Comment: The classic old book "Infinite Sequences And Series" by Bromwich, which requires almost no pre-requisites.


Creating a speech recognition system for the Malinké language

Question: I want to create a speech recognition system for my native language (Malinké). How can I get what I say recognized in my language? Is there already a platform that allows me to record the phonetics of my language and transcribe it to text?
Comment: Which one? This is important to know as somebody already might have implemented that before.
Comment: You may want to specify your language in the question.
Comment: It is a local African language.
Comment: I don't find it anywhere(Language is Malinké).
Comment: You need to gather data (transcriptions and audio) from Malinke language. Then you can follow this tutorial using the deepspeech library: https://discourse.mozilla.org/t/tutorial-how-i-trained-a-specific-french-model-to-control-my-robot/22830
Answer: Speech recognition is a very non-trivial task. If you really want to create such a system, you will need many samples from native speakers. Once collected, a framework such as DeepSpeech from Mozilla might be a good starting point for you.
Mozilla also has another project called "Common Voice" which lets you donate voice samples to help create better voice recognition systems. However, they are really struggling to obtain data as you can see here. The smaller the community of native speakers, the harder it will be to create a good system.


Server does not support secure connections

Question: I'm getting the error "Server does not support secure connections" with my code below.
SmtpClient client = new SmtpClient(exchangeServer);
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(user, password);

MailAddress from = new MailAddress(fromAddress);
MailAddress to = new MailAddress(to);
MailMessage mail = new MailMessage(from, to);

// ...

client.Send(mail);

How can I fix this issue?
Comment: Have you tried `EnableSsl = false`?
Comment: Yes, if I set EnabledSsl = false, it will return the error: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
Comment: Setting enable ssl to false, more specifically, will only allow for sending emails within that domain, so if your domain was "mail.mybusiness.com", you can only send emails to "firstname.lastname@example.com"
Answer: Your server does not support SSL on the default port; Most won't.
When you set SSL off, you get the message, "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated"
That tells you that you are not authenticated. Further, you said in a comment, "Because if I set UseDefaultCredentials = true and use my own user address in the "from" address, I am able to send an email successfully."
This is apparently an issue with how the SMTP server is configured. You will need to get appropriate credentials, or have the SMTP server set to allow mail to be sent from the web server.
Comment: But how come I am able to send an e-mail using default credentials without changing the smtp server setting, like adding a port?
Comment: It will send on the default port if you don't specify one. That is the correct behavior. Your credentials have nothing to do with the port being used; It only seems like that because you changed multiple things at once (SSL setting and login settings)... a big no-no when trying to debug something ;-)
Comment: So does that mean the code above is okay? What specifically do I need to configure in the exchange server side so this issue will go away?
Comment: I can't answer that; what I would suggest might not be appropriate in your environment for security reasons.
Answer: What port are you using?  You may find that you need to specify the port in your SmtpClient object.
Comment: Is the port required? Because if I set UseDefaultCredentials = true and use my own user address in the "from" address, I am able to send an email successfully.
Comment: I had a quick Google, and a lot of answers seem to point to specifying a port.
Answer: write
client.EnableSsl = false;

Comment: As stated in above comment:**it will return the error: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated**


What is wrong with this jQuery element innerHTML statement?

Question: In my HTML page, I have a span:
...

In my $(document).ready function, I have the following.
if (document.getElementById("nlbNode")) {
    document.getElementById("nlbNode").innerHTML = "A";
}

And this works fine, however if I do this:
if (document.getElementById("nlbNode")) {
    $("#nlbNode").innerHTML = "A";
}

It does not work.  It does nothing.  Not even an error.  The span's innerHTML remains unchanged.
So, why doesn't it work?
Comment: in jquery use .html()   $("#nlbNode").html("A");
Comment: In jQuery `$()` function doesn't return a DOM element like it does in some other libraries.
Comment: I do not see innerHTML listed in the docs: https://api.jquery.com/
Comment: squint.  I wish I could upvote comments!  ;-)
Comment: For fun, I should mention that the other source I was looking at that made me feel my syntax was OK was "Experts Exhange".  That's why I prefer StackOverflow!  ;-)
Answer: jQuery's Node element doesn't have a innerHTML method. If you want to use innerHTML you can either retrieve the element's DOM counterpart via .get():
$("#nlbNode").get(0).innerHTML = "A"

Or use jQuery's .text() method:
$("#nlbNode").text("A");

Comment: or `$("#nlbNode").html("A");`
Comment: Apparently, I have to wait for enough minutes to pass before I can "accept an answer".  But I will, Griffith.  Thanks.
Comment: Both Griffith, and Arnav proposed solutions that showed me what was wrong.  Basically, I was using incorrect syntax.  I will have to give the answer to Griffith, as he answered first, however I would like to point out that I am actually going to implement +Pekka's answer as I prefer "html" to "text" because it sticks closer to the html DOM naming convention.  Thanks, guys.
Comment: Thanks, anonymous internet user, for the downvote just seconds AFTER the question has been answered.  I hope you aren't the "other guy" who is upset I didn't select your answer.  Especially after I thanked both of you.
Answer: I'm assuming, that since you said you included
$(document).ready(function() {};

that you have jQuery included somewhere. This means you can .html() to get the result.For example:
if (document.getElementById("nlbNode")) {
   $("#nlbNode").html("A");
}

EDIT
Sorry, I forgot to include the rest of the answer. You probably know this by now, although I will say it again. jQuery does not have an innerHtml method in its node since it doesn't return the DOM element like other frameworks.


Responding to links under an overlay div

Question: The scenario is this.
I've built a top navigation prototype which needs to have an overlay (transparent PNG) image on top of it. It currently covers about 1/3 of the links. Please see below:

Is there any way I can make the top 1/3 of the links respond even-though there's a
 covering them partly? The overlay won't contain anything clickable it's only a design feature.
I've never done this and wouldn't imagine it's possible but I look forward to being proven wrong.
Javascript/jQuery not preferred but will use as a last resort.
Here's a test case on jsFiddle, it directly mimics the structure of my current code.
Comment: You should be able to do it with some combination of `position: relative`, `position: absolute`, `z-index`, and possibly having to change the order of some elements in your HTML. It's difficult to give specifics without a live link or a test case. What's the point of the transparent PNG overlay?
Comment: @thirtydot, I've added a jsFiddle with a test case.
Comment: @Marko: Anything wrong [with this](http://jsfiddle.net/thirtydot/pXXpU/6/)?
Comment: @thirtydot, the image needs to cover the links, not the other way around.
Comment: @Marko: Ah, I see the problem.
Comment: It looks like I'll have to move the menu down thus making the links appear below the overlay.. Unless you have other ideas :/
Comment: @Marko: I posted the only answer I can think of. It's fairly annoying to do in practise, but it should work.
Answer: Yes, this IS POSSIBLE using pointer-events: none!
CSS
div.overlay {
    pointer-events: none;
}

Compatibility for IE (http://caniuse.com/pointer-events) is still non-existent so a conditional CSS statement is required:

If using an overlay div with CSS gradient background the above is enough. If using a transparent image (png, gif, etc), you'll need to add this to your conditional statement:
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='file-name.png', sizingMethod='scale');

Hope that helps.
Answer: you could make a transparent image the size of the tab and then put that image as a link and position it perfectly over the tab.
Comment: I don't quite follow you, explain further perhaps? Thanks for the idea though!
Answer: There's only one way to do this (as far as I know), and it's not great:
Live Demo

Add the same background image (to each) button that your .png with alpha channel overlaps.
Use background-position with pixel perfect offsets.

I'm lucky that in that demo it only overlapped the last button :)
Comment: Yeah I thought of that too but guess what. The menu items are 100% dynamic :)
Comment: @Marko: Thought I'd solved it there, ah well. What does `100% dynamic` mean? `%` based width?
Comment: The menu accross the site is dynamic, meaning they're not fixed width but rather are shrinkwrapped and calculated using their font-size + padding.
Comment: @Marko: Can't think of anything else :( (without resorting to jQuery to figure out the `background-position` based on button width)
Answer: No, only the top layer is clickable.
Comment: This is my opinion too, care to see if it's definitely the case!
Answer: the click() event can be emulated via jquery, although it may not apply to your problem...
You could also (as a last resort) replace the navigation and place it on top more or less like an imagemap...
Comment: The navigation is dynamic, that won't really work. Imagemap is also obsolete.
Comment: or maybe place the text part of the navigation to the top?, anyway, clicking on any part covered by the top div/image won't do anything.
Answer: Hm... use links with no text, with display: block and width and height set. Put inside a DIV as container and z-index to be over the divs from the menu, and position: absolute. Then set the right position for the container. Something like:

.linkOverlay
{
   z-index: 10;
   display: block;
   width: 100px;
   height: 40px;
   float: left;
}
.linkContainer{
   position: absolute;
   top: (top here);
   left: (left here);
}
[div class="linkContainer"]
    [a href="page.html" class="linkOverlay"][/a]
    [a href="page_two.html" class="linkOverlay"][/a]
[/div]

That's just the main idea, you will know how to do it :)
Comment: @Michael, see my update and comments above. The image needs to be on TOP of the anchors.
Answer: For what it's worth, this works in all but ie7, and is almost all CSS.  It just requires adding a little html:
http://jsfiddle.net/pXXpU/8/


BWV 893, London or Altnickol version?

Question: There are 2 versions of the B minor prelude from WTC 2, BWV 893 on IMSLP:
A. 'London version' which is in cut time.
B. 'Altnickol version' which is in 4/4, the note values diminutized proportionally, and the bar lines extended to 4 beats. There also includes some differences in ornamentation.
Which is the more correct version to play, and more commonly played?
Answer: Johann Christoph Altnickol (1720-1759) copied the second book of The Well-Tempered Clavier in 1744. A 2014 paper by Yo Tomita of Queen's University Belfast comes to the conclusion that this was Bach's preferred version. From the abstract:

One of Altnickol's earliest copies, and arguably the most important, is the second book of The Well-Tempered Clavier ... Presently Bach scholarship accepts that this fair copy is one of the primary sources of the celebrated work ... This paper examines a broad range of evidence ... to suggest that it was Bach himself who asked Altnickol to prepare this fair copy, that it remained in Bach's possession after Altnickol had left Leipzig in 1748, and that it was indeed Bach's most important reference copy.

The change in notation makes no difference to the way the piece would be played except for the ornamentation which would be subject to change by the player in any case.
Comment: @Pearl I feel like the meter change would matter more in some styles and less in others, and an argument that it matters not at all for solo baroque keyboard works is completely reasonable. An argument that it matters a lot more for a conducted concert band piece would also be reasonable, IMHO.
Comment: @Pearl Somebody will turn up here and claim there would be a difference, but I would challenge anybody to listen to a series of different recordings of the piece and correctly identify the edition each of them were using (ignoring any ornamentation differences).
Comment: Thanks. Is there really no difference in sound to 2 bars of double beat vs 1 bar of quadruple beat?

BWV 893, London or Altnickol version?


Markdown link ID not recognized

Question: Hopefully this is a simple problem...
After years of web development and sitting on all sorts of re-usable code I decided to combine everything into a custom CMS - mostly for my own usage. Threw together a git repository, made a README.md file, and... some of the links aren't working.
Here's my git repo: https://github.com/stevendesu/MyCMS
If you scroll to the bottom you'll notice the two links to php.net are posted as text, and further up in the document when I attempted to create links using these ID's it just displayed the markdown.
Anyone know what's going on?
Answer: I think the problem might be all of the whitespace between your urls and the title near the bottom. At the bottom of your README, I removed all of the whitespace (except for a single space to separate them) between the links. The resulting code looked like this:
<code>[1]: <http://wordpress.org> "WordPress.org"
[2]: <http://drupal.org> "Drupal (TM)"
[3]: <http://concrete5.org> "concrete5"
[4]: <http://www.php.net/manual/en/intro.pdo.php> "PHP.net: PDO - Introduction"
[5]: <http://www.php.net/manual/en/pdo.drivers.php> "PHP.net: PDO - Drivers"
</code>
Doing so fixed the hotlinks in the paragraphs above.
Comment: Fixed it, thanks! Odd that the links with lots of tabs worked and those with few tabs didn't....

Markdown link ID not recognized


Defining a default class property in Python?

Question: Not sure if this is possible in Python, but I'd like to have an instance of a class as a module-level global variable that, when called, returns a default property.
The idea comes from this question that overrides __call__ to have a class mimic a function.
Quick (untested) example of the idea:
class _foo(object):
    __slots__ = ("_foo",)
    _init = False

    def __init__(self):
        if not _init:
            self._foo = ["bar", "baz", "zog"]

    def __call__(self, item=None):
        if itme is not None:
            return self._foo[item]
        else:
            return self._foo

    def __getitem__(self, item):
        return self._foo[item]

# Module level
FOO = _foo()

Assume the above code is in a module (foo.py).  Using the interpreter, I cal get the callable form to work how I want, but not the non-callable form.
>>> import foo

# callable forms
>>> foo.FOO(0)
"bar"
>>> foo.FOO()
["bar", "baz", "zog"]

# attribute forms
>>> foo.FOO[2]
"zog"

# doesn't work
>>> foo.FOO
<foo._foo object at 0xdeadbeef>

# desired output
>>> foo.FOO
["bar", "baz", "zog"]

My thinking is that I need to define a default property somehow so that when calling the instance directly, I get the internal list/dict of my choosing.  I could cheat and do this via overriding repr, but that kinda breaks Python's own API and I want to avoid that.  Passing no value in square brackets (>>> foo.FOO[]) yields a syntax error instead.
I'd like any potential solutions to be compatible with Python 2.4 at minimum and 2.7 at maximum.  If this isn't possible, then I guess I'll just stick to using the callable format.
Comment: Wait, you want `foo.FOO` to be both a list and a callable?
Answer: This is impossible, sorry. You can't have foo.FOO be both a callable (a _foo instance) and an unadulterated list object.
Of course, I did say "unadulterated". If you're feeling sneaky...
class _foo(list):
    _init = False
    def __init__(self):
        if self._init:
            list.__init__(self)
        else:
            list.__init__(self, ['bar', 'baz', 'zog'])

    def __call__(self, item=None):
        if item is None:
            return self
        return self[item]

FOO = _foo()

Usage:
>>> FOO()
['bar', 'baz', 'zog']
>>> FOO(0)
'bar'
>>> FOO
['bar', 'baz', 'zog']

Comment: I don't want it to be both, no.  In a sense, FOO is a variable that stores an instance of `class _foo`, such that if I go `FOO(), I am really invoking the `__call__()` method and returning a list object.  What I would like to do instead is have a default property/attribute for `_foo` such that if it is directly referenced, instead of getting the address of the instance returned, some default handler returns the list instead.  IF that makes any sense.
Comment: You could do this in VB6, for example, by designation a specific property of a class as the class' default property.  Except in Python, I want to do this on a variable holding an instance of that class.  Overriding `__call__()` accomplishes this, but leads to odd-looking syntax like `x = foo.FOO()` to return the list, when instead I want `x = foo.FOO` and get the list instead.  It's really a style issue at heart, but I am curious if it can be done or not.
Comment: In Python, if you say `foo.FOO`, you get the `FOO` attribute (member) of the `foo` module (in general object), which in your case is always the `_foo` instance. This applies in any context. Accessing an attribute runs `__getattr__` on the parent object (in this case `foo`, but will never run anything on the attribute itself. You should mention you're coming from VB so that clears up the confusion.
Comment: I haven't worked in VB6 in a few years.  I just cited it as an example of a language that allows you to mark a specific property as a class' default.  I'd have gone into more detail, but these SO comment boxes don't allow line feeds and I only have 500 chars to type in.  I'll probably just stick with the callable form once I work out this infinite recursion issue.
Comment: Interesting. Parameterless default properties in VB6, if I understand them correctly, permit the use of a syntactic sugar which allows you to treat an object as if it were one of its properties. You can emulate much of the same functionality in Python by exploiting duck typing -- since most interfaces in Python don't do explicit type checks (preferring instead to rely on the object having certain attributes), if you expose the properties (attributes/methods) of the 'default property' as properties of your object, you get much the same effect as PDP.
Comment: Yup.  It's what allows you, in VB6, to do `TextBox1 = "FOO"` or `debug.print TextBox1` and set/get the `.Text` property because that is the default property for a TextBox object.  In Python, I'm working with the [dpkt](http://code.google.com/p/dpkt/) library, which has a clever routine in `dpkt.ethernet.Ethernet` to load a dict that stores a copy of objects of each ethertype protocol (IP, IPX, ARP, etc), based on a definition of `ETH_TYPE_*` at the top.  Problem is, in `dpkt.gre`, he tries to copy ethernet's `typesw` variable and in certain situations, this can lead to infinite recursion.
Comment: So I am trying to solve that AND remove redundant code by moving the initializer code to its own module, while retaining the `ETH_TYPE_*` definitions within their respective modules.  But I am still running into the infinite recursion issue.  Only solution right now is to duplicate all the supported `ETH_TYPE_*` definitions for the `dpkt.gre` module to break the recursion.
Comment: Have you ever *seen* it infinite recurse? That might be a bug...the `import` is at the bottom for a reason.
Comment: That's where this question derived from.  I am using the static class idea referenced in [this question](http://stackoverflow.com/q/460586) and just wanted to find a way to reference the class instance directly and get the types dict back (instead of the object reference) by having a default property.  Instead, I think I'm just going to stick with the callable form and find a solution to the infinite recursion before I send the code back upstream.
Comment: Yup.  In fact, I am adding new modules, such as LLC for IEEE 802.2 framing after IEEE 802.3 (not EthII).  This works fine on its own, but once I removed the redundant code from `dpkt.ethernet.Ethernet` and replaced it with a reference to `dpkt.llc.LLC`, I tripped the recursion up.  If I solve the recursion, I can reference the LLC module and get proper layer separation between each protocol.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16802/discussion-between-nneonneo-and-kumba)
Answer: I'm not sure what you mean by Right now, when I try this within another module, I get an AttirbuteError that FOO doesn't exist within the module, this code that imports your module works correctly for me
import foo
FOO2 = foo.FOO
print(FOO2())
print(FOO2(1))

Python 2.7.3
Comment: It's possible Python 2.7 does things better.  I only have access to an antiquated Python 2.4 environment right now, so I may be fighting some quirk present in 2.4 that was addressed in newer releases.  I wrote the example based off existing code, and that existing code is not working correctly.  Going to open another question on it in a few minutes.
Comment: It appears part of my issue with this is a case of infinite recursive module loading.  Not the original author of the library I am working in, so I have to figure out a cleaner way of doing what that library is trying to do.
Answer: Define __repr__(self) on your class to define how its instances appear in the Python inteprreter. In this case, perhaps return repr(self._foo).
Comment: The interpreter example is just for reference to support the question.  The goal is to have other modules be able to `import foo` then do something like `x = foo.FOO` and x receives a copy of the foo.FOO instance (copy or pointer, whatever works).  Right now, when I try this within another module, I get an AttirbuteError that `FOO` doesn't exist within the module, despite the example working fine in the interpreter.
Comment: There'sno problem making foo.FOO be an instance of some type and also making this type callable. I guess I'm not clear on what you're trying to do.


Resgatar valores do Cookie

Question: Boa tarde tenho uma aplicação em MVC que gera alguns cookies, gostaria de saber se é possível resgatar esses cookies através de uma Api, pois tentei e infelizmente não consegui.
Código gerado para a api:
[Route("ResgataCookie")]
[HttpGet]
public IHttpActionResult ResgataCookie()
{
    string test = "";
    if (HttpContext.Current.Request.Cookies["RMACookies"] != null)
    {
        test = HttpContext.Current.Request.Cookies["RMACookies"].Value;
    }

    return Ok(test);
}

Segue imagem abaixo:
Answer: Os Cookies na WebAPI podem ser acessados utilizando o Request.Headers.GetCookies
Veja a documentação em https://docs.microsoft.com/pt-br/aspnet/web-api/overview/advanced/http-cookies
Segue exemplo abaixo
[HttpGet]
[Route("ResgataCookie")]
public IHttpActionResult ResgataCookie()
{
  var cookies = Request.Headers.GetCookies().FirstOrDefault();

  if (cookies == null || !cookies.Cookies.Any(p => p.Name == "RMACookies"))
    return NotFound();

  var item = cookies.Cookies.First(p => p.Name == "RMACookies").Value;

  return Ok(item);
}

Comment: Olá amigo fiz dessa forma, também mas o mesmo me retorna nulo. os cookies são gerados em uma aplicação MVC padrão, mas estou tentando acessar os cookies através da api e infelizmente retornam em branco.
Comment: Você esta tentando acessar os cookies de outra aplicação?

Lembrando que os cookies são armazenados por domínios e subdominios então se forem diferentes você não vai ter acesso mesmo.
Comment: Muito Obrigado Danilo.

Resgatar valores do Cookie


Can Apache Access Logs be kept separated & also combined as well too?

Question: My question my be a bit confusing, and sorry for that. Here is what i need:
Well, i have (let's say) 3 Websites hosted on one Apache (which are defined inside each VirtualHost settings. Then i currently log their Access Logs separately as in:

/var/log/httpd/website-a.com.access_log
/var/log/httpd/website-b.com.access_log
/var/log/httpd/website-c.com.access_log

Define something like this:
<VirtualHost *:80>
    ServerName website-a.com
    ..
    CustomLog logs/website-a.com.access_log common
    ..
</VirtualHost>

So it is all fine. But at the same time, i ALSO want them (all the access logs) altogether inside the Apache's default localhost log file (i'm not sure how to call that one). May be:

/var/log/httpd/access_log (I think this is default one)

In other words, is there a way to (how to) keep the Access Logs in the separated manner, and at the same time, keep all in the same combined file also?

So this will allow me to see each of the Access Logs in their separated files. And at the same time, i can see all the logs in one place also IF I NEED TO.
Answer: <VirtualHost *:80>
    ServerName website-a.com
    ..
    CustomLog logs/website-a.com.access_log common
    CustomLog logs/access_log common
    ..
</VirtualHost>

Just add CustomLog logs/access_log common to each virtual host as a second log file and apache will write to both.


Compile an array by including quantity without using JQuery

Question: I was working on an application that needs to have the ability to compile by quantity and decompile back into a large list. Here is some psuedo code for what I am struggling to create in Javascript.
Psuedo Code:
var array = [lorem, lorem, lorem, doler, doler, sit];
var orginizedArray = [];
var unorginizedArray = [];

function compileArray(orgianal, result){
    //code
}

compileArray(array, orginizedArray);

console.log(organizedArray);

function decompileArray(original, result){
    //code
}

decompileArray(orginizedArray, unorginizedArray);

console.log(unorginizedArray);

Console Log:
[4 lorem, 2 doler, 1 sit]
[lorem, lorem, lorem, doler, doler, sit]

Thank you all so much who can help me figure this out as I hit a huge roadblock trying to solve this.
Comment: What is your question? What is your code even supposed to do? And what do you mean by *"compile an array"*??
Comment: compile or combine ??
Comment: @UnholySheep. The question is how do I make the pseudo code into real Javascript code. The pseudo code also explains what exactly is going on and what it needs to do.
Comment: No, the pseudo code does not explain anything. You have an array, feed it into a function an get something out - that's a black box, not a description of what you need. Pseudocode would show what those functions are supposed to do, what the algorithm is, etc. . Also you are essentially asking for code, as you have not shown what you have tried doing to solve this issue yourself.
Answer: The Array.prototype.reduce()  function can group an array like this.
var array = ["l", "l", "l", "d", "d", "s"];
var filtered = array.reduce(function(accumulator,current){
  for(var i = 0; i < accumulator.length; i++){
   if(accumulator[i].val == current) {
     accumulator[i].count++;
     return accumulator;}
  }
  accumulator[i] = {count:1, val:current};
  return accumulator;
}, []);
// filtered == [{count:3, val:"l"},{count:2, val:"d"},{count:1, val:"s"}]

You can loop through this array to 'decompile' the array back into its parts
array = [];
filtered.forEach(function(group) {
  for(var i = 1; i <= group.count; i++)
  {
    array.push(group.val);
  }
});
// array == ["l", "l", "l", "d", "d", "s"]

Answer: var array = ['lorem', 'lorem', 'lorem', 'doler', 'doler', 'sit'];
   var organizedArray = [];
   function compileArray()
   {
       var currentNum = 0;
       for (var i = 0; i < array.length; i++)
       {
           currentNum++;
           if (array[i] == array[i + 1])
           {
               continue;
           }
           else
           {
               organizedArray.push(currentNum + ' ' + array[i]);
               currentNum = 0;
           }
       }
   }
   compileArray();
   console.log(organizedArray);


Como alterar o ícone de um arquivo .jar?

Question: Gostaria de saber como faço pra mudar o ícone de um arquivo .jar.
Há alguma maneira de se fazer isso usando o Scene Builder?
Answer: Eu não acredito que você consiga mudar o ícone do arquivo .jar, já que quem define isso é o próprio SO (você pode até mudar o ícone sem utilizar java, mas isso mudaria para todo .jar que existe no computador). O que eu já fiz é mudar o ícone que fica na barra de tarefas e na janela do programa quando ele é executado usando algo parecido com isso (não tenho o código comigo agora, mas é algo bem parecido):
<code>getFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("caminhoDaImagem"));
</code>
O que eu já vi algumas pessoas fazendo, é utilizar um executable wrapper pra "transformar" (ele não transforma o .jar em .exe, mas não vou entrar em detalhes) o .jar em um executável. Algumas ferramentas pra isso são:
launch4j
Jsmooth


How to correctly retrieve int from a Google App Engine datastore (Java)?

Question: I am building a servlet that needs to retrieve an Entity from a GAE datastore, and then perform certain tasks depending on the entity's "STAGE" property, which is an integer. My code ends up looking like this:
switch( (int) (long) (Long) phrase.getProperty("STAGE")){

This works fine but the code is incredibly ugly and I can't help thinking this can be accomplished in a simpler and perhaps more efficient way.
Thank you,
Billy
Comment: Its java, nothing is as simple as it should be.
Comment: If `STAGE` was saved as long then you should treat is as long.
Comment: ((Long) phrase.getProperty("STAGE")).intValue() if you are sure that there will be always not null value.
Answer: switch( ((Number)phrase.getProperty("STAGE")).intValue() ) {