Consonance & Dissonance Relative To Melodies

Question: I've been reading of consonant and dissonant intervals within a scale and was wondering if this is a rule that is generally applied in current music? Can this rule help make a melody for example if I was in C natural minor:
C - Eb - F - Bb - C -- the melody would unresolved if it was: C - Eb - F - Bb right? so that Bb HAS to be resolved?
I've got the information that 1st, 3rd, 4th, 5th, 6th notes are consonants and 2nd and 7th notes are generally dissonant.
Comment: Yes, it's still relative today though alot of innovations have come about. You're better off concentrating on the consonance/dissonance between melody notes and a chord than on the consonance/dissonance in some sort of scale.
Comment: It totally depends on the musical style, in fact some music rejects the consonance/dissonance distinction entirely, or at least ignores any rules about it. That being said, in traditional musical styles the 6th and (especially) the 4th are generally dissonant as well. Most important of all is @Grey 's comment that the prevailing harmony of any given moment will generally override any scalar "rules" entirely. For example, if there's a V chord (G), the 7th scale degree will sound consonant. Of course, that's part of why V chords tend to go to I, but that's a different question.
Comment: It's mainly my melodies that don't sound great or I can't really come up with anything 'interesting' I had an idea of practising to build tension and release to create my melodies but I don't know which notes create tension and which notes create resolution?
Answer: Typically when we talk about a note or scale degree being consonant or dissonant we are usually relying on harmonic or intervalic context.  The terms "consonant" and "dissonant" usually deal with the relationship of two or more notes, (see wikipedia for consonance and dissonance, which says as of today "In music, a consonance [...] is a harmony, chord, or interval considered stable".)
Thus, I find your statement

I've got the information that 1st, 3rd, 4th, 5th, 6th notes are
  consonants and 2nd and 7th notes are generally dissonant.

to be somewhat misguided.  A note can only be dissonant based upon context.  For example, in C natural minor, the leap from D -> Ab is a tritone, which is a dissonant interval.  In order for a scale degree to be considered dissonant or consonant would require that it be compared to the preceding or subsequent melodic note, or to the underlying harmony.
As far as whether this is still relevant in modern music, it depends on genre.  But in most genres the concept of intervalic consonance/dissonance is still very relevant.
Edit: I tried to soften the absolutism of my answer a bit in response to Pat's valid comment that "there are higher-level dissonances such as relation to the overarching key". This is definitely true but I think context is still paramount.  For example in a completely silent room if I think inside my mind "I'm going to play a note from the key of C major", then walk up to the piano and play a B, that note is not intrinsically dissonant.  Only if I first establish the tonal center can it be heard as a leading tone.  I think it is appropriate to steer the OP in the direction of harmonic and melodic context and away from the idea that scale degrees are inherently consonant or dissonant.
Comment: No, there are higher-level dissonances such as relation to the overarching key. In common-practice music the seventh scale degree (and to a lesser extent, the second, fourth and sixth) is inherently dissonant in this long-term sense, even though it may be rendered temporarily consonant in a short-term sense by accompanying it with a V chord. Indeed, the standard progressive behavior of most harmonies in common-practice music is really just a concatenation of the large-scale dissonances of its constituent pitches, regardless of the consonance of the current harmony or interval.
Comment: Far from being purely academic, I think this exploitation of multiple, sometimes contradictory, levels of consonance and dissonance is one of the greatest beauties of common-practice tonal music. At any rate, I'm only saying that this answer is incorrect to the extent that it denies the consonance and dissonance at the scalar/key level, not for saying that intervallic and local dissonance exists.
Comment: @PatMuchmore I agree that the leading tone could be considered intrinsically dissonant but I would have a hard time applying intrinsic levels of dissonance to other scale degrees.  in any event, I still think it is misguided to say 1, 3, 4, 5 and 6 are "consonant" in the absence of harmonic or melodic context (especially in a natural minor key where the 6 often feels like it wants to resolve down a half step to the 5!)  I do think context is more important for the OP than intrinsic consonance/dissonance of scale degrees.
Comment: Well, yes, "only intervals" can be dissonant, but intervals can be used horizontally in constructing melodies, and thus melodies can be dissonant, too.
Comment: @pat-that's a pretty academic stance, which lead to a lot of confusion. It would be helpful if we came up with a different set of terms for dissonance in this context. For example if I have a excerpt that is a c natural suspended over a g-major chord, you and I both know the c is dissonant; everyone's ears know it's dissonant. We all want it to resolve down. Right? Does any of this change if the key of the piece is C-major? Is the C natural suddenly consonant? If the piece is in G major does the situation really reverse itself?
Comment: -1 Consonance and dissonance ate very broad concepts in music. Saying that one can only apply them in certain situations is simply wrong.
Comment: @MarkM I think you're misunderstanding me. Your example is only a contradiction if you ignore different levels of function. Of course a C suspended above a G major chord is a dissonance regardless of key, but it is a *local* dissonance—one that is often very strong and must resolve locally as when a cadential 6/4 resolves to V. But that V must nevertheless resolve to I due to the higher level dissonance of the (locally consonant) leading tone. The fact that the tonic note is temporarily made to be a dissonance is precisely part of the power of the cadence.
Comment: @Grey horizontal notes form intervals, i.e. two notes do not need to sound simultaneously to form an interval.  Horizontal notes form "melodic intervals".
Comment: @MatthewBriggs Oh yes, I agree the question is misguided, and as I said in my comment on the question, it's flat-out wrong to include 4 and 6 in a list of high-level consonances. Stil, the OP is referring to scalar stability in the question. That isn't a false concept, just not necessarily what they should be focused on. Your answer says that *only* intervals and chords can be dissonant and that's not true either. Dissonance exists on many levels (not to mention rhythmic and metric dissonance),
Comment: @PatMuchmore I tried to clean it up a little, hopefully didn't make it worse...
Comment: Ah, excellent edit, I've changed my -1 to a +1. I'm not sure they need to be steered *away* from scalar/key stability necessarily, but they obviously need to think about immediate context as well—and perhaps even more so for the time being.
Comment: I have done a lot of analysis and reading and have come across the idea of consonant and dissonant tones within a scale (1,5,3) = Stable and (6, 2, 4, 7) = Dissonant...I've also analysed note by note and has always come to the pattern that follows. Is it correct?


Two decimal jquery round not found

Question: Do not quite understand the jquery but in spite of that I have created the following code, but the field IGV dollar does not throw me two decimal places.
For example if I enter 1200 gives me a value of 216 when it should be 216.00
Example: http://jsfiddle.net/XyqCw/
$('.precio').keyup(function () {
    var igvdolaresround = (Number($(this).val()) * 18) / 100;
    var igvdolares = igvdolaresround /* :( not found (igvdolaresround).toFixed(2); */
    var totaldolares = ((Number($(this).val()) + igvdolares).toFixed(2));
    var igvsoles = ((igvdolares * 2.80).toFixed(2));
    var totalsoles = ((totaldolares * 2.80).toFixed(2));
    $('#igvdolares').val(igvdolares);
    $('#totaldolares').val(totaldolares);
    $('#igvsoles').val(igvsoles);
    $('#totalsoles').val(totalsoles);
});

function maxLengthCheck(object) {
    if (object.value.length > object.maxLength) object.value = object.value.slice(0, object.maxLength)
}

Answer: Because you are not using toFixed(2) on that number like you are doing in other places.
$('#igvdolares').val(igvdolares);

to
$('#igvdolares').val(igvdolares.toFixed(2));

Answer: Here is the solution,
$('.precio').keyup(function () {
    var igvdolaresround = (Number($(this).val()) * 18) / 100;
    console.log(Number(igvdolaresround));
    var igvdolares = igvdolaresround /* not found (igvdolaresround).toFixed(2); */
    var totaldolares = ((Number($(this).val()) + igvdolares).toFixed(2));
    var igvsoles = ((igvdolares * 2.80).toFixed(2));
    var totalsoles = ((totaldolares * 2.80).toFixed(2));
    $('#igvdolares').val(Number(igvdolares).toFixed(2));
    $('#totaldolares').val(totaldolares);
    $('#igvsoles').val(igvsoles);
    $('#totalsoles').val(totalsoles);
});

function maxLengthCheck(object) {
    if (object.value.length > object.maxLength) object.value = object.value.slice(0, object.maxLength)
}

I have even made the change to your JSFiddle Code you can check that out.
http://jsfiddle.net/XyqCw/1/

Two decimal jquery round not found


Hibernate com Java 9

Question: Eu tenho um projeto pessoal usando Hibernate com java 9, e me parece que não roda de jeito nenhum! Segue o erro:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1787)
    at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8863)
    at javafx.controls/javafx.scene.control.Button.fire(Button.java:200)
    at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:206)
    at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3876)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1300(Scene.java:3604)
    at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1874)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2613)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:397)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:434)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:433)
    at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
    at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
    ... 51 more
Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
    at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
    at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:208)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:170)
    at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:76)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:181)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:129)
    at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:71)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:52)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at br.com.bookper.coneccoes.util.JPAUtil.<clinit>(JPAUtil.java:9)
    at br.com.bookper.controladores.ControladorLoginESenha.clickRegistrar(ControladorLoginESenha.java:108)
    ... 62 more
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 75 more

Trechos do código:
            // ...
            Gerente gerente = new Gerente();
            gerente.setNome(txtNomeGerente.getText());
            gerente.setSenha(txtSenhaRegistro.getText());
            gerente.setNomeUnidade(txtNomeUnidade.getText());
            gerente.setCodigoAtivacao(txtCodigoDeAtivacao.getText());
            try {
                EntityManager em = new JPAUtil().getEntityManager();
                DAO dao = new DAO(em);
                dao.cadastrar(gerente);
                logar();
            }catch(Exception e){
                System.out.println(e);
            }
            // ...

@Entity
public class Gerente implements Entidade{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String nome;
    private String email;
    private String senha;
    private String codigoAtivacao;
    private String nomeUnidade;
    @OneToMany(mappedBy="gerente", fetch = FetchType.EAGER)
    private List<Funcionario> funcionario;
    @OneToMany(mappedBy="gerente", fetch = FetchType.EAGER)
    private List<Cliente> cliente;
    ...
}

public class JPAUtil {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("bookper");

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

}

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence         http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">

<persistence-unit name="bookper">

    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <class>br.com.bookper.coneccoes.modelo.Gerente</class>
    <class>br.com.bookper.coneccoes.modelo.Funcionario</class>
    <class>br.com.bookper.coneccoes.modelo.Cliente</class>
    <class>br.com.bookper.coneccoes.modelo.Avaliacao</class>
    <class>br.com.bookper.coneccoes.modelo.Livro</class>

    <properties>

        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>

        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/bookper"/>

        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value=""/>

        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>

        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.format_sql" value="true"/>
    </properties>
</persistence-unit>

Preciso usar Java 9 por causa de uma dependência, então usar Java 8 não é viável. Segue o github do projeto, caso queiram dar uma olhada mais de perto: https://github.com/vitorjordao/bookper (o erro vai ocorrer quando tentar registrar alguém).
Comment: Adicione também o código que gera o erro no formato de um **[mcve]**, forçar quem quer te ajudar a baixar seu projeto não é legal, facilite a vida de quem for te ajudar adicionando aqui.
Answer: Na exceção temos:
Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

Ou seja, não encontrou JAXBException (em tempo de execução, só).
JAXB APIs são consideradas como sendo JAVA EE APIs, e portanto não estão mais no classpath default do Java 9.
Solução rápida:
Adicionar os módulos que não são mais carregado por padrão com a opção na linha de comando --add-modules java.se.ee
Porém é possível que esses módulos sejam removidos em futuras versões do Java. Assim...
Solução recomendada:
Incluir sua própria cópia no class path ou module path. Por exemplo, para adicionar as JAX-B APIs como uma dependência maven:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

Referência:
https://stackoverflow.com/questions/43574426/how-to-resolve-java-lang-noclassdeffounderror-javax-xml-bind-jaxbexception-in-j

Hibernate com Java 9


Prove $\det(M)=\det(A)\det(B)$ by induction

Question: Prove by mathematical induction on the size of matrix A that
$\begin{equation}
\begin{aligned}
&\operatorname{If} M \in M_{n \times n}(K) \text { and } A \text { y } B \text { are square } M=\left[\begin{array}{cc}
A & 0 \\
0 & B
\end{array}\right] \text { then }\\
&\det (M)=\det(A)\det(B)
\end{aligned}
\end{equation}$
I try this
If A is a Matrix $1\times1$ then $\det(M)=\det(\begin{bmatrix}
A & 0 \\
0 & B
\end{bmatrix})=a_1\det(B)=\det(A)*\det(B)$
If A is a Matrix $2\times2$ then $\det(M)=\det(\begin{bmatrix}
A & 0 \\
0 & B
\end{bmatrix})=a_1\det(\begin{bmatrix}
A_{11} & 0 \\
0 & B
\end{bmatrix})+(-1)^{3}a_2\det(\begin{bmatrix}
A_{12} & 0 \\
0 & B
\end{bmatrix})=a_1a_4\det(B)-a_2a_3\det(B)=\det(B)(a_1a_4-a_2a_3)=\det(B)\det(A)$
Then I suppose is true for a matrix $n\times n$ with a matrix $A_{s\times s}$
and this is where I'm stuck to prove it is valid for a matrix $A_{s+1\times s+1}$
Comment: Non-inductive proofs galore: https://math.stackexchange.com/questions/75293/determinant-of-a-block-lower-triangular-matrix
Comment: For an inductive proof, see the solution to Exercise 6.29 in [my *Notes on the combinatorial fundamentals of algebra*](http://www.cip.ifi.lmu.de/~grinberg/primes2015/sols.pdf). It's a rather boring argument and not easy to summarize in a quick hint. The best I can do is "expand $\det M$ along the first row, and realize that this boils down to the same as expanding $\det A$ along the first row".
Answer: If $A$ is $n_1\times n_1$ and $B$ is $n_2\times n_2$ then $\begin{pmatrix}A&0\\0&B\end{pmatrix}=\begin{pmatrix}A&0\\0&I_{n_2}\end{pmatrix}\begin{pmatrix}I_{n_1}&0\\0&B\end{pmatrix}$
What you showed for $1\times 1$ matrix just extends to $I_n$ of any size (very straightforward induction).
So the determinant of the first matrix is $\det(A)$ and for the second one $\det(B)$.
Then use $\det(XY)=\det(X)\det(Y)$ property.
Answer: Hint: Expand along the first row.
Comment: The user who voted to delete this answer cannot expand along the first row?
Comment: I did this $\begin{equation}
det(M)=\sum_{j=1}^{s+m+1}(-1)^{1+j} a_{1 j} det(M_{1j})
\end{equation} $ = $\begin{equation}
det(M)=\sum_{j=1}^{s+m+1}(-1)^{1+j} a_{1 j} det(A_{1j}det(B))
\end{equation}$ = $detAdetB$ is this right?
Comment: Yes, that is right.
Comment: There is a ")" missing. And before the last "=" you should take $\det B$ outside the $\Sigma$.


What does this mean: v=spf1 include:_spf.google.com ~all?

Question: In addition to my previous question, what does this DNS entry mean:
 v=spf1 include:_spf.google.com ~all  ?

Answer: This is a SPF record.
The include directive includes SPF records for the domain _spf.google.com. This way Google can add and remove permitted mail servers without you having to change your DNS record whenever Google updates their settings.
The ~all means that receiving mailservers should accept Emails even the SPF verification failed, but mark them as failed. This is called "SoftFail". In comparison -all is a "HardFail", saying "don't accept the Email if the SPF verification failed.
Comment: Can the first use of the word *domain* in this accepted answer be changed to *host* instead? The domain is google.com, the host is _spf.google.com.
Answer:
When you are configuring email handling for your domain, you might need to know the IP addresses of the Google Apps mail servers, to help prevent Google messages from being marked as spam. (...)

v=spf1 include:_spf.google.com ~all

(...) With this method, your domain automatically inherits changes to the
  Google IP addresses as they happen.

http://support.google.com/a/bin/answer.py?hl=en&answer=60764
Comment: Actually, that is to prevent his own messages, sent via google's server but with his own domain, to be classified as spam.


What does "PCA (Principal Component Analysis) spheres the data" mean?

Question: I was reading some notes and it says that PCA can "sphere the data". What they define to me as "sphering the data" is dividing each dimension by the square root of the corresponding eigenvalue.
I am assuming that by "dimension" they mean each basis vector into which we are projecting (i.e. the eigenvectors we are projecting to). Thus I guess they are doing:
$$ u^{'}_i= \frac{u_i}{\sqrt{eigenValue(u_i)}}$$
where $u_i$ is one of the eigenvectors (i.e. one of the principal components). Then with that new vector, I am assuming they are projecting the raw data we have, say $x^{(i)}$ to $z^{(i)}$. So the projected points would now be:
$$ z'^{(i)} = u^{'}_i \cdot x^{(i)}$$
They claim that doing this ensures that all the features have the same variance.
However, I am not even sure if my interpretation of what they mean by sphering is correct and wanted to check if it was. Also, even if it was correct, what is the point of doing something like this? I know they claim it makes sure everyone has the same variance but, why would we want to do this and how does it achieve this?
Comment: What you say is right. `u` is eigenvectors's value and is related to raw PC values. `u'` is called a loading and is related to the normalized (equal variances) PC values. You may want read my answer about it: http://stats.stackexchange.com/a/35653/3277.
Comment: In other words, you may compute raw PC values and then to standardize them to equal (unit) variance. Or, to get the same result, you may first calculate loadings and then compute PC values with their help.
Comment: Related thread: [Principal component analysis and variance normalization](http://stats.stackexchange.com/questions/95806/principal-component-analysis-and-variance-normalization).
Comment: For what it's worth most people would not consider this use of 'sphere' as a verb to be very good English style, even if it is comprehensible.
Answer: Your understanding is right. Have a look at this figure which represents various possibilities of your data points: http://shapeofdata.files.wordpress.com/2013/02/pca22.png
They look ellipsoidal. If you do what you've described above i.e. compress the points in the direction in which they are spread the most (approx the 45 degree line in the image), the points will be lying in a circle (sphere in higher dimensions).
One reason you spherify the data is while doing prediction and understanding which coordinates are important. Say you wish to predict $y$ using $x_1$ and $x_2$, and you get coefficient values $\beta_1$ and $\beta_2$ i.e. $y\sim \beta_1 x_1+\beta_2x_2 $. Now if $x_1$ and $x_2$ have the same variance, i.e. they are roughly distributed spherically, and you find that $\beta_1=1$ while $\beta_2=10$, you can interpret this has saying that $x_2$ influences $y$ more than $x_1$. If their scales were not the same however, and $x_1$ was distributed 10 times more than $x_2$, then you would get the above values of $\beta_1$ and $\beta_2$ even if they both influenced $y$ roughly the same. To summarize, you "spherify" or "normalize" to make inferences about the variable's importance from its coefficient.


Is any Python type whose objects contain elements that are numbered called a sequence type?

Question: I've been confused about that question for a long time. Is any Python type whose objects contain elements that are numbered called a sequence type?
Comment: https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange should answer your question. Everything that has sequence-like behavior (as following the specified protocol) is a sequence type. If it looks like a sequence, it's a sequence. Hello Duck Typing
Comment: https://docs.python.org/2/reference/datamodel.html#emulating-container-types
Answer: A sequence is a type that follows the sequence protocol. That implies not just that indices are numeric, but that they are consecutive, start at zero, and iterating yields elements in order of increasing index, and that len(my_sequence) works. In practice, this means they need to implement __getitem__ and __len__ methods appropriately. From there, Python can "fill in the blanks" so that iteration, x in my_sequence and reversed(my_sequence) all work without implementing the associated methods - but they might still choose to implement those, particularly if they can provide a more efficient implementation (for example, the default iteration behaviour is as if __iter__ just tried self[i] from i=0 until it hits an IndexError, which isn't ideal for a linked list).
Comment: And they have a length. `__len__` and `__getitem__` both must be implemented.
Answer: Sequences in python are Containers (i.e. they have a __contains__ method), are Iterable (i.e. they have a __iter__ method) and are Sized (i.e. they have a __len__ method).  They also have the following methods:
__getitem__
__reversed__
index
count

these are your basic immutable sequences, to be mutable they'll also have the following methods:
__setitem__
__delitem__
insert
append
reverse
extend
pop
remove
__iadd__

Comment: You don't actually need `__contains__` or `__iter__` - an `__getitem__` that accepts sequence-like indices and eventually raises an exception is enough. `__reversed__` is also optional (`reversed` can use `__getitem__` and `__len__`). `index` and `count` are provided by the built-in sequences, but they aren't required (and, eg, numpy arrays don't provide them).
Comment: Thanks a lot! I understand
Comment: @lvc that's very enlightening, thanks.  What are sequence-like indices?  I assume they must have `__add__`, `__neg__`, `__cmp__` (and I guess `__mul__` for extended slices or can they get by with just addition?)  Anything else (or less)?
Comment: Sequence like indices are the ints in `range(len(mysequence))`. The default itertion behaviour does effectively `for i on it.count(0): yield mysequence[i]`, stopping when one of them is an error. Reverse iteration uses a similar strategy except it starts at the end (so it needs `len(mysequence)` to work) and decerements until 0. I believe it carefully avoids making assumptions about whether negative indices will work.


Tipos de dados incompatíveis ao chamar procedure

Question: Estou com problemas em chamar a procedure seguinte no meu form:
procedure TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string);
begin
  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      sender.AsInteger := 1
    else if Text = 'Linha 2' then
      Sender.AsInteger := 2
  end;
end;

No botão salvar:
procedure TForm.salvar(Sender: TObject);
var
 ValorLinha : Integer;
begin
 ValorLinha := DM_Maquinas.IBDSMaquinasCOD_LINHASetText(DBComboBox2.Field, 'Linha 1'); //erro
end;

Estou com erro na linha a cima:

E2010 Incompatible types: 'Integer' and 'procedure, untyped pointer
  or untyped parameter'

Se mudarmos o tipo da variável ValorLinha para String o erro persiste.
Comment: Uma procedure não retorna valor e você esta tentando atribuir o retorno à variavel ValorLinha. Você pode transformar a procedure em function e retorna valor ou rever sua lógica.
Answer: Exatamente como informado no comentário, você precisa de uma função para retornar o valor desejado, ou alimentar uma variável no procedimento!
Função:
function TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string): Integer;
begin
  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      Result := 1
    else if Text = 'Linha 2' then
      Result := 2
  end;
end;

Ou modificando o procedimento para alimentar uma variável externa:
procedure TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string);
begin
  _VariavelExterna := 0;

  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      _VariavelExterna := 1
    else if Text = 'Linha 2' then
      _VariavelExterna := 2
  end;
end;

No botão salvar:
procedure TForm.salvar(Sender: TObject);
var
  ValorLinha : Integer;
begin
  DM_Maquinas.IBDSMaquinasCOD_LINHASetText(DBComboBox2.Field, 'Linha 1');
  ValorLinha := _VariavelExterna;
end;

Para todos os casos a melhor opção e correta é a função!
Answer: Você poderia criar mais um parâmetro na procedure, para alimentar a variável.
Exemplo:
procedure TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string; aValorLinha: Integer);
begin
  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      sender.AsInteger := 1
    else if Text = 'Linha 2' then
      Sender.AsInteger := 2;
    aValorLinha := Sender.AsInteger;
  end;
end;

No botão Salvar:
procedure TForm.salvar(Sender: TObject);
var
 ValorLinha : Integer;
begin
  DM_Maquinas.IBDSMaquinasCOD_LINHASetText(DBComboBox2.Field, 'Linha 1', ValorLinha);
end;


How to get the length of a non list?

Question: Fixed it with:
Dictionary<string, Dictionary<string, object>> saveState = new Dictionary<string, Dictionary<string, object>>();

Don't mind this part:
I have some data I want to save to the player which I've done.
This data contains levels which the player needs to read which it can but when I'm creating UI elements for the levels I don't want to do a bunch of functions, I want to make it a lot easier so I can just call a function which iterates the levels and then creates a certain amount of frames depending on how many levels.
I want to count how many levels there are so I can "automate" this frame creation process and I need to get the levels data (if you've completed it and etc.)
Inside PlayerData = new SetupData I have a line which goes Levels = new Levels and inside that one I have two classes, objects whatever Level1 = new Level, and one Level2 = new Level I want to count how many of those there are with script.
If I were to add 5 more of the Level2 = new Level but level3, level4 etc. I want the computer to know how many of those there are inside of the Levels = new Levels
Basically:
Levels {

    Level1 = {Completed = true},
Level2 = {Completed = true},
Level3 = {Completed = true},

}

Count script:
Levels.Length // -- prints there are 3 levels.

This is just the players data:
public static SaveManager Instance { set; get; }
public SetupData state;

public object PlayerData;

PlayerData = new SetupData
    {
        // Level Data
        Levels = new Levels
        {
            Level1 = new Level
            {
                Name = "First Level",
                Progress = 0,
                Completed = false
            },
            Level2 = new Level
            {
                Name = "Second Level",
                Progress = 0,
                Completed = false
            },
        },
        // Character Data
        Player = new Player
        {
            SelectedColor = 0,
            Berries = 0
        }
    };

The problem is that this isn't a list or anything so I can't use .Length
SaveState script:
[Serializable]
public class Level
{
    public string Name;
    public int Progress;
    public bool Completed;
}

[Serializable]
public class Levels
{
    public Level Level1;
    public Level Level2;
}

[Serializable]
public class Player
{
    public int SelectedColor;
    public int Berries;
}

[Serializable]
public class SetupData
{
    public Levels Levels;
    public Player Player;
}

Comment: "This isn't a list or anything"? Then you need to turn it into a list or something.
Comment: What is the type of `Levels`? If it's an array or List to hold the levels you can easily get the Count or Length of it
Comment: Ok based on your code so far you know there will always be two levels, because you only added properties for two levels. There's not to count, and you have no need  to count because you already know the answer even before you compile the code. As others mention, if you want to allow a varied number of levels, and then count them, you need a list to contain the Level objects instead of having a static property for each level.
Comment: If you solved your own problem, put the answer in the Answer box below. Do not change your question. Also explain how the code solves your problem, because that is not at all clear to me.
Comment: Not sure what You are trying to count here , you are already presetting 2 levels per player, I see no list.
May be you wanna do a null check on one of the levels ? instead of counting
Comment: The question is still completely unclear I'm afraid. What are you trying to count?
Comment: Why do you have `Level1`, `Level2` etc. properties, just have one property of type `List` where you can get a count instead of having to use reflection as per Eric's answer?
Comment: The fact that you're getting so much confusion from this question is because the operation you're describing, whatever it is, is not one that we normally do in C#. If your intention is that there can be a varying number of levels then, as David and others have indicated, normally you'd say `List` and not `Level1`, `Level2`, and so on.
Comment: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.7.2, https://www.dotnetperls.com/list are good starting points. The nice thing about a List is you can make a list of any type. So in your case `public class SetupData
{
    public List Levels;
    public Player Player;
}` would be a sensible structure. And you can get rid of the `Levels` class entirely. Just keep `SetupData` and `Level` (and `Player` obviously, that's not relevant to this)
Comment: Is `Levels` actually a type? Or should that be `Levels = new List`?
Comment: I added the savestate script
Comment: I once again edited the question.
Comment: Is your question "Given a type, how many fields of that type are of type `Level`?"
Comment: I'll read about this List thing
Answer: It is very hard to tell from this question what you are asking; please try to clarify the question.
My best guess is that you are asking "how can I programmatically count the number of fields of type Levels that are of type Level?"  If that's not your question, please clarify.
You do that like this:
using System;
using System.Linq;

class Level { }
class Levels
{
    public Level level1;
    public Level level2;
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(
          typeof(Levels)
            .GetFields()
            .Count(f => f.FieldType == typeof(Level)));
    }
}

How to get the length of a non list?


Convergence of integral $\int_{0}^{\pi/2}\tan(x)\, dx$

Question: Problem
Is following integral convergent ?
$$ \int_{0}^{\pi/2}\tan(x)\,dx $$
Attempt to solve
We can solve first indefinite integral of $\tan(x)$
$$\int \tan(x)\,dx=-\ln(\cos(x))$$
Now we can calculate from 0 to $\pi/2$
$$ \int_{0}^{\pi/2}\tan(x)\,dx=-\ln(\cos(\frac{\pi}{2}))-(-\ln(\cos(0))$$
$$\approx 3.044343016\cdot 10^{-4}$$
I can get a tiny number for area from 0 to $\pi/2$. Now if you take a look at graph of $\tan(x)$ from 0 to $\pi/2$ you can see that when $x \rightarrow \pi/2$ y goes to $+\infty$ ? Now i doubt that my calculated value for the area is correct since area should be infinity too ? since area increases when y increases.
Comment: Did you put in $(\pi/2)°$ instead of $(\pi/2)$ into cosine? Blindly entered into calculator, which is accidentally set to degrees? That shows the danger of using a calculator for values where you know the answer analytically.
Comment: the thing is $\ln(\cos(\frac{\pi}{2}))$ is not defined. It tends to $-\infty$. So your calculations are write up to the last part. I don't know how you got the last part.))
Comment: @orion i can confirm this is the reason why the last part is incorrect.
Comment: @orion, when I use degrees instead of radians, I get $-\ln(\cos((\pi/2)^\circ))=0.00037585376$, not $0.0003044343016$.
Comment: Oh gosh, I think I figured it out:  The OP's calculator is using **gradians** (see https://en.wikipedia.org/wiki/Gradian).  A right angle, $\pi/2$ radians, is $100$ gradians, and $-\ln(\cos((\pi/2) grad))=-\ln(\cos(\pi^2/400))=0.0003044343$.
Comment: @BarryCipra i can also confirm this that unit that my calculator was set was gradians indeed.
Answer: The function $\tan(x)$ behaves as $1/x$ around the pole (technically, $1/(\pi/2-x)$, but the important thing is the asymptotic power law behaviour and you can always change variables). By knowing that integral of $1/x$ diverges, the integral of $\tan x$ will diverge too.
I don't know how you got your last number, but $\log \cos\frac{\pi}{2}=\log 0$ evidently diverges.
Answer: I would even say that the problem you want to solve does not exist, as $\tan x$ is not defined for $x=\frac{\pi}{2}$.


Umbraco 5: site search

Question: Is there a viable way to search an Umbraco 5 site? I've read a lot on XLST search, but nothing using MVC3. It also seems that Examine is coming a little bit buggy, as even the backoffice has lost the search box that was present in v4. Any ideas?
Comment: I was actually working on a little something last night; its not going to be perfect (not Google) but a decent start. Watch this space, as I'll try to make a package out of it soon.
Comment: Great, I'll keep an eye!
Comment: Unfortunately package support stumped progress for me initially, but now that U5 has been officially abandoned that's an even bigger hurdle. I might still do what I was going to do but for 4.7.x.
Answer: As you know Umbraco V5 is retire; you can try 4.x and do the above with user controls that do search logic using umbraco node factory.
Hope you get my views.
Answer: I've created a very basic search, it might not be best way but it gives the results I need.
var results = Hive.QueryContent().OfRevisionType(FixedStatusTypes.Published).ToList().Where(c => c.AllAncestorIds().Any() && c.Name.ToLowerInvariant().Contains(query.ToLowerInvariant()) && c.Attribute<bool>("excludeFromSearch") == false).ToList();

OfRevisionType(FixedStatusTypes.Published) returns published pages
c.AllAncestorIds().Any() stops deleted items being returned
Comment: And how do you feed the query to Hive? Also, how would you render the list in a view? Just @results?

Umbraco 5: site search


sets with sum of 3 digit

Question:
How many distinct subsets of the set $S=\{1,8,9,39,52,91\}$ have three-digit sums?

I know we have $64$ total subsets, but I don't think that helps us in this question ... does it?
Comment: You can calculate the number of subsets with sum less than 100 (i.e. not three digit sum) and subtract from 64.
Comment: There are 32 subsets containing 91, and they all work, with three exceptions. Subsets not containing 91 must contain both 52 and 39, and then you can work out the possibilities for the other elements to make the sum have 3 digits.
Comment: Since there are only 64 cases to check, it's doable on pen and paper. But if there were much more numbers, the problem becomes more interesting!
Answer: The rationale behind the selection is ${91,52,39,9,(8,1)} = {a1,a2,a3,a4,a5}$ The way I have grouped from the second element to the last element (i.e from a2 to a5) when added alone or a combination thereof will have a distinct set with sum >=100. The number of ways are $4\left({3\choose1}+{3\choose2}+{3\choose3}\right)+1 = 29$. Further${(52,39),9,(8,1)} = {b1,b2,b3}$.  The way I have grouped the second element to the last element(i.e from b2 to b3) when added alone or a combination thereof will have a distinct set with sum >=100.  The number of such sets is $2\left({2\choose1}\right)+1=5$.  Thus the total number of distinct sets where the sum of their elements  is a three digit  = $34$

sets with sum of 3 digit


Send dictionary with socket.send and str.encode()

Question: I'm trying to send an dictionary with socket.send but this function takes binary string, i tried to do:
test = {"key":"value", "key2":"value2"}
test = str(test).encode()
test.send()

The server have just to do:
dict = client.recv(1024)
dict = dict(dict.decode())

But when i try to get the dictionary from an string i get this error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Answer: First of all, you have shadowed the builtin dict type by binding name dict to client.recv, which you must not do.
Now, the dict() constructor does not take a string as argument. You can use ast.literal_eval instead:
In [25]: d = '{1: 2, 3: 4}'

In [26]: import ast

In [27]: ast.literal_eval(d)
Out[27]: {1: 2, 3: 4}

Comment: Think what happens if somebody figures out how to send `import os;os.system('rm -rf /')` to your socket, though. Maybe look at `pickle` and friends for a safer alternative. JSON would also work.


How can I get StackPanel to use an ItemTemplate?

Question: In the following code, I tell the ComboBox to use the DataTemplate called CustomerTemplate by assigning its ItemTemplate attribute.
StackPanel, however, doesn't have an ItemTemplate attribute.
How can I get the StackPanel to also use CustomerTemplate?
<Window.Resources>
    <DataTemplate x:Key="CustomerTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}"/>
            <TextBlock Text=" "/>
            <TextBlock Text="{Binding LastName}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<DockPanel LastChildFill="False" Margin="10">
    <ComboBox
        x:Name="CustomerList"
        ItemTemplate="{StaticResource CustomerTemplate}"
        HorizontalAlignment="Left"
        DockPanel.Dock="Top"
        Width="200"
        SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
        ItemsSource="{Binding Customers}"/>

    <StackPanel DataContext="{Binding SelectedCustomer}" Orientation="Horizontal">
        <TextBlock Text="Chosen: "/>
        <TextBlock Text="{Binding LastName}"/>
    </StackPanel>

</DockPanel>

Answer: ItemsControl is essentially a StackPanel with an ItemTemplate. It uses a StackPanel internally.
However, it looks like you're trying to display a single customer rather than a list of them (I sound like Clippy, don't I?). In that case you want to use a ContentControl:
<ContentControl
    Content="{Binding SelectedCustomer}"
    ContentTemplate="{StaticResource CustomerTemplate}" />

Comment: perfect, another useful control crawled out of the woodwork, thanks
Comment: "It looks like you're trying to write an upvote-worthy answer"


Getting xml response from ebay api

Question: I have created code to get the response from ebay. I tested using sandbox in ebay, which gives correct result.
but here in localhost example it does not give response:
For below code when I do:
$xmlResponse = simplexml_load_string($response);
var_dump($xmlResponse);

it returns : false;
any idea what can be wrong here?
code:
require_once 'tradingConstants.php';
//DEFINE("API_URL",'https://api.sandbox.ebay.com/ws/api.dll');

// check if posted

    // grab our posted keywords and call helper function
    // TODO: check if need urlencode
    $title = $_POST['title'];
    $categoryID = $_POST['categoryID'];
    $startPrice = $_POST['startPrice'];
    $pictureURL = $_POST['pictureURL'];
    $description = $_POST['description'];

    // call the getAddItem function to make AddItem call
  $response = getAddItem($title, $categoryID, $startPrice, $pictureURL, $description);
// Function to call the Trading API AddItem

function getAddItem($addTitle, $addCatID, $addSPrice, $addPicture, $addDesc) {

    /* Sample XML Request Block for minimum AddItem request
    see ... for sample XML block given length*/

    // Create unique id for adding item to prevent duplicate adds
    $uuid = md5(uniqid());

    // create the XML request
    $xmlRequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    $xmlRequest .= "<AddItemRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">";
    $xmlRequest .= "<ErrorLanguage>en_US</ErrorLanguage>";
  $xmlRequest .= "<WarningLevel>High</WarningLevel>";
  $xmlRequest .= "<Item>";
  $xmlRequest .= "<Title>" . $addTitle . "</Title>";
  $xmlRequest .= "<Description>" . $addDesc . "</Description>";
  $xmlRequest .= "<PrimaryCategory>";
  $xmlRequest .= "<CategoryID>" . $addCatID . "</CategoryID>";
  $xmlRequest .= "</PrimaryCategory>";
  $xmlRequest .= "<StartPrice>" . $addSPrice . "</StartPrice>";
  $xmlRequest .= "<ConditionID>1000</ConditionID>";
  $xmlRequest .= "<CategoryMappingAllowed>true</CategoryMappingAllowed>";
  $xmlRequest .= "<Country>US</Country>";
  $xmlRequest .= "<Currency>USD</Currency>";
  $xmlRequest .= "<DispatchTimeMax>3</DispatchTimeMax>";
  $xmlRequest .= "<ListingDuration>Days_7</ListingDuration>";
  $xmlRequest .= "<ListingType>Chinese</ListingType>";
  $xmlRequest .= "<PaymentMethods>PayPal</PaymentMethods>";
  $xmlRequest .= "<PayPalEmailAddress>firstname.lastname@example.com</PayPalEmailAddress>";
  $xmlRequest .= "<PictureDetails>";
  $xmlRequest .= "<PictureURL>" . $addPicture . "</PictureURL>";
  $xmlRequest .= "</PictureDetails>";
  $xmlRequest .= "<PostalCode>05485</PostalCode>";
  $xmlRequest .= "<Quantity>1</Quantity>";
  $xmlRequest .= "<ReturnPolicy>";
  $xmlRequest .= "<ReturnsAcceptedOption>ReturnsAccepted</ReturnsAcceptedOption>";
  $xmlRequest .= "<RefundOption>MoneyBack</RefundOption>";
  $xmlRequest .= "<ReturnsWithinOption>Days_30</ReturnsWithinOption>";
  $xmlRequest .= "<Description>" . $addDesc . "</Description>";
  $xmlRequest .= "<ShippingCostPaidByOption>Buyer</ShippingCostPaidByOption>";
  $xmlRequest .= "</ReturnPolicy>";
  $xmlRequest .= "<ShippingDetails>";
  $xmlRequest .= "<ShippingType>Flat</ShippingType>";
  $xmlRequest .= "<ShippingServiceOptions>";
    $xmlRequest .= "<ShippingServicePriority>1</ShippingServicePriority>";
  $xmlRequest .= "<ShippingService>USPSMedia</ShippingService>";
  $xmlRequest .= "<ShippingServiceCost>2.50</ShippingServiceCost>";
  $xmlRequest .= "</ShippingServiceOptions>";
  $xmlRequest .= "</ShippingDetails>";
  $xmlRequest .= "<Site>US</Site>";
  $xmlRequest .= "<UUID>" . $uuid . "</UUID>";
  $xmlRequest .= "</Item>";
  $xmlRequest .= "<RequesterCredentials>";
  $xmlRequest .= "<eBayAuthToken>" . AUTH_TOKEN . "</eBayAuthToken>";
  $xmlRequest .= "</RequesterCredentials>";
  $xmlRequest .= "<WarningLevel>High</WarningLevel>";
    $xmlRequest .= "</AddItemRequest>";

    // define our header array for the Trading API call
    // notice different headers from shopping API and SITE_ID changes to SITEID
    $headers = array(
        /*'X-EBAY-API-SITEID:'.SITEID,
        'X-EBAY-API-CALL-NAME:addItem',
        'X-EBAY-API-REQUEST-ENCODING:XML',
        'X-EBAY-API-COMPATIBILITY-LEVEL:' . API_COMPATIBILITY_LEVEL,
        'X-EBAY-API-DEV-NAME:' . API_DEV_NAME,
        'X-EBAY-API-APP-NAME:' . API_APP_NAME,
        'X-EBAY-API-CERT-NAME:' . API_CERT_NAME,*/

        'X-EBAY-API-APP-ID:Startupb1-efb9-43ca-a0e8-473753fe9ad,
        X-EBAY-API-VERSION:863,
        X-EBAY-API-SITE-ID:203,
        X-EBAY-API-CALL-NAME:AddItem,
        X-EBAY-API-REQUEST-ENCODING:XML,
        Content-Type: text/xml;charset=utf-8'
    );
    $API_URL = 'https://api.sandbox.ebay.com/ws/api.dll';
    // initialize our curl session
    $session  = curl_init();
    curl_setopt($session, CURLOPT_URL, $API_URL);
    // set our curl options with the XML request
    curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($session, CURLOPT_POST, true);
    curl_setopt($session, CURLOPT_POSTFIELDS, $xmlRequest);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

    // execute the curl request
    $responseXML = curl_exec($session);

    // close the curl session
    curl_close($session);
    //echo $addTitle;
    // return the response XML
    return $responseXML;
}

Answer: simplexml_load_string returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or FALSE on failure.
You will need to find out why getAddItem dies not return a valid xml

Getting xml response from ebay api


Form is not being rendered in template file

Question: I have tried drupal_render,drupal_get_form etc for rendering the form,but the form is not being rendered. Is there any error in code or else what else should i add to the code so that it works.
function questionnaire_template_form($form, &$form_state, $question) {
 print_r("in template function");

 $form_build = unserialize($question->criteria_data);

 foreach ($form_build as $key => $value) {

  $options = ($form_build[$key]['1']);
   $list = explode("\n", $options);

   $list = array_map('trim', $list);

   $list = array_filter($list, 'strlen');

   foreach ($list as $key => $value) {

    $new = explode('|',$value);
    $new_key = reset($new);
    $new_value = end($new);
    $new_list = array($new_key => $new_value);
    dsm($new_list);
   }
dsm('next');

   $fb = explode("_",$key);
   $type =reset($fb);

  if($type == 'radio') {

    if($form_build[$key]['0']) {
      $form['radio_form'] = array(
        '#type' => 'radios',
        '#options' => $list,
      );
    }
  }
   elseif($type == 'checkbox') {
    if($form_build[$key]['0']) {
     $form['checkbox_form'] = array(
       '#type' => 'checkboxes',
       '#options' => $list,
      );
    }
   }
   elseif($type == 'selectlist') {
    if($form_build[$key]['0']) {
      $form['selectlist_form'] = array(
        '#type' => 'select',
        '#options' => $list,
        );
   }
  }

}
return $form;
}

Above code is my form.

<?php
//print_r($variables['entity']->qid);?>
<?php
print_r($variables['entity']->title);?>
<?php
print_r($variables['entity']->text);?>
<?php
?>
<?php
?>
<?php
if($variables['entity']->criteria) {
  ?>
<?php
  $form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
  print(drupal_render($form_template));

}
?>
<?php

print_r(l( t("Yes"), 'questionnaire/' . $variables['entity']->yes_quid));?>
<?php
print_r(l( t("No"), 'questionnaire/' . $variables['entity']->no_quid));?>
<?php

?>

And this is the template where I am rendering the form.
I am getting the form if I dsm the form
Comment: Why do you not creating custom module for the same?
Comment: This is custom module
Comment: I ma not seeing anywhere, did you miss printing the rendered form?
Comment: $form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
  drupal_render($form_template);
Comment: Are you attaching form with menu item or displaying in block and are you creating template for form or custom template?
Answer: Drupal render will return the html
drupal_render(drupal_get_form('form_id'));

you have to print the returned html as well.
print drupal_render(drupal_get_form('form_id'));

in your case
$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
drupal_render($form_template);

change it to
$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
print drupal_render($form_template);

Comment: I updated the code in question.Tried with print drupal_render($form_template);      This too not working
Comment: different approach, check if this [link](http://drupal.stackexchange.com/questions/22815/best-way-to-render-a-form-on-a-node) helps you


Switched exchange servers, kept the same e-mail but some incoming mail is still going to the old server

Question: I recently switched from an axoim exchange mail server to microsoft 365 exchange server. Now my email address is still the exact same as it was, and most of the incoming mail comes to my new server and address, but it looks like some incoming mail is still going to the old server. Why is that and what can i do to address it?
Answer: I'm assuming that you changed the MX records for your domain, so that they now point to Microsoft 365's mail servers, correct?  If so, it may take a day or two for the DNS changes to propagate.


Will iOS apps that are just UIWebView's be rejected?

Question: Are apps that are simply UIWebViews (or the Phonegap equivalent) that point at a remote URL subject to rejection from the App store based on that fact alone?
If not outright, what mistakes are easy to make in such a situation that could cause an app to be rejected?
Comment: Ask Apple. We cannot guarantee that they will reject or deny an app.
Comment: I've seen such an app (by a big bank) rejected on the grounds that it doesn't offer anything substantial compared to the plain website in the browser.
Comment: This question is more appropriate for [the App Stores proposal on Area 51](http://area51.stackexchange.com/proposals/30702/app-stores).
Comment: I don't think apple will answer that. Just ask yourself reasonably if your usage is appropriate.
Comment: @hop Would that be a WebUIView app or an actual Objective-C app?
Answer: As per section 4.2 of the App Store Review Guidelines, yes, this kind of app will be rejected.

4.2 Minimum Functionality
  Your app should include features, content, and UI that elevate it beyond a repackaged website. If your app is not particularly useful, unique, or "app-like," it doesn't belong on the App Store. If your App doesn't provide some sort of lasting entertainment value, it may not be accepted.
Answer: @Moshe is correct with pointing out what they SAY, but what they do is a completely different story as we all know. I think it depends on the reviewer that you get, and the mood they are in! Take a look at this example.
KSL app is just their mobile website wrapped in a Web view with a back and forward button, and its in the store.
Their mobile site: http://m.ksl.com/
Their App Link: http://itunes.apple.com/us/app/ksl.com/id363278608?mt=8
Update: KSL now has an updated app, which is an actual app... so my example no longer pertains to them.
Comment: This app still is https://itunes.apple.com/us/app/arc-heitinga-toernooi/id961449214?mt=8


Uniqueness of a 2nd order differential equation

Question: Consider a second order differential equation of the form
$y''(x)+f(x)y'(x)+j(x)y(x)=g(x)$
on the interval $[0,\infty)$, where $f,j$ and $g$ are continuous functions. Are the conditions $y(0)=y_0$ and $\lim_{x \to \infty} y'(x)=c$ with $c$ being some constant enough to ensure the existence of a unique solution?
Answer: No, for example, the functions on the form
$$
y(x)=C_1\exp(-x)+C_2\exp(-2x)+1
$$
all satisfy
$$
y''(x)+3y'(x)+2y(x)=2
$$
and
$$
\lim_{x\to+\infty}y'(x)=0.
$$
However,
$$
y_0=y(0)=C_1+C_2+1,
$$
So any values of $C_1$ and $C_2$ satisfying $C_1+C_2=y_0-1$ will give you a solution.
Comment: Indeed, many thanks!


Before we consider the prime decomposition

Question: Let $L/K$ be a number field extension. Let $I$ be a prime ideal of $O_K$. How to prove that $IO_L\neq O_L$?
It looks there should be a very fast way to see this, but I don't know how.
Comment: This should have been asked in math.stackexchange. If $\sum a_ib_i =1$ with $a_i \in I, b_i \in O_L$, choose a $O_K$-basis for $O_L$ containing $1$ and express the $b_i$ in term of the basis.
Comment: OK,do you mean that $O_L$ is a free $O_K$-modular with a basis containing 1? If yes, how to prove that? I know both of them are free $\mathbb{Z}$ module.
Answer: One method to prove $IO_L\neq O_L$: Consider the localization $O_{L,I}=\{a/b:a\in L,b\in O_K-I\}$, $O_{K,I}=\{a/b:a\in K,b\in O_K-I\}$. First one proves that $O_{K,I}$ is a PID. Then by an argument similar to the proof that $O_K$ is a free $\mathbb{Z}$ module, we can prove that $O_{L,I}$ is a free $O_{K,I}$ module: $O_{L,I}=O_{K,I}\alpha_1\oplus \dotsm \oplus O_{K,I}\alpha_n$.  Now $IO_L=O_L$ is equivalent to $IO_{L,I}=O_{L,I}$ which implies $IO_{K,I}=O_{K,I}$, because $IO_{L,I}=IO_{K,I}\alpha_1\oplus \dotsm \oplus IO_{K,I}\alpha_n$. But $IO_{K,I}=O_{K,I}$ is the same as $IO_K=O_K$. Done.


Don't understand the algebra at the end of this inductive proof.

Question: So, can anyone explain the algebra at the end of this inductive proof?

I am confused in how they are getting line 1 to line 2 and then also how they get from line 2 to line 3.
Comment: It seems that the base of the logarithm is $2$. What are they proving?
Comment: Let me add the entire proof.
Answer: I'm assuming the base of the logarithm is $2$, since otherwise this proof is false. I'm going to do the steps with more intermediate detail:
$$2\left(2^k\log_2\left(2^k\right)\right)+2^{k+1}$$
$$2^{k+1}\log_2\left(2^k\right)+2^{k+1}$$
$$2^{k+1}\left(\log_2\left(2^k\right)+1\right)$$
$$2^{k+1}\left(\log_2\left(2^k\right)+\log_2(2)\right)$$
Using the fact that $\log_a(b)+\log_a(c) = \log_a(bc)$:
$$2^{k+1}\cdot\log_2\left(2^{k+1}\right)$$
Comment: Thanks!  I am not sure I ever would have thought of that on my own.  Oh well, I don't really have a lot of experience doing the algebraic manipulations that these proofs require.  The overall structure of these inductive proofs make a lot of sense to me but I just find the algebra required to be so hard! :(
Comment: @timbram The only good way to get better at this is practice. Look exactly at what you're trying to achieve. Try to factor things out. Try to use properties of the functions in question (e.g. the property of $\log$ that I used). Practice this and I have no doubt that you'll get better.
Comment: Thanks for the encouragement!  Just out of curiosity, do a lot of people new to proofs have trouble with the algebra?
Comment: @timbram I'm not sure, but I can't imagine it's that uncommon. How removed are you from your most recent algebra class?
Comment: About 10 years actually.
Comment: @timbram Ok. I imagine it's just lack of practice with algebraic expressions. Just keep working on them and you'll get better in no time!
Comment: @timbram By the way, $\log_2\left(2^{k+1}\right)=k+1$.


How does Ed O'Brien (Radiohead) get his guitar to sound like a synth?

Question: Ed O'Brien frequently plays parts on his guitar that sound like a synth, despite not having a synth in his signal path.
I know that he's used an E-bow in the past and that he uses a sustainer guitar for some of these effects but I've watched videos of him playing with guitars that don't have infinite sustain features, so a substantial part of his sound must be coming from his pedal board. However, outside of a Digitech Whammy Pedal, there are no obvious synth imitators except for having multiple delay pedals.
When Ed plays live, he doesn't have the benefit of post-production but live he does stack his delays. I'm interested in the specifics of that.
How does Ed use multiple delay/looper pedals to get synth pads?
Comment: Not a guitarist, but as someone watching friends try to sound like The Edge, I feel like enough delay eventually does the trick. Especially tape delay. I had a friend who added the Voodoo Labs Sparkle Drive to that chain (probably with the treble turned up?) and the result was magical.
Comment: Not an answer, but I use a Boss SY-1 which acts like a synth, producing many synth and other sounds. Started with SY-5, but the response time was way too slow.
Answer: Looks like it's not only pedals but also production techniques. About his solo album he said:

Every part that sounds like a synth is multi-tracked sustainer guitars, like the string-section of an orchestra. Even the deeper bass notes, is a Spanish guitar played in a way that sounds more like a sequencer.

That means part of the sound quality he gets comes from recording layers of single note parts that each sounds a bit like a mono synth and having them stack up to an "orchestra" type of sound.
There are two main components at work for his raw guitar tone: the sustainer system and the pedals. Using an ebow or sustainer does a lot to change the timbre of the guitar because it allows the guitarist to change the transients and envelope of the sound. It can be very hard to recognize a sound as a guitar when the initial picking noise transients and the normal attack/decay of the sound is removed. On top of that, a whammy pedal messes with the raw tone a bit, especially when the pitches are shifted by larger intervals. At in the memory man that he says he has on almost all the time, and the chorus and delay effects complete the change from clearly a guitar sound to what seems like a synth.
If you just have distortion, delay, and reverb on a guitar and simply roll off the volume, pluck a note, and roll the volume back up, you get a sound that might still be clearly a guitar but also could be something else. The sustainer and effects just enhance that to a great degree.
Comment: When you say 'whammy pedal', do you mean wah pedal?
Comment: When Ed plays live, he doesn't have the benefit of post-production but live he does stack his delays. I'm interested in the specifics of that.
Comment: @Tim No, I mean [Whammy pedal](https://digitech.com/dp/whammy/).
Comment: @empty Do you know how looping works? Combined with near-infinite delay and a standard delay and a sustainer circuit you can do almost anything.
Comment: @ToddWilcox - ah, well, something else to spend my ill-gotten funds on...


Building strace for an older Linux system that does not have a build environment

Question: I have a bit of a problem.  I need to use the strace utility to figure out why a command is crashing on an older Linux system.  Unfortunately, I don't have strace nor do I have gcc/binutils on that system.
I tried building the app statically on a current Debian system, but calls to getpwnam require a dynamic load of the version of libc that was used at compile time.  That would be fine, but being that the utilities on the older system were all built using an ancient version of libc, putting a newer libc on that system breaks everything else.
Short of downloading and installing an old distribution of Linux and then doing the build, is there an easier way around this problem?  The original distribution on this system is currently unknown and the more I research it, it's getting to seem like a huge chicken vs egg problem.  Any tips would be much appreciated.
Comment: Just to follow up on my query, I ultimately took an educated guess as to what distribution it was, then had to work backwards through the releases until I had a system with the same version of libc.  Once I did that, I could compile the utility I needed (strace).
Answer: Using an outdated Linux system is never wise... can it be upgraded? If not, why not? What is failing, and how? Any chance of updating that?
There should be a file named /etc/release or similar, that should give you an idea of the distribution and version. Or uname -a might give a clue on the distribution. If it doesn't work, try to see if commands like rpm, apt-get, or one of the other package management commands are available, that will narrow down the distribution. A Google search for some of the installed packages with versions might help narrow down the version of the distribution.
Knowing distribution and version you may be able to get strace (and perhaps other needed packages). Many distributions keep archival  versions (at least of the original installation media for old versions) around.
Comment: I would normally agree with you, but this is a vendor supplied, embedded system and I can't make the alterations you suggest.  My only choice here is to set up a build environment that can create a utility that runs on the target system.
Comment: Any chance of contacting the vendor for details? Under the GPL you are entitled to full source, so they should have at least that available. That would be a starting point, most embedded systems use idiosyncratic setups that aren't easy to assimilate to "normal" distributions.
Comment: The vendor isn't going to help me.  They're the paranoid type.  Thanks for the help, but I need a build environment - that's the only solution I've found so far.


Problemas ao utilizar o Query Builder no Laravel

Question: Tenho manipulado os dados do BD com a criacao de Models, mas no meu projecto mais recente estou tendando fazer o uso de Query Builder, mas esta dando errado.
Gostaria entender o que esta faltando para que o codigo funcione perfeitamente. Para comecar declarei a facade use DB no meu controller. Aqui esta o código.
public function putente(Request $request)
{
     $putentes = DB::table('utentes')->where('nome',$request->get('putente'))->orWhere('bi_n', $request->get('putente'))->get();
     if(count($putentes)>0)
     {
         return view('home', ['putentes'=>$putentes]);
     }
 }

Na minha view tento pegar os dados dessa forma
{{$putentes->nome}}

Mas esta retornando esse erro
ErrorException in db040389b09b4e77a2f0e7fafa9a269acda44af2.php line 45:
Trying to get property of non-object (View: C:\xampp\htdocs\admc\resources\views\home.blade.php)

Existe algum problema de se utilizar nos projectos o Query Builder em vez de Models?
Answer: Da forma que você está fazendo $putentes é um array. É preciso iterar esses caras antes de acessar a propriedade name:
Assumindo que você está usando o Blade:
@foreach($putentes as $putente)
   {{$putente->nome}}
@endforeach

Sobre utilizar ou não o query builder depende muito do caso. Qual o seu motivo para não utilizar o Model?
Se você não tiver uma razão que se justifique, você só vai estar gerando mais código para fazer a mesma coisa que faria com o model.
Comment: Obrigado pela contribuição, mas solucionei a questão adicionando o metodo first() no final da consulta, assim ele retorna apenas uma linha e não um conjunto de linhas em forma de Array.


Need help reading Muddy Waters's "Got my mojo working"

Question:
This is the rhythm guitar part to Muddy Waters's "Got My Mojo Working". I would like to know what beats the chords land on for this measure. I only know that the first chord lands on the and of 1. Can someone please help me?
Comment: That's only part of your problem! See my comment under Aaron's answer for the rest.
Answer: A graphical supplement to @HaveProblemsEveryday's answer with strumming pattern suggested by @Tim (see comments below).
Note that the chords occur on every third sixteenth note (semiquaver).
Comment: Showing the underlying 16ths above the rhythm makes this rhythm much easier to understand, +1.  @AndyBonner your count is a little off at the end, it should be: ||: 1231231231231231 :|| (with notes on all of the 3's).
Comment: @jamesrivers For a rhythm like this, practice it at slower, manageable tempos. Once the feel of it is internalized, it will come naturally, and you won't need to count every sixteenth note. At that point, you can just strum on each chord, alternating ups and downs.
Comment: Anoter point relevant to the OP's problem then is - what strumming pattern works best? Personally, I'd be playing d,u,d,u, for each beat, to keep the arm moving rhythmically, then hit the strings on the appropriate places, as you indicate.
Comment: @Tim By each beat, you mean each sixteenth? Please confirm, and I'll add that to the graphic.
Comment: Each semiquaver takes a strum, starting down, so 16 separate strums per bar. Others might 'stutter' their strum pattern, but that then means it will only work for that one pattern - and I don't believe that (or any) strum pattern would be used for the entirety of the (or any) song.
Comment: Aaron's comment here comes the closest IMO to explaining this rhythm from the point of view that probably produced it: It's simply counting running 16ths, and playing on every third one. But note, you have to reset the count at the start of the bar, so there's a gap of *four* 16ths between the last note in the bar and the first that you play in the next bar. In other words, you might count to yourself "1 2 **3** 1 2 **3** 1 2 **3** 1 2 **3** 1 2 1 2 **3** ..."
Comment: @AndyBonner More like "1 2 **3** 1 2 **3** 1 2 **3** 1 2 **3** 1 2 **3** _4_ 1 2 **3** ...", right?
Comment: @walen Yeah, or John's correction above, depending what you want to say on that lone 16th at the end of the measure. I just got myself confused.
Comment: @AndyBonner    I have tried to play this but the tempo is 144 and I find it impossible to count let alone play 16th notes at the tempo ,is there any other strum pattern to keep me in time and count?
Comment: This is one of those rhythms that looks impossible at first glance. Then merely difficult when you add the visualised 16s. After a month, you won't even need to visualise, or even wave your arm in time with the 16s. It's a common 'trope' that you will just feel after a while. Once you do, you will just be able to play it all ups, all downs, alternating - it just falls into complete familiarity.
Answer: Since we are dealing with sixteenth notes here, we can break the bar in to
1 e + a 2 e + a 3 e + a 4 e + a
The first chord is on the and of 1
The second chord is on the e of 2
The third chord is right on 3
The fourth chord is on the a of 3
The fifth chord is on the and of 4
Often, what I have found helps me when dealing with tricky rhythms is to count out the beats and write them under the bar to know where each note is played.
Answer: Start by finding the quarter note beats:

Since there are sixteenth note subdivisions here, you can count 1-e-and-a 2-e-and-a 3-e-and-a 4-e-and-a and so on. Now you can see which subdivisions the notes fall on: the "and" of 1, the "e" of 2, the 3, and the "and" of 4.
Something else you should notice: four of the five notes have a dot above them. These dots are articulation marks which mean that these notes should be played staccato.
Comment: @AndyBonner -- I'm not sure that I agree that using 16ths would be busier; then all rests would be eighth rests, and in some ways this might communicate the syncopated rhythm more clearly. On the other hand, these are probably chord stabs which may be better thought of as staccato since they wouldn't be thought of as having precise duration. In any case, I didn't intend a critique of the posted notation, only an exposition of what is there.
Comment: Of course, the notes marked staccato are eighths, and the one not is a 16th; it's likely that the 8ths are to be played as short as 16ths, and it was all notated this way because making them all 16ths would be even busier.
Answer: What you might want to do is either:

Find a youtube video of Muddy playing it.  You Tube allows you to slow down the playback without changing the pitch.  Click on the settings icon and then on playback speed.

If you have the song on your phone or iPad, you can get a music slowdown app for free and slow it down that way.  This will also let you loop a small section of the song.  I think you need to actually own the song to do this. I use an app called Music Speed and it works great.

Far better for this type of music than notation.  I guarantee Muddy never notated it on sheet music.


How many five-digit numbers do not have three consecutive digits the same?

Question: How many five-digit numbers do not have three consecutive digits the same? Also, the initial digits might be $0$, but I'm not sure how that changes the answer.
This is the formula I've come up with for solving this problem.
Total number of numbers - $A - B - C + A \cap B + B \cap C + A \cap C - A \cap B \cap C$
$$10^5 - (10^3 \cdot 3) + (10^2 \cdot 2) - 10$$
So I have
set $A$, positions 1 2 3 are filled;
set $B$, positions 2 3 4 are filled;
set $C$, positions 3 4 5 are filled;
so each set will have $10 \cdot 10 \cdot 10$ subsets of numbers that have $3$ consecutive numbers.
I know that their should be double counting because having consecutive numbers in positions 1 2 3 4 and 2 3 4 5 should be added back, and consecutive numbers 1 2 3 4 5 will need to be subtracted.
So, I get
$$10^5 - (10^3 \cdot 3) + (10^2 \cdot 2) - 10 = 100000 - 3000 + 200 - 10
= 97190$$
However, this is not the correct answer. What is the correct procedure to solve this problem? Or what way am I to look at counting up the sets?
Thanks
Comment: To subtract the numbers with at least three consecutive digits the same, notice that at most one of 0,1,...,9 can repeat thus. Fix this digit, it can occur 5 times, or exactly 4 times consecutively or exactly 3 times consecutively.
Comment: Please read this [tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Answer: There's one mistake and one possible misinterpretation.
The mistake is that you only substracted $10^2$ twice for $|A\cap B|$ and $|B\cap C|$, but $|A\cap C|$ is missing. This is actually the same as $|A\cap B\cap C|$, since in both cases all five digits have to be equal; so those two cancel and the correct total would be $10^5-3\cdot10^3+2\cdot10^2+10^1-10^1=97200$.
The potential misinterpretation is that the problem may have meant only "proper" five-digit numbers that don't start with a $0$.
Comment: @joriki: Your final result has a typo which should be 97200, a 5-digit number.
Comment: I edited the question for addressing the issue with initial 0. Thanks for pointing that out. So I'm assuming that I'm supposed to count 00000 as a number.
Comment: @PVanchinathan: Thanks, fixed.
Comment: @WP0987: Yes (which doesn't correspond to the usual meaning of the word "number"). Does the result match the answer you were given?
Comment: Am I misinterpreting the question ?
Comment: @trueblueanil: I have no idea whether you're misinterpreting the question, since I don't understand your answer. You can certainly solve it this way, but then the last term, where you have $3\cdot9^2$, should be $10\cdot9\cdot10+10\cdot9\cdot9+10\cdot10\cdot9=2610$, which would make your result match mine.
Comment: Thanks, expanded & removed devils !
Comment: @joriki 97200 is the correct answer.  How is |A∩C| and |A∩B∩C| the same? So  |A∩B∩C| has all positions filled. |A∩C| has set A positions 1 2 3, then put with set C positions 3 4 5? Oh! I see now.
Answer: I would do simple subtraction, viz.
all "numbers" - [all 5 digits same + 4 consecutive digits same +  3 consecutive digits same]
e,g, with consecutive 0's, the patterns can be: 00000 , x0000, 0000x, 000xx , x000x and xx000
$10^5 - [ 10 + 2\cdot10\cdot9 + 10\cdot9^2 + 2\cdot 10\cdot9\cdot10 ] = 97200$
Comment: Two patterns with 5 same, oooox and xoooo , 10 choices for the string of o's, but only 9 choices for the x, so $2\cdot10\cdot9$. Three patterns with 3 same, xooox $(10\cdot9^2)$ but in the remaining 2 patterns, xxooo & oooxx  the extreme x's have 10 choices. You should be able to figure it out now.
Comment: In the last line, the signs are correct; in the second line they're wrong.
Comment: @joriki:Thanks, I think I need coffee !
Comment: @trueblueanil yes 97200 is the correct answer. However, I having trouble understanding the math. 10^5 (all 5 digit numbers) minus [ 10 (all 5 digits same) plus 2⋅10⋅9+10⋅9^2 +2⋅10⋅9⋅10 ]. I'm confused about how the rest of the numbers are derived.
Answer: This problem can be broken down into two cases-

When no consecutive digits are same
When two consecutive digits are same

The answer would be the sum of the number of ways of the two indvidual cases.

If f(n) be the answer to the above problem having n number of digits. Then,
f(n) = 9*(f(n-1)+f(n-2))
 The equation can be represented in matrix from as,
\begin{equation*}
\begin{bmatrix}
f(n) \\
f(n-1) \\
\end{bmatrix} =
\begin{bmatrix}
9 & 9 \\
1 & 0 \\
\end{bmatrix}*\begin{bmatrix}
f(n-1) \\
f(n-2) \\
\end{bmatrix}
\end{equation*}
Solving the recurrence, we get,
\begin{equation*}
\begin{bmatrix}
f(n) \\
f(n-1) \\
\end{bmatrix} =
\begin{bmatrix}
9 & 9 \\
1 & 0 \\
\end{bmatrix}^{n-2}*\begin{bmatrix}
f(2) \\
f(1) \\
\end{bmatrix}
\end{equation*}
Clearly, the base cases are f(1) = 10 and f(2) = 100.

This can now be solved using matrix exponentiation having computation complexity of (k3log(n)) where k=2 (size of the square matrix).
Now, considering the above asked question, plugging n=5 into the recurrence gives,

\begin{equation*}
\begin{bmatrix}
f(5) \\
f(4) \\
\end{bmatrix} =
\begin{bmatrix}
9 & 9 \\
1 & 0 \\
\end{bmatrix}^{3}*\begin{bmatrix}
100 \\
10 \\
\end{bmatrix}
\end{equation*}
i.e.,
\begin{equation*}
\begin{bmatrix}
f(5) \\
f(4) \\
\end{bmatrix} =
\begin{bmatrix}
891 & 810 \\
90 & 81 \\
\end{bmatrix}*\begin{bmatrix}
100 \\
10 \\
\end{bmatrix}
\end{equation*}
Therefore,
\begin{equation*} f(5)=891*100+810*10=97200\end{equation*}


SlidingTabLayout compressing tab text

Question: I am using the SlidingTabLayout.java and SlidingTabStrip.java files along with the Toolbar to create swipeable tabs.
I followed a couple different tutorials now and run into the same problem with how my tabs are displaying. I set setDistributeEvenly to true and changed my code to have four strings rather than 3. Now the text in my tabs are compressing rather than setting the width to the largest string value and allowing overflow for the sliding while in portrait mode. In landscape, the problem doesn't exist. https://i.stack.imgur.com/ILBaP.png vs https://i.stack.imgur.com/CXMuK.png
If I remove a string, the problem is solved, and if I add another string, overflow is allowed but it no longer sets the width evenly, but it again works fine in landscape.
My theory is that the calculated width for my four tabs, given the text length, is hitting some weird "sweet" spot for my screen size. It's too big to contain itself on one screen, but it's not big enough for it to trigger overflow.
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_square);

Toolbar appToolbar = (Toolbar) findViewById(R.id.square_toolbar);   //creates instance of app_toolbar to serve as actionbar
//setting toolbar to actionbar
setSupportActionBar(appToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false); //do not have app_toolbar Title

// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager(), TheSquare.this));

//Give slidingTabLayout ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
//Center the tabs in the layout
 slidingTabLayout.setDistributeEvenly(true);

slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer(){
    @Override
    public int getIndicatorColor(int position){
        return getResources().getColor(R.color.green);
    }
});

slidingTabLayout.setViewPager(viewPager);

}

TabFragmentPagerAdapter.java
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
private String tabTitles[] = new String[] { "Featured", "News", "Sports", "Life"};
private Context context;

public TabFragmentPagerAdapter(FragmentManager fm, Context context) {
    super(fm);
    this.context = context;
}

@Override
public Fragment getItem(int position) {
    return PageFragment.newInstance(position + 1);
}
@Override
public int getCount() {
    return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position
    return tabTitles[position];
}
}

main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@color/white"
          android:orientation="vertical">

<include
    android:id="@+id/square_toolbar"
    layout="@layout/app_toolbar"/>

<com.squareoffs.squareoffs.SlidingTabs.SlidingTabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:layout_weight="1"
    android:background="@android:color/white"/>

I'm a bit out of ideas to test, appreciate the help.
Answer: Could not resolve the 'why' of the issue, aside from my theory above, but I added spaces to each string ("News" to "  News  ") so they were equal length and, at least in this particular case, it resolved the problem. It's not an ideal solution as I've had to reduce padding to make sure everything looks similar in the tabs if I want the text to take up equal space but it at least displays properly.

SlidingTabLayout compressing tab text


Executar duas funções com onclick

Question: Eu preciso executar duas funções com onClick, mas não estou conseguindo, alguém poderia me ajudar?
Eu quero esconder a div pai "introductionAds" e mostrar a div "mostrarID"

function ocultar(ocultarID){
    document.getElementById(ocultarID).style.display='none';
}
function mostrar(mostrarID){
    document.getElementById(mostrarID).style.display='block';
}
.disabled {
  text-decoration: none;
  color: gray;
  cursor: default;
}

 Link habilitado

 Link habilitado

 Link habilitado

 Link habilitado

 Link habilitado

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Answer: Adicione ponto e virgula no final para chamar as funções, (será chamado em ordem)
 <input id="botao" type="button" value="click" onclick="ocultarID(); mostrarID();"/>

Comment: Guilherme essa foi a minha primeira tentativa e por incrivel que pareça não funciona, porem perceba que eu quero executar a função em um link e não em um botão. Pra vc ter umaideia tente colocar o meu script num editor e executa pra vc ver, não funfiona assim, pelo menos deveria.
Answer: Cara, se eu entendi certo, vc vai esconder uma e mostrar a outra no mesmo momento. Então pode colocar tudo numa função só. Ficaria assim:

function mostrar (){
  document.getElementById('mostrarID').style.display = 'block';
  document.getElementById('introductionAds').style.display = 'none';
}

E não precisa passar nada como parâmetro, o JS busca o id no HTML. Tenta assim, se não for isso q vc quer, só avisar.
Comment: Junior também já tentei isso e só oculta a div introductionAds mas não mostra a div mostrarID. Só pra ter certeza acabei de tentar isso ai de novo mas nada ainda. Não entendo porque não esta funcionando.
Answer: Você pode também transcrever essa função em uma só:
function mostrar(id, show){
    var show = (show) ? 'block' : 'none';
    document.getElementById(id).style.display=show;
}

mostrar('introductionAds', true);
mostrar('introductionAds', false);

Comment: Guilherme acabei de testar aqui e também não funciona veja no link abaixo:
Comment: Também não funcionou, confira http://jsfiddle.net/p3Bht/74/

Executar duas funções com onclick