Distributed Erlang and riak-core: how does the mesh scale for large clusters?

Question: Using distributed Erlang creates a mesh network between all the nodes, and that doesn't scale well to hundreds of nodes. How does riak-core deal with that?
Does it not use distributed Erlang (set -connect_all=false and use custom protocol for communication between riak nodes)? From a cursory look at the code, it doesn't seem like they are doing that.
Answer: I believe they recommend to limit the cluster to 100 nodes, I can't find the reference now, tho.
In clusters over 100 nodes, ping noise will be significant part of network traffic. Even bigger deployments require deep changes in Erlang VM and OS.
Here is the link to cluster capacity planning from their wiki: http://wiki.basho.com/Cluster-Capacity-Planning.html
Comment: The capacity planning page does not mention the upper limit on the cluster size. But they do say a moderately sized riak cluster is around 18 nodes. So I'm guessing anything beyond 100 nodes hasn't been attempted.
Comment: oh no, there is even blog post from basho employee with the script to deploy 100 nodes on EC2. But one thing to deploy, the other thing to use it. http://reiddraper.com/100-node-riak-cluster/
Comment: Erlang clusters seem to be good to 125-175 nodes, though there's research going into making them *far* more scalable http://www.release-project.eu/


OnMyLocationChangeListener Google maps android

Question: Eu tenho uma aplicação que funciona como um rastreio de GPS, está funcionando normal, quando o usuario se mexe ele joga no meu servidor a mudança que faz com que todos os aparelhos troquem de lugar o Marker. Porém eu preciso fazer com que a função OnMyLocationChangeListener, funcione mesmo com o aplicativo fechado, pensei em um Service, mas não sei se isso é possível. Alguém sabe se é? Se não for, existe uma forma melhor de se fazer?
Comment: Sim, é possível. Da mesma forma que se conecta com a `GoogleApiClient` na `Activity`, é possível fazer em um `Service`, porém irá usar o `LocationClient` e não o `GoogleMap`. Apenas cuidado com o uso do GPS, não deixe o `Service` ativo sem necessidade, porque GPS gasta muita bateria. Para usar o `LocationClient` de uma olhada em http://developer.android.com/training/location/receive-location-updates.html.
Comment: Opa, obrigado, vou tentar usar.
Answer: Sim isso é possivel. Você deve declarar um IntentService e usar um BroadCast para comunicar com a app. Você poderá estar sempre com os dados de localização atualizados, mesmo se a app não estiver executando.  Aqui você encontra a melhor forma de fazer isso.


Avoid "unused typedef" warnings when wrapping with swig

Question: I am using swig as a wrapper to call c++ functions from my python code. My problem is, that a lot of warnings of the following type are generated, because I included part of the Boost library.
<code>/usr/local/include/boost/math/special_functions/bessel.hpp:744:4: warning: unused typedef
  'boost_static_assert_typedef_747' [-Wunused-local-typedef]
</code>
Is there a way to avoid this? I guess using
<code>-isystem /usr/local/include
</code>
as a flag instead of
<code>-I /usr/local/include
</code>
would solve the problem. But where do I have to add it? The latter option is currently implemented in my setup.py:
<code>#!/usr/bin/env python

"""
setup.py file for SWIG spherical_overlap
"""

from distutils.core import setup, Extension

spherical_overlap_module = Extension('_spherical_overlap',
                       sources=['spherical_overlap_wrap.cxx', 'spherical_overlap.cpp'],
                           swig_opts=['-c++', '-py3'],
                           extra_compile_args =['-lboost_system '],
                           include_dirs = ['/usr/local/include'],
                           )

setup (name = 'spherical_overlap',
       version = '0.1',
       author      = "SWIG Docs",
       description = """Simple swig spherical_overlap from docs""",
       ext_modules = [spherical_overlap_module],
       py_modules = ["spherical_overlap"],
       )
</code>
Comment: Thanks, that is enough for me. I added `-Wno-unused-local-typedef` to `extra_compile_args`.
Answer: if you want just to avoid warnings you can add <code>-Wno-unused-local-typedef</code> option


Moralization and triangulation on belief networks

Question: Assume that I have a belief network with a set of nodes.
In order to create a valid junction tree I have to moralize the graph. Assume now that I have nodes with more than 2 parents (e.g 3 parents) then I have to link each of the parents. After doing that, the graphical models contain some unnecessary cliques. Can I use only a part of the cliques for the Junction Tree Creation? Or I must use every clique in the junction tree (e.g., a case with 8 nodes and 8 cliques)?
Answer: You only need to use maximal cliques. That is, if you have two cliques {a,b,c} and {a,b}, you only use {a,b,c}. Other than that, yes, you might generate unnecessary cliques, but how many depends also on the triangulation strategy (minimum fill-in is an NP-hard problem, so you won't really be able to do it perfectly in all cases).
Answer: I'm trying to implement the junction tree algorithm in Ruby.
I found that after moralizing, triangulating, and creating the final cliques by variable elimination, the final cliques contained all of the cliques from triangulated graph, but the maximally connected cliques in the triangulated graph were combined into one clique in the junction tree.
I'm new at this, but I don't think you can drop cliques along the way.


Efficient Way of finding possible sums in equation

Question: I am looking for an efficient way to find the following numbers numbers $a, b$
Let $x$ be 63 (as example)
$$\sum_{k = a}^b k = \sum_{l = 1}^b l - \sum_{j=1}^{a-1} j = \frac{b*(b+1)}{2}-\frac{a*(a-1)}{2} = x = 63$$
in this case for example
$$63 = 8+9+10+11+12+13 = \sum_{k = 8}^{13} k $$
Answer: Given positive integer $x$, you want positive integers $a,b$ such that
$$ 2x = b(b+1) - a(a-1) $$
If $c = 2a-1$ and $d=2b+1$, this says
$$ (d-c)(d+c) = d^2 - c^2 = 8x $$
(with $c$ and $d$ both odd).
So look at factorizations of $8x$.  If $8x = uv$ where $u$ and $v$ are positive integers, $u < v$,
we want $d-c = u$ and $d+c = v$, and then $d = (u+v)/2$, $c = (v-u)/2$.
Note that we can take $u \equiv 2 \mod 4$ and $v \equiv 0 \mod 4$ (or vice versa), and get $c$ and $d$ odd.
In your example, $x=63$, $8x = 2^3 \times 3^2 \times 7$, and the solutions are:

$u = 2$, $v = 252$, $c = 125$, $d = 127$, $a = 63$, $b = 63$
$u = 6$, $v = 84$, $c=39$, $d=45$, $a = 29$, $b=22$
$u = 14$, $v = 36$, $c=11$, $d=25$, $a = 6$, $b=12$
$u = 18$, $v = 28$, $c=5$, $d=23$, $a = 3$, $b=11$
$u = 12$, $v = 42$, $c=15$, $d=27$, $a = 8$, $b=13$
$u = 4$, $v = 126$, $c=61$, $d=65$, $a = 31$, $b=32$
Comment: Thanks for catching that - edited.
Answer: Expanding your sums, you have :
$$\frac{b^2+b}{2}-\frac{a^2-a}{2} = x$$
$$\iff (b+a)(b-a+1)=2x$$
Here, you have one of the two terms which is odd and then other even... Wait I guess that should be useful but..
The most obvious solution I see is :
$a = \frac{x-1}{2}, b=\frac{x+1}{2}$ but it will only work for an odd $x$.
But it's not really satisfying I guesS.


Can there be a bipartite graph that has an Eulerian circuit, Hamiltonian cycle, but is nonplanar?

Question: So far I have that the graph's chromatic number is two (not sure how that would help) as well as that since it has an Eulerian circuit, all vertices must have even degree. I am thinking of using Kuratowski's theorem and showing it has no subgraphs homeomorphic to $K_5$ or $K_{3,3}$ but I am unsure how to do that.
Should I start by showing since it is bipartite all of its subgraphs must be bipartite, hence cannot be homeomorphic to $K_5$ or $K_{3,3}$? Or would that be an incorrect approach? Thanks!
Comment: Have you made an attempt to find such a graph?
Comment: Yes, $K_{4,4}$.
Answer: Actually yes and there are quite a few of them. How about, for each integer $n$ at least 2, the complete bipartite graph $K_{2n,2n}$ with $2n$ vertices on each side.
Note that $K_{3,3}$ is a subgraph of $K_{2n,2n}$ for all $n \ge 2$ and indeed $K_{3,3}$ is a subgraph of $K_{m,m}$ for all integers odd or even $m \ge 3$ .


Same shadow for android and ios

Question: I know there is elevation for android and shadowColor, shadowOffset, shadowOpacity, shadowRadius for ios. But I want to get the same shadow for android and ios, but i can't do it with just elevation for android.
So, i tested the packages react-native-shadow and react-native-shadow-2, they are not too bad, but they have so many default:
react-native-shadow:

is old
can not have child size
too many options for nothing
...

react-native-shadow-2:

supports the dynamic size (width='100%').. but the child of Shadow can't fill the parent size by setting width='100%' or with the height ...
can not define the intensity of the blur (it is automatic)
...

How or what can I do for get the same shadow like I can do it with ios for android (like, with approximately the same properties for ios) ?
Answer: I am the dev of the react-native-shadow-2 :)
For the "but the child of Shadow can't fill the parent size by setting width='100%'", I have recently added to the FAQ this issue:

Q: My component is no longer using the available parent width after
applying the Shadow! What to do?
A: Use viewStyle={{alignSelf: 'stretch'}} or undefined instead of
'stretch', in your Shadow component.

Feel free to open any issue in the repository!

Same shadow for android and ios


Flutter way to implement clean architecture

Question: I have started learning flutter after 5 years of android dev. And right now i am trying to implement multi modular clean architecture as i used to, when developing android, example of such architecture: https://github.com/android10/Android-CleanArchitecture
And i have ran into two issues i can't solve by on my own.
1) What type of flutter module should i use module/plugin/package? I want to make domian layer as simple as it could be(list of interfaces,mappers and dto's), in android it was written in plain kotlin without any android sdk's usage. It seems like domain layer should be package(because it doesn't have any platform specific code and seems to be the simplest module possible) and data layer should be plugin in case i would be forced to make some platform specific code here, but i am not sure. It would be great to have some suggestions here.
2) Maybe there is a github repo example, as I have shown above? All git repos i have found so far are implementing clean architecture with just folders and this approach always ends up with dependencies mess, loosing all the profit you can get from clean architecture.
Any help is appreciated!
Comment: Have you found a solution?
Comment: Ehm, I made it myself, I have two implementations, one with more pain, and one with less, second one is less "clean" but at least flutter is able to build it without me building each module by hands, and then running the app.
Answer: Recently I published an article on using DI container abstractions in a Modularized Flutter App adhering to Clean Architecture Principles. The package separation example in the article should give a decent overview of how to divide the solution into packages and organize dependencies between them to adhere to the Clean Architecture principles.
Here are the short answers to your questions:

The modules in your solution should be packages. It should be Dart-only packages for UI-agnostic layers like Domain and Flutter packages for layers like Presentation/UI.
This Github repo is the example implementation of the Counter Flutter app with the solution division into physical Dart/Flutter packages instead of just the folders division. The diagram below depicts the packages you'll see in that example and the dependencies between them. I definitely recommend using physical layer division, i.e. using packages, in any serious Flutter app.

Hope that helps you and others!
Answer: You could pay attention to the library clean_architecture (https://pub.dev/packages/clean_architecture).
It may be possible to implement a clean architecture not by all the rules, but it brings a certain useful result.
In the near future I will add instructions on how to use it
Comment: I have already did this, but it implements clean architecture using just folders, it is much harder to control dependencies with such implementation. So i am searching for module based implementation.


Should Stack Overflow tell users with Magento-related questions of borderline quality to come here?

Question: When I see a Magento question on Stack Overflow that doesn't belong there (i.e. it has no programming aspect at all or is extremely specialized) I tend to tell them to go to http://magento.stackexchange.com and ask there. I try to filter a bit - if it's an extremely low quality question, I will just vote to close. But even with that, most of the questions that we are talking about are of.... borderline quality.
SO's sending users with questions of less-than-perfect quality to  other, smaller sites in the network has caused trouble in the past because those new users were perceived as drowning the place with their questions.
Does Magento.SE have problems with its incoming user / question base, or is it more tolerant towards questions like "how do I implement feature X???????" or "X feature in my Magento install doesn't work???????"
tl;dr: Should experienced users on Stack Overflow continue recommending Magento.SE to people  with relatively little discrimination, or should great care be taken that the questioner has an actual high quality question?
Answer: From my understanding of the intentions of starting our own magento.SE is to have a site dedicated to Magento since not all Magento questions are necessarily SO relevant.
In that spirit I would say send every one our way and if we feel the users did not make enough of an effort we will for sure let them know.

Does Magento.SE have problems with its incoming user / question base,
  or is it more tolerant towards questions like "how do I implement
  feature X???????" or "X feature in my Magento install doesn't
  work???????"

I personally don't mind "how do I implement feature X?" questions. Most answers would not include full fledged working code examples but would rather outline an approach in broad strokes. This is something that even I as an experienced Magento developer can learn from and find valuable.
Comment: I totally agree. I often ask those "how to implement feature x" questions here and prefer answers the provide an approach.


How do you configure kotlinx serialization in Spring Boot?

Question: I am wondering how I can configure kotlinx as a default serialization in Spring Boot app.
For Jackson, I would use e.g. spring.jackson.deserialization.fail-on-unknown-properties=false
But I haven't found any configuration options for kotlinx in Spring.
I know kotlinx supports this, I only cannot find a way to configure it on Spring level so that it works for example in controller method signatures:
@PostMapping("/foo")
fun fooMethod(
    @RequestBody fooJsonRequest: SomeDataClassRepresentingTheJson,
) {}

↑ Throws HttpMessageNotReadableException exception suggesting I use ignoreUnknownKeys=true when constructing kotlinx.serialization.json.Json. However I do not know where to do this so it would apply to Spring itself.
I have tried creating a bean providing Json object to no avail.
Answer: Publish a @Bean of the following type and customize Json constructor as needed:
@Bean
fun messageConverter(): KotlinSerializationJsonHttpMessageConverter {
    return KotlinSerializationJsonHttpMessageConverter(Json {
        ignoreUnknownKeys = true
    })
}


Why does the program loop the same output if the user inputs a number higher then 10?

Question: I was assigned a program in C to get a users input for how much additional water will be added to a fish tank, and after 24 hours the fish will be "BBQ'd". The problem that I'm having is if i input a higher number then 10 in scanf. The loop repeats and gives the same output forever. Am i using the correct place holder for scanf?
#include <stdio.h>

int main(void) {

    //Declares variables
    double fishTank = 500;
    int hours = 0;
    int addWater;
    //asks user for input.
    printf("Please enter additional water to be added per hour:");
    scanf("%d", &addWater);

    //while fishtank is greater then or equal to 100 it will run this loop
    while (fishTank >= 100) {
        fishTank = fishTank - (fishTank * .1) + addWater;
        printf("The tank still has %f gallons remaining\n", fishTank);

        //increments hours by 1
        hours = hours + 1;
    }
    //if hours drops below 24 it will print this output
    if (hours < 24) {
        printf("Out of water at hour %d when remaining gallons were %f\n", hours, fishTank);
    }
    //if hours is greater then 24 by the time the loop ends it will print this.
    else if (hours >= 24) {
        printf("Get out the BBQ and lets eat fish.\n");
    }
    system("pause");
    return 0;
}

Answer: Look at the equation
 fishTank = fishTank - (fishTank * .1) + addWater;

If at the beginning fishTank is  > 100, (fishTank * .1) cannot decrease fishTank if addWater >= 10, because after some iterations fishTank * 0.1 becomes equal to addWater.
I suppose, that your solution is correct, but you should provide an alternative way out of the loop. For example, change the condition for while as
  while (hours <= 24 && fishTank >= 100)

Answer: The tank looses 10% of it's current volume every hour, which if it has 100 units is 10 units. It gains whatever the user enters. If this number is greater than 10, every time it could drop below 100 it's gaining enough to go above 100 again. Even if it gets back to exactly 100, adding 10 or more is enough to keep it there – so it loops forever
Your while statement needs to be:
while (fishTank >= 100 && hours < 24) {


Como resolver problemas no display flex do firefox

Question: Criei este portfólio ele funciona perfeitamente no chrome, porém no firefox a tag button que fica sobreposta na tag img (para fazer o efeito de sombra e abrir um modal) aparece como um quinto item, gerando scroll horizontal e não fazendo o efeito de sombreamento quando o mouse passa em cima, gostaria de saber como deixar sobreposto no firefox!
Como fica no chrome:(como deveria ficar)

Como fica no firefox:

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

Comment: Alguns elementos CSS necessitam de prefixos para funcionar em diferentes navegadores, não tenho certeza se é a solução mas vale a pena dar uma olhada nesse link da Tableless que fala sobre Prefixos (https://tableless.com.br/prefixos-dos-browsers-a-web-precisa-de-voce/) e nesse Link da Mozilla que fala sobre Flexbox (https://developer.mozilla.org/pt-BR/docs/CSS/Usando_caixas_flexiveis_css). Além disso, esse site aplica automaticamente alguns prefixos para o código que você inserir (https://autoprefixer.github.io/)
Comment: muito obrigado vou ler e tentar aplicar
Answer: Amigo basicamente o que faltou no seu código foi definir uma referencia no eixo X, repare que vc declarou um top como 0, que seria o seixo Y, porém não declarou nada pro eixo X, vc pode usar ou um left: 0; como eu usei ou right: 0; que tb da certo. Então na classe .sombra eu adicionei tb um left: 0;.

Veja como fica. Pode testar no Fire Fox que vai dar certo. Essa particularidade vai de browser para browser, não tem muito o que explicar nesse "erro", isso tem mais a ver com o motor de renderização do browser, que no FireFox é diferente do Chrome....

.portfolio{margin-bottom: 100px; margin-top: 86px;display: flex; flex-wrap: wrap;}

.projetos{width: 25%;}

.projetos-content{position: relative;}

.projetos-img{width: 100%;}

.sombra{background: rgba(255,255,255,0.0); width: 100%; height: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; border: none;}

.sombra:hover{background: rgba(0, 0, 0, 0.4); cursor: pointer;}

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

      <button type="button" class="sombra" data-toggle="modal" data-target="#exampleModal"></button>

Comment: Muito obrigado, resolveu o problema!
Comment: @DeMarchi se vc não definir de onde o elemento deve começar em um dos eixos, o browser não entende de onde o elemento começa e onde termina. Mas legal que resolveu! Considere marcar a resposta como aceita nesse ícone  `✔` abaixo das setinhas da minha resposta. Assim o site não fica com a pergunta sem resposta aceita, mesmo já tendo sido resolvido. Depois se aparecer outra resposta que te atenda melhor vc pode mudar o aceite para ela.


Why doesn't GDB recognize the language of my C program?

Question: I'm working from an example in a book, where the author writes a short, flawed C program to demonstrate debugging with GDB.
#include <stdio.h>

int main (void)
{
    const int data[5] = {1, 2, 3, 4, 5};
    int i, sum;

    for (i = 0; i >= 0; ++i)
        sum += data[i];

    printf ("sum = %i\n", sum);

    return 0;
}

After compiling with gcc -g program.c, he runs gdb ./a.out and calls run from within gdb. When it hits the flaw in the program, he calls,
(gdb) print data
$1 = {1, 2, 3, 4, 5}

When I try the same, I get,
(gdb) print data
$1 = 0x100000f80
Current language:  auto; currently minimal

I did some digging and it sounds like the fact that I'm only being shown the memory address is related to the message beneath about "Current language".
I compiled and ran the above C program like so,
❯ gcc -g program.c
❯ gdb ./a.out
Reading symbols for shared libraries .. done
(gdb) run
Starting program: /Users/ivan/Development/books/c/programming-in-c/a.out

GDB then outputs a bunch of lines about unsupported "indirect" references,
Reading symbols for shared libraries +..............bfd_mach_o_scan_read_symtab_symbol: symbol "_bzero" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_memccpy" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_memchr" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_memcmp" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_memcpy" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_memmove" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_memset" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_strchr" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_strcmp" is unsupported 'indirect' reference: setting to undefined
bfd_mach_o_scan_read_symtab_symbol: symbol "_strncmp" is unsupported 'indirect' reference: setting to undefined

...followed by warnings about not being able to find object files (all of which look related to ssl/tls):
...warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Objects/coretls.build/coretls.build/Objects-normal/x86_64/system_coretls_vers.o" - no debug information available for "system_coretls_vers.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_ciphersuites.a(tls_ciphersuites.o)" - no debug information available for "tls_ciphersuites.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslSession.o)" - no debug information available for "sslSession.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslCipherSpecs.o)" - no debug information available for "sslCipherSpecs.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslDigests.o)" - no debug information available for "sslDigests.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslCrypto.o)" - no debug information available for "sslCrypto.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslChangeCipher.o)" - no debug information available for "sslChangeCipher.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslCert.o)" - no debug information available for "sslCert.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslKeyExchange.o)" - no debug information available for "sslKeyExchange.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslAlertMessage.o)" - no debug information available for "sslAlertMessage.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslHandshake.o)" - no debug information available for "sslHandshake.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslHandshakeFinish.o)" - no debug information available for "sslHandshakeFinish.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(tls1Callouts.o)" - no debug information available for "tls1Callouts.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(sslHandshakeHello.o)" - no debug information available for "sslHandshakeHello.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(tls_handshake.o)" - no debug information available for "tls_handshake.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_handshake.a(ssl3Callouts.o)" - no debug information available for "ssl3Callouts.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(tls1RecordCallouts.o)" - no debug information available for "tls1RecordCallouts.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(ssl3RecordCallouts.o)" - no debug information available for "ssl3RecordCallouts.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(tls_record.o)" - no debug information available for "tls_record.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(sslRc4Cipher.o)" - no debug information available for "sslRc4Cipher.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(sslMemory.o)" - no debug information available for "sslMemory.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(sslUtils.o)" - no debug information available for "sslUtils.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(symCipherParams.o)" - no debug information available for "symCipherParams.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(sslNullCipher.o)" - no debug information available for "sslNullCipher.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(symCipher.o)" - no debug information available for "symCipher.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(tls_digest.o)" - no debug information available for "tls_digest.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(tls_hashhmac.o)" - no debug information available for "tls_hashhmac.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_record.a(tls_hmac.o)" - no debug information available for "tls_hmac.c".
warning: Could not find object file "/BinaryCache/coreTLS/coreTLS-35.40.1~1/Symbols/BuiltProducts/libcoretls_stream_parser.a(tls_stream_parser.o)" - no debug information available for "tls_stream_parser.c".
....................... done

...then finally it stops at the expected (flawed) line of the program:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x0000000100006000
0x0000000100000f1e in main () at prog.18.4.c:9
9                       sum += data[i];

I'm on OS X Yosemite, with the following versions of gcc and gdb:
❯ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix

❯ gdb --version
GNU gdb 6.3.50-20050815 (Apple version gdb-1824) (Wed Feb  6 22:51:23 UTC 2013)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".

What do I need to do to get GDB to recognize this as a C program?
Comment: Are you sure you compiled with `-g`?
Comment: Please explain your *gcc* / *gdb* installation and what OS or if Linux which distro
Comment: @nos Fair enough. I still would like to know why gdb isn't recognizing the language though.
Answer: You must compile and link the program with the -g option, to include debugging information such as function and variable names, source language and location...


How to design a grid layout which will fit whole screen?

Question: I like to design a layout like in the image below. What would be the best way to design this layout, so the icon will be centered in the box and if we load it in big screen the whole screen should fit those 8 boxes?
Comment: How did you tried to make this simple layout?
Comment: I tried to use grid layout and relative layout with ImageView. But not getting the exact results. also in bigscreen its not fitting the whole screen.
Answer: Here's an example on how you might do that layout:
<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <View
        android:id="@+id/middle_separator"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@id/middle_separator"
        android:orientation="vertical" >

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#000000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#220000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#440000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#660000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/middle_separator"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#880000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#aa0000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cc0000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#ee0000" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stuff"
                android:textColor="#ffffff" />
        </FrameLayout>
    </LinearLayout>

</RelativeLayout>
</code>
Comment: thanks a bunch. works like a charm. except the  its not working . how to make that work? it says "Couldn't resolve resource"
Comment: @jquery404 It's a `` tag (with a capital letter) and not ``.


Which axiom makes a vector space flat?

Question: First of all, I'm not sure if this question even makes sense, i.e. is there a notion of curvature on a vector space structure. However, when dealing with vector spaces (here I am mostly thinking of tangent spaces on a manifold), we treat (and draw) them as flat. On the other hand, I don't see the flatness assumption (nor any kind of parallelism) in the vector space axioms.
So, my question is, are and what makes vector spaces flat? What is the difference between the arrows in flat space and e.g. directed arcs of great circles on a 2-sphere? Don't they both satisfy the same axioms?
Comment: "Flat" seems like a topological-geometric assumption. Vector spaces are not necessarily topological-geometrical objects, so they don't need to have a notion of "flatness" or "shape" to them. So the axioms don't have to satisfy that.
Answer: I think it's not about curvature, there is something more fundamental that distinguishes $\mathbb{R}^n$ from any other manifold. For any $p\in\mathbb{R}^n$ there is a canonical isomorphism $T_p\mathbb{R}^n\to\mathbb{R}^n$. Any tangent vector $v\in T_p\mathbb{R}^n$ is represented by some path $\alpha$ with $\alpha(0)=p$. The isomorphism is given by $v\mapsto\dot{\alpha}(0)\in\mathbb{R}^n$.
This isomorphism yields a canonical isomorphism between the tangent spaces at two distinct points, and this is something that does not exist on any other manifold.
The concept of parallel transport is thus very simple on $\mathbb{R}^n$. Actually, a vector field on $\mathbb{R}^n$ can be constant, where the definition of constant is very clear.
Intuitively speaking, curvature of a Riemannian manifold $M$ measures how much two vector fields don't commute. But in Euclidean space, having noticed that any tangent vector can be extended canonically to a constant vector field, the fact that every two tangent vectors commute is just the theorem of changing the order of differentiation:
$$\frac{\partial^2}{\partial x\partial y}=\frac{\partial^2 f}{\partial y \partial x}.$$
Since every two tangent vectors (or vector fields) commute, the curvature is $0$.
Comment: What do you mean by "flat", anyway? I think this point needs clarification. Euclidean spaces are the simplest manifolds there are, and curvature is some way to check how much a given manifold is similar to a Euclidean space. So from the first place curvature was invented in such a way that Euclidean spaces would turn out to be flat. Maybe you need to ask what the meaning of "flat" is.
Comment: I don't understand the question. How can arcs in $S^2$ satisfy the axioms of vector spaces?
Comment: @LittleBrownOne If you're talking about the tangent space at some point, sure. If you're talking about actual geodesics, I challenge you, for $n \geq 2$, to try and rigorously make sense of addition. (Hint: the definition doesn't commute). It's actually rather subtle to specify what it means to take a pair of arcs $c_1,c_2$ both starting at one point and then to move $c_2$ to the start of $c_1$.

The notion you'll end up needing is "parallel transport" but curvature actually measures the failure of parallel transport to commute.
Comment: This is still implicitly using the smooth structure. $\mathbb{R}^4$ has a continuum of homeomorphic, non-diffeomorphic smooth structures. I don't think things work as simply on all exotic structures. I could be mistaken, but I'm doubtful.
Comment: Would you say that directed lines in $R^2$ and directed arcs in $S^2$ are just two models which satisfy axioms of vector space but the lines have an additional structure, the canonical isomorphism?
Comment: You can add them and multiply by a scalar and still get a directed arc. Shouldn't it be the same for every geodesic?
Comment: @JHance OK, I see your point. So, it is the commutativity of vector addition which makes the vector space flat?

Which axiom makes a vector space flat?


How to catch subsequent API signatures?

Question: I am creating an API server with user provided routes. I am stuck how can I write routes that user defined routes are dynamically handled, if the precedent route matches user's token.
I have tried two approaches, One with :params, but that doesn't work as desired as a user might input multiple levels of routes.
router.all('/api/:apikey/:fakeapi', function (req, res, next) {
  logger.debug(`API Key: ${req.params.apikey}, Requested URL: ${req.params.fakeapi}`);

  res.send(`API Key: ${req.params.apikey}, Requested URL: ${req.params.fakeapi}`);
});

Above code, works if route /api/378929832/fine, but fails when the route is something like api/378929832/fine/with/me.
How can I make it handle all subsequent /xyz/xyz/xyz/... if the precedent API signature matches it?
Answer: I have come up with a hacky solution, but it's not the best way, so I have asked above question.
I have used * to make it catch all after a precedent match, like below
router.all('/api/:apikey/*', function (req, res, next) {
  logger.debug(`API Key: ${req.params.apikey}, Requested URL: ${req.url.replace('/api/', '').replace(req.params.apikey + '/', '')}`);

  res.send(`API Key: ${req.params.apikey}, Requested URL: ${req.url.replace('/api/', '').replace(req.params.apikey + '/', '')}`);
});

Above code works for http://localhost:8080/api/378929832/fine as well for any dynamic http://localhost:8080/api/378929832/fine/with/me or even with http://localhost:8080/api/378929832/fine/with/me/?redirect=http://stackoverflow.com.
Answer: First, just a heads up on the design of your routes - RESTful API design is all the rage, and trying to design your API in a RESTful way can be great. It makes sense logically, and is generally expected of web services these days. Even if you're only using it internally, it can really simplify things for you by enforcing consistency across your routes, and means that it's ready-to-use if you want to open up your API to the outside world. If you're already building an API intended for outside consumption, not following best practices opens your developers up to a world of hurt!
The thing that stuck out immediately to me was the API key as part of the path. Routes are usually written as /api/[object or resource], so from that perspective it doesn't make sense to throw an API key in there. More importantly, requiring the key in the URL means that every API key will be revealed in your web server's logs. You'd also have this issue if you changed it to a query string parameter, so a good option is usually having the API key or other auth token in a header (the Authorization header is commonly used with tokens).
Moving on, if you're keen to continue with the current format, you can use router.param().
router.param takes the name of a route parameter as well as a function that will be called when a subsequent route shows up with that parameter. This means you can catch and check your API key whenever it shows up in a route without having to explicitly specify it.
For example:
var checkApiKey = function(req, res, next, id) {
    // `id` is the parameter that was passed
    if(!isValidApiKey(id)) return res.send("Bad");
    return next();
}

router.param("apikey",routes.checkApiKey);

router.get("/:apikey/me",routes.listMe);
router.post("/:apikey/me",routes.createMe);

If you have a parent router, you can move some things around so that :apikey is only specified once, at the root, and all API requests have a base of /api/[key]/. Functionally the same, this just means you're not duplicating the :apikey parameter for every route:
var apiRouter = express.Router();
apiRouter.get("/me",listMe);
apiRouter.post("/me",createMe);

parentRouter.param("apikey",checkApiKey);
parentRouter.use("/api/:apikey",apiRouter);

Update
I see that your focus is on getting the requested route after the API key, which is variable according to the user. This you can accomplish easily with a parent router, like so:
var parseUserApiRoute = function(req, res, next) {
    // req.path contains the URL after /api/:apikey
    // e.g. For a request to /api/abcdef/this/is/my/route, req.path will be /this/is/my/route
    res.send("Path: "+req.path);
}
var checkApiKey = function () {...};

var apiRouter = express.Router();
apiRouter.get("*",parseUserApiRoute);

parentRouter.param("apikey",checkApiKey)
parentRouter.use("/api/:apikey",apiRouter);

Comment: @errhunter Sorry, I misunderstood what you were trying to do - you have a very interesting use case! In this case, you can still use a parent router to simplify catching the URL that the user has entered after their API key. I have updated my answer with an example. I would still suggest moving the key out of the URL for the same reasons as above.

How to catch subsequent API signatures?


What's the correct data structure for 2-prop sorted list?

Question: I am writing a simple handless ui framework, in which i need to dispatch all the message by my own.
Every widget has a list of child, which has two properties: paint order(the order to recieve paint message) and other-event order(the order to receive message other than paint).
void Widget::sortChildWidgets( SortMode mode )
{
    if (mode == kSortByPaint) {
        //return true if should precede otherwise return false;
        m_children.sort([&](Widget* pw1, Widget* pw2) ->bool {
            if (pw1->getPaintOrder() < pw2->getPaintOrder()) {
                return true;
            } else {
                return false;
            }
        });
    }

    if (mode == kSortByEvent) {
        //return true if should precede otherwise return false;
        m_children.sort([&](Widget* pw1, Widget* pw2) ->bool {
            if (pw1->getEventOrder() < pw2->getEventOrder()) {
                return true;
            } else {
                return false;
            }
        });
    }
}

Because widget could change its order at runtime, i need to resort everytime i dispatch any message, which definitly is too bad.
My problem: Is there any better data structure rather than std::list to free me from sort every time dispatch message, Or i need to maintain too std::list and make it sorted everytime i insert an child to a widget?
Answer: The recommended data-structure for keeping items ordered is an std::set. You can provide a custom predicate for the ordering, and thus keep the same items in multiple sets with different ordering.
If you need more performance, you could look into Boost.Multi-Index. This is a library designed to keep multiple views of the same data-set with different orderings.
Note that neither of these data-structure assume that the value of a key does not change once it has been added.
Comment: In this project, I could not use heavy-library such as boost. Maybe, I would need to maintain one std::list, two std::set!!!
Comment: @Jichao: Are you sure that you need an `std::list`? An `std::vector` is almost always more efficient.


How to manage the order of the modules execution?

Question: I have a 2 modules which has javascript files modify the height of an element (through jquery).
module one set the height to 100px
module two set the height to 200px
I seems like the module one is fired after module two. I need the js file of module two to be fired after the js file of module one. This is to change the weight of the js files.
I included the js file in the module_one.info file like this:
scripts[] = js/myfile.js
Can I do this?
Should I add the js files in myTheme.info ?
Answer: You can change the module weight in your system table in the data base. This will reorder the execution of the modules and also the inclusion of js.
You can update the weight via myphp admin or you can do it via a custom modules .install file in a hook_install. for example:
db_update('system')
 ->fields(array(
   'weight' => 10,
 ))
 ->condition('name', 'module_name')
 ->execute();

Replace module_name with the name of the module you would like to delay.
Clear all cache afterwards
Comment: although that tends to make the JS execute in the correct order, it's not guaranteed. See http://drupal.stackexchange.com/a/1678/633


Como mostrar quantidade de vendas por forma de pagamento por mes no SQL Server

Question: Estou tendo o seguinte resultado:
Mes | QtdPorMes
 1  |    124
 2  |    102
 3  |    84
 4  |    32

Precisaria que ficasse assim:
 Mes |   Boleto  | Cartão  | Total
  1  |     100   |   24    |  124
  2  |     82    |   20    |  82
  3  |     34    |   50    |  84
  4  |     12    |   20    |  32

Quais cláusulas eu deveria usar?
A tabela é fictícia, apenas para estudos.
SELECT
    MONTH(DataVenda) AS 'Mes',
    COUNT(FormaPagamento) AS 'QtdPorMes'
FROM
    vendas
WHERE
    DataVenda > '2018-01-01'
GROUP BY MONTH(DataVenda)
ORDER BY MONTH(DataVenda);

Comment: Qual estrutura da tabela vendas? E como você diferencia a forma de pagamento?
Comment: A estrutura da tabela vendas: CodVenda INT, DataVenda DATE, ValorVenda DECIMAL, FormaPagamento INT. (FormaPagamento 1 = Boleto, 2 = Cartão)
Comment: Gabriel, isso é uma informação relevante que deveria estar na pergunta. Você pode editá-la e incluir =)
Answer: Montei um exemplo, veja se te atende:
create table tempVendas
(
    DataVenda datetime,
    FormaPagamento varchar(100)
)

insert into  tempVendas values ('2018-01-01', 'Boleto')
insert into  tempVendas values ('2018-01-01', 'Boleto')
insert into  tempVendas values ('2018-01-01', 'Boleto')
insert into  tempVendas values ('2018-01-01', 'Cartão')
insert into  tempVendas values ('2018-01-01', 'Cartão')

insert into  tempVendas values ('2018-02-01', 'Boleto')
insert into  tempVendas values ('2018-02-01', 'Cartão')
insert into  tempVendas values ('2018-02-01', 'Cartão')
insert into  tempVendas values ('2018-02-01', 'Cartão')

insert into  tempVendas values ('2018-03-01', 'Boleto')
insert into  tempVendas values ('2018-03-01', 'Boleto')
insert into  tempVendas values ('2018-03-01', 'Boleto')
insert into  tempVendas values ('2018-03-01', 'Cartão')
insert into  tempVendas values ('2018-03-01', 'Cartão')
insert into  tempVendas values ('2018-03-01', 'Cartão')
insert into  tempVendas values ('2018-03-01', 'Cartão')
insert into  tempVendas values ('2018-03-01', 'Cartão')

SELECT month(dataVenda) [Mes],
count(case when FormaPagamento = 'Boleto' then FormaPagamento end) 'Boleto',
count(case when FormaPagamento = 'Cartão' then FormaPagamento end) 'Cartão',
count(FormaPagamento) Total
FROM tempVendas
group by month(dataVenda)
order by month(dataVenda)

http://sqlfiddle.com/#!18/0c28a/2
Answer: Você conseguiria o resultado esperado com a seguinte consulta:
SELECT
    MONTH(DataVenda) AS 'Mes',
    (SELECT COUNT(*) FROM vendas V2 WHERE V2.DataVenda > '2018-01-01' AND MONTH(V2.DataVenda) = V1.DataVenda AND FormaPagamento = 1) as 'Boleto',
    (SELECT COUNT(*) FROM vendas V2 WHERE V2.DataVenda > '2018-01-01' AND MONTH(V2.DataVenda) = V1.DataVenda AND FormaPagamento = 2) as 'Cartão',
    COUNT(FormaPagamento) AS 'QtdPorMes'
FROM
    vendas V1
WHERE
    DataVenda > '2018-01-01'
GROUP BY MONTH(DataVenda)
ORDER BY MONTH(DataVenda);

Porém assim você precisa executar subconsultas. Se possível, sugiro usar o código abaixo e montar o QtdPorMes total via código:
SELECT
    MONTH(DataVenda) AS 'Mes',
    FormaPagamento,
    COUNT(FormaPagamento) AS 'QtdPorMesForma'
FROM
    vendas V1
WHERE
    DataVenda > '2018-01-01'
GROUP BY MONTH(DataVenda), FormaPagamento
ORDER BY MONTH(DataVenda);

Assim, o retorno seria algo como abaixo:

 Mes | FormaPagamento | QtdPorMesForma
  1  |         1      |       100
  1  |         2      |       24
  2  |         1      |       62
  2  |         2      |       20
  3  |         1      |       34
  3  |         2      |       50
  4  |         1      |       12
  4  |         2      |       20

Comment: Na segunda forma o resultado seria 3 colunas e 2 linhas (boleto/cartão) para cada mes? Algo assim:
`Mes | Forma | Qtd
  1   |  Boleto |  5
  1   |  Cartão |  8
  2   |  Boleto |  4
  2   |  Cartão |  12`
Comment: editei a resposta, veja se ficou claro ;)
Answer: Você pode fazer assim:
SELECT
    MONTH(DataVenda) AS 'Mes',
    Sum( CASE WHEN FormaPagamento = 1 THEN 1 ELSE 0 END) AS 'Boleto',
    Sum( CASE WHEN FormaPagamento = 2 THEN 1 ELSE 0 END) AS 'Cartão',
    Sum( CASE WHEN FormaPagamento <> 1 AND FormaPagamento <> 2 THEN 1 ELSE 0 END) AS 'Outros',
    COUNT(*) AS 'QtdTotal'
FROM
    vendas
WHERE
    DataVenda > '2018-01-01'
GROUP BY MONTH(DataVenda)
ORDER BY MONTH(DataVenda);

Note que eu já incluí uma coluna adicional 'Outros' para o caso de a forma de pagamento ser diferente de 1 e 2.
O problema é que a cada nova forma de pagamento que você precisar incluir como coluna, esse select precisará ser alterado.


maven scoverage check for lines/branches not covered by unit tests

Question: I am quite new to maven scoverage plugin which is the preferred code coverage tool in the team that I am working with.
I am trying to generate reports for test coverage using the following command:
 mvn scoverage:report

It gives me a detailed report showing class name and code coverage both in terms of lines of code and branches but it does not show which lines/branches of code are not covered by unit tests.
Is there an option with scoverage that I can use to display those lines or generate as part of report?
I have tried googling but haven't been able to find anything helpful for scoverage
Answer: So Finally I figured it out, all i needed to do was put a small change in plug-in section for scoverage of my pom file and set highlighting to true
Before:
<plugin>
                <groupId>org.scoverage</groupId>
                <artifactId>scoverage-maven-plugin</artifactId>
                <version>${scoverage.plugin.version}</version>
                <configuration>
                    <minimumCoverage>80</minimumCoverage>
                    <failOnMinimumCoverage>true</failOnMinimumCoverage>
                    <aggregate>true</aggregate>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <phase>prepare-package</phase>
                    </execution>
                </executions>
            </plugin>

After:
<plugin>
                <groupId>org.scoverage</groupId>
                <artifactId>scoverage-maven-plugin</artifactId>
                <version>${scoverage.plugin.version}</version>
                <configuration>
                    <highlighting>true</highlighting>
                    <minimumCoverage>80</minimumCoverage>
                    <failOnMinimumCoverage>true</failOnMinimumCoverage>
                    <aggregate>true</aggregate>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <phase>prepare-package</phase>
                    </execution>
                </executions>
            </plugin>


jQuery isn't executing one event, but executes 4 identical ones

Question: It's a large layout, so I will just post the parts that are linked to the jQuery and HTML (full site at http://www.gronge.com/index3.php). It all works fine, except the About link changes back to .navBarActive in Firebug inspection but does not visually change. I am new to web design, and this has been my first big issue so far.
jQuery
$(document).ready(function() {
    $("li.navBarNormal").click(function () {
        $("li.navBarActive").removeClass("navBarActive").addClass("navBarNormal");
        $(this).removeClass("navBarNormal").addClass("navBarActive");
    })
});

HTML

About

Subscribe

News

Updates

Contact

Comment: I would suggest removing the navBarNormal class and simply pass the "Active" class to the current item.  Then bind the click event to all the ListItems.  That way you are not messing with the class you are using in the selector.
Answer: It's because you are not setting the event listener on the #navLinkAbout node, as this node does not have a navBarNormal class to start with.
My suggestion is to use a better selector for setting the listener, like #navLinks li.
$(document).ready(function() {
    $("#navLinks li").click(function () {
        $("li.navBarActive").removeClass("navBarActive").addClass("navBarNormal");
        $(this).removeClass("navBarNormal").addClass("navBarActive");
    })
});

Comment: You my friend, are the greatest!
Answer: try this: http://jsfiddle.net/treyeckels/DgQfw/
Change the event trigger to "li.liNav". That will apply the event handler to all the links. Then do your add/remove action on this (that which was clicked), traverse and find the siblings and do their add/remove actions.
$(document).ready(function() {
$("li.liNav").click(function() {
    $(this).removeClass("navBarNormal").addClass("navBarActive").siblings().removeClass("navBarActive").addClass("navBarNormal");
}) });


Como não permitir fechar o modal do twitter-bootstrap clicando fora da área?

Question: Não sei se tem como, mas estou precisando bloquear o fechamento do modal do twitter-bootstrap quando o usuário clica fora da área do elemento, só permitindo fechar o mesmo ao clicar nos botões de fechamento.
Comment: Só para complemento da pergunta: o modal a qual você se refere é esse aqui? http://getbootstrap.com/javascript/#modals
Answer: Segundo a documentação, basta colocar o atributo data-backdrop="static" no seu modal:

    ...

Comment: Já conferi na documentação que é isso mesmo. +1
Comment: Simples assim, me ajudou mesmo e bastava eu ter lido um pouco mais a documentação. E eu achando que seria complicado. Dos males o menor.


Beta confidence intervals in transformed linear regression

Question: Let's say I have a model:
$$Y_i = \beta_0 \beta_1^{X_i} \epsilon_i$$
(note: This is slightly different than the more common example case of $Y_i = \alpha e^{\beta x_i}\epsilon_i$.)
I can take the log of $Y$:
$$\log Y_i = \log\beta_0 + X_i\log\beta_1 + \log\epsilon_i$$
Assuming all the usual assumptions around the errors, etc, hold, I can estimate this with simple linear regression. However, I only get an estimate, and therefore a confidence interval, for $\log\beta_1$, not $\beta_1$ itself.
Can I backtransform with $\hat{\beta_1} = \exp(\widehat{\log\beta_1})$? If so, for a  confidence interval for $\hat{\beta_1}$, would I just transform the endpoints of the interval?
Answer: Actually, the interval carries over just fine. The transformation is monotonic; the probability statement that applies on the log-scale transforms directly to the original scale, so as long as the assumptions under which the original interval was computed do apply, then it works as an interval for the original population parameter after transformation.
It's the estimate that may be problematic (but may be okay, depending on what you want). Note that $E[\exp(X)]\neq \exp[E(X)]$ if $\sigma_X^2>0$. If the log-scale estimate is unbiased, the transformed estimate is biased.
If you're happy to have an estimate that's median-unbiased, then the back-transformed estimate is also okay, for the same reason that the interval works.
If you seek mean-unbiasedness there are some choices. For example, if you're prepared to assume a normal distribution on $\hat\beta$ you can unbias it by using the properties of the lognormal. Alternatively, you can use a Taylor expansion to get an approximate adjustment (details are also in a number of posts on this site). If the standard error of the estimate is small, it won't matter much. There are other things that are done.
Answer: Your $\hat{log(\beta)}$ estimator is asymptotically normal. So, use delta method to derive asymptotic distribution (and confidence intervals) of a function of the estimator:
Let $\gamma=log(\beta)$ and $h(\gamma)$ is some differentiable function s.t. $h'(\gamma)\not=0$. Under some basic conditions
$\sqrt{n}(\hat\gamma-\gamma)\rightarrow N(0, V)$
Then
$\sqrt{n}(h({\hat\gamma})-h(\gamma))\rightarrow N(0, (h'(\gamma))^TV(h'(\gamma)))$

In your case:
$h(\gamma)=\begin{bmatrix} e^{\gamma_0} \\ e^{\gamma_1} \end{bmatrix}=\begin{bmatrix} \beta_0 \\ \beta_1 \end{bmatrix}$
$h'(\gamma)=\begin{bmatrix} e^{\gamma_0} & 0 \\ 0 & e^{\gamma_1} \end{bmatrix}$
$V=\begin{bmatrix} \sigma_{\gamma_0}^2 & \sigma_{\gamma_0\gamma_1} \\ \sigma_{\gamma_0\gamma_1} & \sigma_{\gamma_1}^2 \end{bmatrix}$
$\sqrt{n}({\hat\beta}-\beta)\rightarrow N(0, \begin{bmatrix} e^{2\gamma_0}\sigma_{\gamma_0}^2 & e^{\gamma_0+\gamma_1}\sigma_{\gamma_0\gamma_1} \\ e^{\gamma_0+\gamma_1}\sigma_{\gamma_0\gamma_1} & e^{2\gamma_1}\sigma_{\gamma_1}^2 \end{bmatrix})$
Finally, you can estimate the s.e. of $\hat\beta_1$ as $e^{\hat\gamma_1}\hat\sigma_{\gamma_1}/\sqrt{n}$. So, the relevant confidence interval is
$CI_{95\%}(\hat\beta_1)=[e^{\hat\gamma_1}-z_{97.5\%}e^{\hat\gamma_1}\hat\sigma_{\gamma_1}/\sqrt{n}, e^{\hat\gamma_1}+z_{97.5\%}e^{\hat\gamma_1}\hat\sigma_{\gamma_1}/\sqrt{n}]$
where $z_{0.975}$ is $97.5\%$ quantile of the standard normal distribution.
Answer: Here's a simple example with simulated data where $\beta_0=3$ and $\beta_1=2$:
. #delimit;
delimiter now ;
. clear;

. set seed 10011979;

. set obs 10000;
obs was 0, now 10000

. gen x = rnormal();

. gen y = 3 * (2^x) * rnormal(1,.25);

. gen lny = ln(y);

. reg lny x;

      Source |       SS       df       MS              Number of obs =   10000
-------------+------------------------------           F(  1,  9998) =60377.64
       Model |  4697.83357     1  4697.83357           Prob > F      =  0.0000
    Residual |  777.919401  9998  .077807502           R-squared     =  0.8579
-------------+------------------------------           Adj R-squared =  0.8579
       Total |  5475.75297  9999   .54763006           Root MSE      =  .27894

------------------------------------------------------------------------------
         lny |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           x |   .6883164   .0028012   245.72   0.000     .6828254    .6938074
       _cons |   1.065971   .0027894   382.15   0.000     1.060503    1.071438
------------------------------------------------------------------------------

Using the delta method and the fact that the derivative of $\exp$ is itself, you know that
$$SE(exp (\beta_1)) = \exp (0.6883164) \cdot 0.0028012 = 0.0055754 $$
This is the standard error that Stata calculates with nlcom:
. nlcom (exp_b1:exp(_b[x]));

      exp_b1:  exp(_b[x])

------------------------------------------------------------------------------
         lny |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
      exp_b1 |   1.990362   .0055755   356.98   0.000     1.979434    2.001289
------------------------------------------------------------------------------

To get the 95% CI, it's the usual formula:
$$1.990362 \pm 1.96 \cdot 0.0055755 = [1.979434,2.00129] $$
We can also use non-linear least squares to fit this model without transforming it:
. nl (y = {b0=1}*{b1=1}^x), nolog;
(obs = 10000)

      Source |       SS       df       MS
-------------+------------------------------         Number of obs =     10000
       Model |   235659.16     2   117829.58         R-squared     =    0.9386
    Residual |  15404.5955  9998   1.5407677         Adj R-squared =    0.9386
-------------+------------------------------         Root MSE      =  1.241277
       Total |  251063.755 10000  25.1063755         Res. dev.     =  32699.58

------------------------------------------------------------------------------
           y |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         /b0 |   2.996304   .0128667   232.87   0.000     2.971083    3.021525
         /b1 |   1.994413   .0048325   412.71   0.000     1.984941    2.003886
------------------------------------------------------------------------------

This gives similar results.
Answer: Calculate a simple linear regression and get values a couple of values. Try 1 + 2x. Then take the exponent of the values. That's what the values should be. Now try calculating the 1 + exp(2)x.
In R it would be:
exp( 1 + 2 * 1:3)
# versus
1 + exp(2) * 1:3

It should be pretty obvious these won't be equal. Given that finding it should be clear that you don't even back transform the beta coefficient let alone make a CI around it. The back transformed coefficient is useless.
What you can do is use the equation to generate points in the linear function and a CI around that function within the transform space and then back transform those final values.


Run sieve when movin messages

Question: I have sieve working for incoming messages. I would also love to run sieve for delivered messages that are being moved between mailboxes on the server (for the same account).
For example. I have mail history spanning a decade or two. Many mail clients have troubles with mailboxes of that size. I want to split it into years/months. I know Thunderbird can do that automatically but many other clients can not. Specifically, I'm not aware of any iOS mail client that can do that. Anyway, I'd like to move any message that enters Archives mailbox to be further filtered into Arthives// mailbox.
I use Dovecot 2 as my IMAP server. How can I do that?
Comment: @anx As far as I can tell it has to be ran manually. I was looking for a way to run sieve on each message entering my `Archive` mailbox to further divert it to, say, `Archive//` mailbox.
Answer: Triggering actions on IMAP commands is one of the main applications of the IMAPSieve extension, as proposed in RFC6785 and implemented in Dovecot 2.2.24+. What you have to do is roughly this:

add imap_sieve to your dovecot mail_plugins
add sieve_imapsieve to your dovecot sieve_plugins
add your filter to imapsieve_mailbox1_before and filter IMAP actions in imapsieve_mailbox1_causes (COPY)
add a filter by mailbox, so you only redirect messages from specific folders (my guess: all folders which have per-date-range subfolders)
use fileinto in your IMAP-triggered script to move the message to a different folder than the one the user moved/copied to

Special cases / additional consideration required:

IMAP APPEND
is the archive folder splitting logic shared between incoming mails and manually moved mails? it IS possible to share the script, but doing so might not be worth the additional script complexity
Comment: I know about this feature. I use it for spam training. However, there's a complication. It seem this is applicable to all users on the server. Is it possible to scope it only to some users? Preferably by opt-in from the users themselves.
Comment: @PointlessOne You can accomplish 4. with `mailboxexists`. Any user that creates a folder like `Archive/2019-05` (unfortunately, I did no figure out how to use `:regex` there) opts in to have all his new messages in `Archive` moved into automatically created folders of that scheme.

Run sieve when movin messages


Dir columns coming by default while querying parquet files in apache drill 1.20 versions

Question: In the latest version of drill, the dir columns are coming by default when giving a 'select *' on a parquet file. Is there a way we can disable them?
The query: 'Select * from dfs.`C:\Sample.parquet` where EmpID <>'null''

The result for the above query is coming as:
dir0 | dir1 | dir2 | dir3 | EmpID

I just need the EmpID column. But the dir columns are coming by default. Tested in drill 1.20.1 and 1.20.2 as well. Same resultset.
Comment: If you only want one column, then don't use `Select *`. What happens when you run `Select EmpID`?
Comment: Thanks for the response @OneCricketeer. That was just for sample. The column would be dynamic in that parquet file. I need to use '*' to get the entire column set.
Answer: the issue is fixed. If I changed the '\' to '/', then the result set is coming without any additional columns. Turns out '\' is an escape character in drill, which gives an unexpected result set. Not sure why it was not happening in earlier drill versions.
Hope this helps. :)


How to simplify: $C_{t} = r[a_{t} + \frac{1}{1+r} * \sum_{j=0}^{\infty} (\frac{1}{1+r})^j * E(w_{t+j})]$

Question: I have to find C_t (Optimal Consumption for each period). Thank you!
$$C_{t} = r[a_{t} + \frac{1}{1+r} * \sum_{j=0}^{\infty} (\frac{1}{1+r})^j * E(w_{t+j})]$$
Where,
$$w_{t+j} = \begin{cases} w + \Delta &, j=0,2,4... \\
                     w - (1+r)*\Delta &, j=1,3,5....\end{cases}$$
Comment: There is still much unclear. Is left-hand side of last line $w_j$? Is $w$ in right-hand side of this line some constant or previous value like in Abdoul comment? Is $t$ non-negative integer? If $E(w_{t+j})$ is expected value, then what are averaging conditions?
Comment: @IvanKaznacheyeu In this case $w_{t+j}$ is not random since it just alternates between two values. The expected value was given in the initial problem. Since there is no randomness is it possible to just find the infinite sum in some way? When w is constant in each period, I just pull it out of the sum but now it changes in each period.
Comment: I would really appreciate it if you can help. I have to simplify this equation and find optimal consumption for each period t.
Comment: I used the average of the two values of w and plugged it in instead of E(W) but I am not sure if that's a correct way to do it.
Comment: [Please do not use pictures for critical portions of your post.](https://math.meta.stackexchange.com/a/34123/42969)  Pictures may not be legible, cannot be searched and are not view-able to some, such as those who use screen readers. – For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: I got $$C_{t} = ra_{t} + w - (r\Delta)/(2)$$
Comment: Is $\omega_{t+j}$ linked to $W$? And dit $E(.)$ stand for expectation? Is $\omega_{t+j}$ a random variable?
Comment: @AbdoulHaki Yes, I am sorry. w is a wage for each period. E is an expectation. In even periods wage increases by delta, and in odd periods the wage decreases by (1+r)*delta. I would really appreciate it if you could help me with this.
Comment: You meant $w_j = \left\{\begin{array}{ll}
w_{j-1} + \Delta & j = 0, 2, 4,\dots\\
w_{j-1} - (1+r)*\Delta & j = 1, 3, 5,\dots\\
\end{array}\right.$ ?
Comment: @AbdoulHaki w stays the same in this case, it is not changing.
Comment: w stays the same for all periods j. The equation is a general case where w can change in each period. But for this problem, the assumption is that if j is 0,2,4.. wage increases by delta and if j is 1,3,5... wage decreases by -(1+r)*delta.
Comment: When $w_j$ is constant I am getting $C_t = r*a + w$. But if it is changing do I have to plug the weighted average of w into the equation?  $1/2 *(w+\Delta) + 1/2*(w-(1+r)*\Delta)$
Comment: As I understand, there is some infinite sequence $w_j$ such that $w_j=w_0=w+\Delta$ for even $j$ and $w_j=w_1=w-(1+r)\Delta$ for odd $j$. There is non-negative integer index $t$. Then sequence $C_t$ is defined by $C_t=r\left(a_t+\sum_{j=0}^{\infty} \frac{1}{(1+r)^{j+1}} E(w_{t+j})\right)$. $w_{t+j}$ is not random variable it is just one of sequence $w_j$ terms. Then what is $E(w_{t+j})$? If $w_{t+j}$ is random variable, then what is source of this randomness?
Comment: If sum is really $S=\sum_{j=0}^{\infty} \frac{1}{(1+r)^{j+1}} w_{t+j}$ then it can be found. First step: divide sum into even $j=2m$ and odd $j=2n+1$. $S=\sum_{m=0}^{\infty} \frac{1}{(1+r)^{2m+1}} w_{t+2m}+\sum_{n=0}^{\infty} \frac{1}{(1+r)^{2n+2}} w_{t+2n+1}$. Second step: Use $w_{t+2m}=w_t$ and factor out. $S=\frac{w_t}{1+r} \sum_{m=0}^{\infty} \frac{1}{(1+r)^{2m}}+\frac{w_{t+1}}{(1+r)^2}\sum_{n=0}^{\infty} \frac{1}{(1+r)^{2n}}$. Third step: use infinite geometric sequence sum and factor out. $S=\left(\frac{w_t}{1+r} + \frac{w_{t+1}}{(1+r)^2}\right) \frac{(1+r)^2}{(1+r)^2-1}$.
Comment: Result for $S$ can be written as $S=S_0$ for even $t$ and $S=S_1$ for odd $t$, where $S_0$ is value at $t=0$ and $S_1$ is value at $t=1$.
Answer: I suppose that $\omega$ is not a random variable but just a sequence of real value and answer you question.
\begin{align}
\sum_{j=0}^{\infty} \frac{1}{(1+r)^j} * E(w_{t+j}) &= \sum_{j=0}^{\infty}\frac{1}{(1+r)^j}\left[(\omega) +(\omega - (1+r)\Delta) + (\omega+\Delta) + (\omega - (1+r)\Delta)  + \dots \right]\\
&= \omega + \sum_{j=1}^{\infty}\frac{1}{(1+r)^{2j-1}}\left[\omega - (1+r)\Delta\right] + \sum_{j=1}^{\infty}\frac{1}{(1+r)^{2j}}\left[\omega+\Delta\right]\\
&= \omega + \frac{\omega(1+r)}{(1+r)^2-1} - \frac{\Delta(1+r)^2}{(1+r)^2-1} + \frac{\omega+\Delta}{(1+r)^2-1}\\
&=\frac{\omega(1+r) + (\omega+\Delta)(1+r)^2 + \Delta}{(1+r)^2 - 1}
\end{align}
Then, you get
\begin{align}
C_t = r\left[a_t + \frac{\omega + (\omega+\Delta)(1+r) + \frac{\Delta}{1+r}}{(1+r)^2 - 1}\right]
\end{align}


Output in two-part Fractional Response Model (FRM) package incorrect?

Question: I was experimenting with the Fractional Response Model (FRM) package, and decided to replicate the results using the base GLM package to better understand the theory. I am able to replicate the results, however, I would have expected the frm$yhat2P output to be different.
Consider the case where we are estimating a two-part fractional regression model with y = 1 as the relevant boundary value, using a probit binary link function and a logit fractional link function. I have generated some toy data to work with below. We create this function using the frm package as such:
set.seed(1337)
N <- 250
u <- rnorm(N)
X <- cbind(rnorm(N), rnorm(N))
dimnames(X)[[2]] <- c("X1", "X2")
ym <- exp(X[, 1]+X[, 2]+u)/(1+exp(X[, 1]+X[, 2]+u))
y <- rbeta(N, ym*20, 20*(1-ym))
y[y > 0.9] <- 1

temp <- frm(y, X, linkbin="probit", linkfrac="logit", type="2P",
             inf=1)
df2 <- as.data.frame(round(temp$yhat2P, 8))
                 # store results for future reference.

The first-part of the frm model above can be replicated using glm in the following way:
X2 <- as.data.frame(cbind(X,y))
X2$y_binary <- ifelse(y == 1, 1, 0)
temp2 <- glm(y_binary ~ X1+X2, family = binomial("probit"),
              data = X2) # Generates the likelihood of y = 1.
summary(temp2)
    # Produces identical coefficients etc. as the FRM package
      # first-part.

The second-part of the frm model above can be replicated using glm in the following way:
X3 <- X2[X2$y_binary!=1,]
temp3 <- glm(y~X1+X2, family=quasibinomial("logit"), data = X3)
   # this generates the fractional response for y[0,1).
summary(temp3)
    # Produces identical coefficients etc.
    # as the FRM package second-part.

Finally, replicating the frm temp$yhat2P results (df2 produced above), i.e., the overall fitted mean values using glm can be done as such:
test <- as.data.frame(round(predict(temp2,newdata=X2,
          type = "response"),8)) # 1st part.
names(test)[1] <- "first_part"
test$second_part <- round(predict(temp3,newdata=X2,
                    type = "response"),8) # 2nd part.
test$final_part <- round(test$first_part*test$second_part, 8)
                  # final step.

The formula to generate these results is essentially the following (first_part*second_part):
$$
E(y|x) = Pr[y = 1|x]*E[y | x, y[0,1)]
$$
This output, however, is not consistent with how I interpret the frm theory, as found in Ramalho et al's 2011 paper (the author of the package) "Alternative estimating and testing empirical strategies for fractional regression models" and other supporting papers. I would expect the output should align with the following formula instead (for this particular case):
$$
E(y|x) = E[y | x, y[0,1)]*Pr[y[0,1) | x] + E[y | x, y = 1]*Pr[y = 1|x]
$$
Which I believe is produced using glm as in the following way:
test$what_I_expect <- round(test$second_part*(1-test$first_part)
                           + (1*test$first_part), 8)

Why is the frm$yhat2P output not consistent with the formula above? Am I misunderstanding the theory behind two-part FRM models? Or is it possible I am misinterpreting the frm package output? Any guidance and/or clarity would be greatly appreciated.
Comment: I don't know, and this is a little too much for me to dig into right now, but would digging through the [source code](https://github.com/cran/frm/blob/master/R/frm.R#L567-L568) help?
Answer: I am aware of this bug. Your formula is correct and in fact I have used it in my JPA 2010 paper. However, later on, when constructing the frm package, I implemented the formula for the case where the observed boundary value is 0 and forgot to adapt it to the case you are considering (by the way, I promptly answered your 2 previous emails regarding this question).


How can I get a p-value for a distribution that isn't normally distributed?

Question: I have four independent trials of a random variable. I have run a Shapiro-Wilk test on it and it is not normally distributed.
I have two different images of a peak. The background is flat with a little bit of noise but no large trends. I am subtracting the two peaks and seeing if their difference is significant or if they are the same.
What is the best way to quantify the statistical significance of the difference region?
EDIT: I have clarified my problem. I am trying to see if the region of interest between the dashed lines (where my two peaks where) is significantly different from the rest of the image.
Comment: "I want to know if my peak above the threshold area in Run 4 is just due to noise or if it is a signal." The problem here is what exactly do you mean by "noise", and what constitutes a "signal"  in your application. Some use the term "noise" for what is normally distributed, in which case your data wouldn't be "noise" anyway (in fact peaks could lead to rejection of normality). The thing is that a peak "stands out" *relative to a model assumption* such as normality, so such an assumption needs to be provided.
Comment: Also observations within runs don't look independent, although I'm not sure as there's no information about potential smoothing. In which case a model for dependence would be needed.
Comment: @ChristianHennig I do not know if there is an alternative way of devising a hypothesis.

I am considering making a histogram of the noise outside of the region of interest and doing a chi-squared test with the noise/signal inside the region to find the goodness of fit. Would this work?
Comment: The goodness of fit of what?  What is your hypothesis there?
Comment: So I want to check if the data within the region of interest has the same distribution as the data outside of it. My hypothesis is that if the difference between the two peaks is significant then the data in the region of interest (where my peaks were) will have a different distribution to that of the background.
Comment: Not sure I understand this. Am I right that the peaks are in one region of the data space ("region of interest") and the "background" in another? But then any distribution of the "background" can be combined with any distribution in the "region of interest" to form a distribution together. The background cannot tell you how data outside the background should look like. Apart from the dependence issue, that is.
Comment: Yes, the peaks are in a smaller region of the whole image. By background, I mean the area outside of the peak region. I was thinking of comparing the distribution of the background to the distribution of the region of interest to see if there is a significant difference. My thought process is that the region of interest would have the same distribution as the background if the difference between the two peaks is not significant. Does this make sense or am I making poor assumptions?
Comment: The peaks are extreme and the background isn't. They are in different regions of the data space, so they can't have the same distribution. That would mean that they can take the same values with the same probability, which obviously can't be the case if they take systematically different values. (What you mean is probably that the *overall* distribution is the same, but as written before, you can put together any two distributions on disjoint domains and get a legitimate distribution on the overall space.)
Answer: Welcome to the site.
A "peak" does not have a p-value.  To get a  p value, you need a hypothesis and a hypothesis test. You haven't stated one and I don't think you actually need one here. What you need to do is more precisely define peak (ideally, you would have done this beforehand; you should not let the actual results affect your definition). So for instance, you might say:

A peak is a value that is higher than both the preceding and
succeeding variable by at least XXX.

I am not saying this is what you should use, it's just an example of the sort of thing I mean.
Then you can say whether or not you have peaks, and p values never come into it.
Comment: Thank you. I am asking about p-values because I want to know if my peak above the threshold area in Run 4 is just due to noise or if it is a signal. I am not sure how to 'combine' it with the other Runs where there isn't a big peak. This is why I want to ask about p values.
Comment: P values won't help you answer that question.
Comment: Would comparing the distribution of the noise outside the region of interest (I am only concerned with the region in between the dashed lines) and the noise within the region with a chi-squared test work?
Comment: If you want to test that, you need to define the process that is generating the "signal".


$f:[a,b] \to \mathbb{R}$, differentiable, not constant with $f(a) = f(b)$ has points s.t. $f(x) = f(y)$ and $f'(x) \neq f'(y)$

Question: Is this statement true?
Let $f:[a,b] \to \mathbb{R}$ be a non constant differentiable such that $f(a) = f(b)$, then there are numbers $x,y \in [a,b]$ such that $f(x) = f(y)$, but $f'(x) \neq f'(y)$.
If yes, could someone give me a hint on how to prove it?
Answer: Assume $f(t)>f(a)$ for some $t\in [a,b]$.
Then $f$ attains its global maximum at some $c\in(a,b)$.
Let $d=\max(f^{-1}(f(a))\cap [a,c])$ be the greatest number below $c$ where the function has the same value as at $a$ (and $b$). Then by the MVT, for some $x\in(d,c)$, we have $f'(x)=\frac{f(c)-f(a)}{c-d}>0$ and by choice of $d$,  we have $f(a)<f(x)<f(c)$.
By the IVT, the set $Y=f^{-1}(f(x))\cap[c,b]$ is non-empty and closed.
Let $y=\min Y$. Then $f(y)=f(x)$ and $f'(y)\le 0< f'(x)$.
A symmetric argument applies if $f(t)<f(a)$ for some $t\in[a,b]$.
Comment: Nothing in OP's question says that $f'$ is continuous, so unless you assume it you should not use the MVT like that.
Comment: @SergeBallesta Differentiability implies continuity.
Comment: But not of the derivative...
Comment: Still, your answer does not use continuity of $f'$ anywhere. Thanks!
Answer: there are points on a curve symmetric with respect to y axis, with equal values while going uphill and while going downhill.
Comment: Yes I realized this, but stil couldn't find a point with positive derivative at one side and negative on the other


Python recursion permutations

Question: I'm having trouble trying to make a permutation code with recursion. This is suppose to return a list back to the use with all the possible position for each letter.
For the word cat, it is suppose to return ['cat','act',atc,'cta','tca','tac'].
So far I have this code:
def permutations(s):
    lst=[]
    if len(s) == 1 or len(s) == 0 :
        # Return a list containing the string, not the string
        return [s]
    # Call permutations to get the permutations that don't include the
    # first character of s
    plst = permutations(s[1:])
    print(plst)
    for item in plst:
        print (item)
        plst= permutations(s[1+1:])

         # Now move through each possible position of the first character
        # and create a new string that puts that character into the strings
        # in plst
        for i in range(len(s)):
            pass
            # Create a new string out of item
            # and put it into lst
        # Modify
    for item in lst:
        print(index)

There are steps there but im not sure how to use them
Comment: I am not sure why you are writing this, but you can also use [itertools.permutations()](http://docs.python.org/2/library/itertools.html#itertools.permutations). It uses `yield` so it does not have to construct the whole list.
Comment: I haven't learn how to use yield yet. so i was wondering if there was a way to do this code with out using yeild
Comment: Why don't you check Numpy.. I think it provides these features. Not sure though
Comment: @brianChiem, `itertools.permutations()` use of `yield` is mostly transparent to you, so give it a whirl.  Use `list(itertools.permutations(...)` if you don't plan on iterating over it in a `for` loop.
Answer: You want to do recursion, so you first have to find out how the recursion would work. In this case it is the following:
permutation [a,b,c,...] = [a + permutation[b,c,...], b + permutation[a,c,..], ...]

And as a final condition:
permutation [a] = [a]

So the recursion splits up the list in sublists with one element extracted each time. Then this element is added to the front of each of the permutations of the sublist.
So in pseudo-code:
def permutation(s):
   if len(s) == 1:
     return [s]

   perm_list = [] # resulting list
   for a in s:
     remaining_elements = [x for x in s if x != a]
     z = permutation(remaining_elements) # permutations of sublist

     for t in z:
       perm_list.append([a] + t)

   return perm_list

Does this help?
Comment: so for the z = s without element a does plst = permutations(s[1:]) work for it
Comment: Yes, but you have to do this for every element of s. So the next one (with the 'b' removed) would be `permutations(s[0] + s[2:])`. Note that the 'a' is included in this subset.
Comment: Where's the recursive call? Shouldn't it be `for each t in permutations(z): perm_list.append([a]+t])`?
Comment: @tobias_k: Ah yes, I looked over that! I've corrected it now.
Comment: im not sure what should i put in this part
perm_list.append([a] + t)

i think it is the recursive call but im not sure. i was thinking that i should put permutations(s[1:]) +permutation(s[0])
Comment: It is not the recursive call. That is at `z=permutation(...)`, because  you can see that the function `permutation` is called from itself. The `perm_list` part does not have to be altered.
Answer: Recursively, think about the base case and build from that intuition.

What happens when there's only one character 'c'? There's only one permutation of that element, and so we return a list containing only that element.

How can we generate the next permutation given the last one? Adding an additional letter 'a' at all possible positions in the previous permutation 'c' gives us 'ca', 'ac'.

We can continue building larger and larger permutations by adding an additional character at all possible positions in each earlier permutation.

The following code returns a list of one character if the string has one character or less. Otherwise, for all permutations not including the last character in the string s[-1], we generate a new string for each position where we could include that character and append the new string to our current list of permutations.
def permutations(s):
    if len(s) <= 1:
        return [s]
    else:
        perms = []
        for e in permutations(s[:-1]):
            for i in xrange(len(e)+1):
                perms.append(e[:i] + s[-1] + e[i:])
        return perms

Answer: When you're lost in recursive function, you should draw the call tree. The following version (inspired @Ben answer) keep the input order (if the input is in lexicographic order, the list of permutations will be, '012' -> ['012', '021', '102', '120', '201', '210'].
def permut2(mystr):
    if len(mystr) <= 1:
        return [mystr]
    res = []
    for elt in mystr:
        permutations = permut2(mystr.replace(elt, ""))
        for permutation in permutations:
            res.append(elt + permutation)
    return res

The following version works for strings and lists, notice the reconstruction step is not the same:
def permut(array):
    if len(array) == 1:
        return [array]
    res = []
    for permutation in permut(array[1:]):
        for i in range(len(array)):
            res.append(permutation[:i] + array[0:1] + permutation[i:])
    return res

As an exercice, you should draw call tree of the these functions, do you notice something ?
Answer: You can use a function that iterates an index through the list, and yield a list consisting of the value at the index followed by the permutations of the rest of the list values. Below is an example using features from Python 3.5+:
def permutations(s):
    if not s:
        yield []
    yield from ([s[i], *p] for i in range(len(s)) for p in permutations(s[:i] + s[i + 1:]))

so that list(permutations('abc')) returns:
[['a', 'b', 'c'],
 ['a', 'c', 'b'],
 ['b', 'a', 'c'],
 ['b', 'c', 'a'],
 ['c', 'a', 'b'],
 ['c', 'b', 'a']]

Comment: The genexp looks beautiful!  Terse but still readable
Answer: I know this is a me too, but I think this one might be easier for some folks to understand....

The base case is when the input is just one character.
Setup up a for loop that iterates through each of the letters in the string.
Another for loop recursively permutes through all the other possibilities.
def permute(s):

    out = []

    if len(s) == 1:
        out = [s]
    else:
        for i,let in enumerate(s):
            for perm in permute(s[:i]+s[i+1:]):
                out += [let+perm]
    return out

Answer: def permutations(string_input, array, fixed_value=""):
    for ch in string_input:
        permutations(string_input.replace(ch, ""), array, fixed_value + ch)
    if not string_input:
        array.append(fixed_value)

You can call it by
array = []
permutations("cat", array)
print array

Answer: This is the easiest solution I came up with.
   def permutations(_string):
        # stores all generated permutations
        permutations = []

        # this function will do recursion
        def step(done, remain):
            # done is the part we consider "permutated"
            # remain is the set of characters we will use

            # if there is nothing left we can appened generated string
            if remain == '':
                permutations.append(done)
            else:

                # we iterate over the remaining part and indexing each character
                for i, char in enumerate(remain):
                    # we dont want to repeat occurance of any character so pick the remaining
                    # part minus the currect character we use in the loop
                    rest = remain[:i] + remain[i + 1:]
                    # use recursion, add the currect character to done part and mark rest as remaining
                    step(done + char, rest)
        step("", _string)
        return permutations

You can test it with:
@pytest.mark.parametrize('_string,perms', (
    ("a", ["a"]),
    ("ab", ["ab", "ba"]),
    ("abc", ["abc", "acb", "cba", "cab", "bac", "bca"]),
    ("cbd", ["cbd", "cdb", "bcd", "bdc", "dcb", "dbc"])
))
def test_string_permutations(_string, perms):
    assert set(permutations(_string)) == set(perms)

Answer: The easiest way to do permutations through recursion
is to first imagine a recursion tree for the problem

base case: if we are given an empty list permutation would be [ [] ]
Then we just want to remove an item from the list and add it to all indices of the rest of the list.

eg input : [a,b,c]
first = a
rest = [b,c]
all = [a,b,c] , [b,a,c] , [b,c,a]

Time: O(N!) #This is best since we are creating N! element
Space O(N^2) #N stack frame * N item in per_with_all

Source:
https://www.youtube.com/watch?v=us0cYQXQpxg
def permetutation(arr):
    if len(arr) == 0:
        return [ [] ]
    #We remove 1st item from error as at each level we introduce 1 item
    first_elenment = arr.pop(0)

    #getting permet for all other item
    perm_without_first = permetutation(arr)

    per_with_all = []

    #Add permtution to every index
    for comb in perm_without_first:
        for ind in range(len(comb)+1): #We also wan to add elenment to last so do +1
            all = comb[0:ind] + [first_elenment] + comb[ind:]
            per_with_all.append( all)

    return per_with_all

Answer: These examples codes are really helpful but I found a test case failed when I was doing a code practice on CodeSignal. basically all the given approach here ignoring if there are any duplicates.
Input: s: "ABA"
Output: ["ABA", "AAB", "BAA", "BAA", "AAB", "ABA"]
Expected Output: ["AAB", "ABA", "BAA"]

So, if you see, it has following duplicates in the output:
["BAA", "AAB", "ABA"]

I modified this by bit here
def stringPermutations(s):
        news = s
        if len(news) == 1:
            return [news]
        res = []
        for permutation in stringPermutations(news[1:]):
            for i in range(len(news)):
                res.append(permutation[:i] + news[0:1] + permutation[i:])
        # To Remove Duplicates From a Python List: list(dict.fromkeys(res))
        # To Sort List : sorted()
        return sorted(list(dict.fromkeys(res)))

def main():
    arr = 'ABA'
    print(stringPermutations(arr))

if __name__ == '__main__':
    main()

But this answer is not appropriate as per time complexity. Time complexity with this approach is: o(n^2)
I think the below approach is quite reasonable.
def stringPermutations(string, prefix, permutation_list):
    #Edge case check
    if len(string) == 0:
        permutation_list.append(prefix)
    else:
        for i in range(len(string)):
            rem = string[0:i] + string[i + 1:]
            stringPermutations(rem, prefix + string[i], permutation_list)
    return sorted(list(dict.fromkeys(permutation_list)))
def main():
    permutation_list = []
    print(stringPermutations('aba','', permutation_list))

if __name__ == '__main__':
    main()

Comment: Use `set` for elimination of duplicate values
Answer: def permute(s):
    ch = list(s)
    if len(ch) == 2:
        per = ch[1] + ch[0]
        return [''.join(ch)] + [per]
    if len(ch) < 2:
        return ch
    else:
        return [ init+per for init in ch for per in permute(''.join(ch).replace(init,""))]

Answer: Using generators:
def generate_perm(alist, index, path, result):
    yield path
    for i in range(index, len(alist)):
        yield from generate_perm(alist, i + 1, path + [alist[index]], result)

print(list(generate_perm([0, 1, 2], 0, [], []))

Answer: Too late, but this one should also answer your question :)
def permutation(sofar, rest,res):
    if len(rest) == 0:
        res.add(sofar)
    else:
        for i in range(len(rest)):
            permutation(sofar + rest[i], rest[:i] + rest[i+1:len(rest)], res)
    return res

s = 'cat'
res = set()
permutation('',s,res)
print(res)

Answer: Solution with recursion
Libraries aren't needed but wants it much simpler
import random
import string
import math

def perm(string, output = []):
strlen = len(string)
strlist = list(string)
if (len(output) == (math.factorial(strlen))):
  return output

elif string in output:
  string = (''.join((random.sample(strlist, 3))))
  return perm(string, output)

else:
  output.append(string)
  string = (''.join((random.sample(strlist, 3))))
  return perm(string, output)

Answer: you can solve the problem as following:
def permutations (arr):
    if arr == []:
        return [ "" ]
    res = []
    for i in range (len(arr)):
        l = remove(arr,i)
        for j in perm(l):
            res.append(arr[i] + str(j))
    return res

def remove (l, index):
    res = []
    for i in range (len(l)):
        if i == index:
            continue
        res.append(l[i])
    return res

the permutations function does the following: 1 - if the input is empty then we do not have any permutations instead of the empty string so the result will be [ "" ]. This is the  base  of the recursive function. 2 - otherwise, note that in a permutation each element can occur as the first element. Using this logic, the permutations function takes each element from the array and sets it as the first element of the resulting permutation (this is the outer loop). this element is added to all the permutations of the  remaining  elements (If you use a pen and paper and walk through the procedure of the function step by step it will be much easier to understand).
The remove function takes a list and an index and returns a new list without the element in that index.
Obviously many approaches exist. This approach only uses the minimum python methods and I consider it a beginner friendly and easy-to-understand approach. However it is not the most efficient!
Test it with the following and you will get the desired output.
print (permutations("cat"))

Python recursion permutations