svn per apache with mod_rewrite

Question: I have the following virtuslhost for my subversion repository and i want to create a link which always points at the latest stable tag. i tried this using mod_rewrite. it is accepted by apache without any errors but wont work.
i also tried to rewrite .* which seems not work (yes i restarted apache)
<VirtualHost svn.warsow-race.net>
    ServerAdmin             email@example.com
    ServerName              svn.warsow-race.net

    ErrorLog                /srv/svn/error.log
    CustomLog               /srv/svn/access.log combined

    RewriteEngine On
    RewriteRule ^/racesow0.5/latest-stable(.*) /racesow0.5/tags/0.5.4-stable$1

    <Location />
            DAV svn
            SVNParentPath /srv/svn
    </Location>

    <Location /racesow0.5>
            AuthType Basic
            AuthName "Racesow 0.5"
            AuthUserFile /srv/svn/racesow.passwd
            <LimitExcept GET OPTIONS PROPFIND REPORT>
                    Require valid-user
            </LimitExcept>
    </Location>
</VirtualHost>

the rewrite log says
(2) init rewrite engine with requested uri /racesow0.5/latest-stable/sdk
(3) applying pattern '^/racesow0.5/latest-stable(.*)' to uri '/racesow0.5/latest-stable/sdk'
(2) rewrite '/racesow0.5/latest-stable/sdk' -> '/racesow0.5/tags/0.5.4-stable/sdk'
(2) local path result: /racesow0.5/tags/0.5.4-stable/sdk
(2) prefixed with document_root to /htdocs/racesow0.5/tags/0.5.4-stable/sdk
(1) go-ahead with /htdocs/racesow0.5/tags/0.5.4-stable/sdk [OK]

but when calling i get a 404 not found
Comment: Is the "ReweiteEngine" typo in your config?
Comment: Also, best not to crosspost (http://superuser.com/questions/187856/svn-per-apache-with-mod-rewrite)
Comment: it was only a typo in this posting
Answer: The mod_rewrite documentation (see "Per-directory Rewrites") indicates that you should avoid putting directives inside of a <Location> section, declaring it "unsupported". I'd have to check in with the source code to see what impact that actually has, but it's best to just avoid it.
I'd suggest trying to move your rules out into the <VirtualHost>, and then also PT (passthrough) the rewrite in case any other module needs proper access to the rewritten path:
<VirtualHost svn.warsow-race.net>
    ...
    ReweiteEngine On
    RewriteRule ^/racesow0.5/latest-stable(.*) /racesow0.5/tags/0.5.4-stable$1 [PT]
    ...
</VirtualHost>

Comment: @zolex - Hm..Maybe you should setup a [`RewriteLog`](http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritelog) to see if `mod_rewrite` is being properly invoked in the first place. Currently you're getting 404s when you try to view `/racesow0.5/latest-stable`?
Answer: This will not work as Subversion will do its request on top of the location and then involves some "magic" look into your access log to see what is actually requested:
/racesow0.5/!svn/vcc/[...]
/racesow0.5/!svn/bc/888/[...]

I do not know exactly how it works, but to simply "rewrite" the request will not work.
I would suggest to create a folder "/racesow0.5/latest-stable" and put an svn:external into this folder  pointing to your latest release.
Comment: added a folder /repp/latest, and on this folder added svn:externals latest URL, then you can checkout /latest and get a fodler stable containing the target :)
Comment: you mean you get something like /wc/latest/tag_1.5.x/further/src ?
Comment: i do "svn export .../latest-stable ." and get the contents from the tag in ./latest-stable
Comment: just do it "svn export http:// svn.warsow-race.net/racesow0.5/latest-stable ." (use . as destination! it will create another folder latest-stable in it) what you get is exactly http:// svn.warsow-race.net/racesow0.5/tags/0.5.4-stable
Comment: what do you want to get? The external will always create a subfolder with the name you provided next to the URL inside the svn:externals property.

svn per apache with mod_rewrite


When performing for money, do musicians have to buy special sheet music for copyright purposes?

Question: In the same way that I can't buy a cd and broadcast it at a radio station without paying royalties, does a musician have to buy or pay extra to perform a piece?
Comment: This is different in every country. Which one do you mean?
Comment: Questions on copyright law are off topic here.
Answer: In the US, compositions, performances, and recordings are all handled separately.
As a musician, you are free to make a recording of any music you want, and once you do so you own the copyright on that recording. If someone else records the same music, they also own a copyright on their own recording (note this does not mean something like recording a song off the radio or copying a CD or mp3... that would be a copy of someone else's recording). What gives value to one specific recording over another is some level of "officialness" or fame... if you make the song famous or wrote the original song, your recording is the one people will want.
For a performance, a copyright license is paid through the venue... but only to the author/composer (and the music and lyrics may be registered separately). This money is paid to a collection society like ASCAP or BMI. In the case where there is a specific recording of a work that everyone knows, if you cover that song, the band that originally recorded it and made it famous it gets nothing if they used a song first written by someone else. In the case of radio... there are no license fees. In fact, not too far in the past the money went the other direction, with labels paying radio stations to play songs for promotional reasons. This is called, "payola", and more complicated schemes still take place today.
Now for compositions. In the US, a printed musical composition is not different from any other printed work. That is, the author has a copyright... only they can make more copies under the law. But just like you can read a book out loud, you can play the music in the composition anywhere and in anyway that you want. Once the copy has been made, the author's say in how you use that copy is done. You can even re-sell it if you want. There is a difference, however, when it comes to performances. As a composer, you are legally entitled to a royalty when your music is performed. In exchange for this entitlement, you lose the right to license the work yourself, which means losing the right to say, "No" if your music is used at an event you don't like. Instead, there is a compulsory license, and the money is funneled through ASCAP or BMI. If the American Nazi convention latches onto your song for some chance lyric phrase, and get their own members to create a cover recording, you can't stop them from using it as long as they stick to ASCAP-licensed venues.
Comment: That may be a publisher attempting to extend beyond what copyright law really allows (they _will_ do this when they think they can get away with it, or if they're just based in a jurisdiction where they can enforce it via contract law or different copyright rules), or it may have been a digital file, in which case you (again) need a license for the incidental copying, and therefore they can use copyright law to control the terms of that license.
Comment: You don't need to have a copy of the sheet music at all!  Many players can't read music and learn songs by ear.  As was pointed out, a license to perform music doesn't require the sheet music, and buying the sheet music (usually) doesn't grant the license to perform.
Comment: This pretty much sums up what I know of the US situation, with the exception of the fact that each "score" needs to be licenced. Meaning if you have 7 parts to a piece each of those 7 parts needs a licence, though they are often sold together.
Comment: @coteyr My understanding is you don't get licenses at all. A license is a legal permission, and in the context of copyright it is granted to allow someone to make a copy. With physical printed music, you aren't the one making a copy. The publisher makes the copy, and you merely purchase a copy that was already made... no license required on your end. The exception would be if your purchase takes the form of a digital PDF download of the music. In this case, you need a license for the incidental copies created in the process of downloading and printing the final output.
Comment: My point is that you can't just make 7 copies of the "conductor's score" and pass them out. You have to buy 7 distinct copies. But you are correct, the publisher/printer gets the rights to make the copy.
Comment: There is also some confusion around rather a piece of sheet music can be used for personal use only or used in a broadcast or public event.
Comment: Again... no license is needed. Copyright is entirely limited to making copies, and this does not happen when live music is played. Going beyond that enters into contract law. You might sign a purchase contract agreeing not to do so, but that's a separate thing, and would likely not even be enforceable thanks to the consumer's protections defined by the right of first sale.
Comment: Not sure that's true. Researching now. I remembering buying sheet music for personal use only, and not being allowed to "exhibit or preform" but I have to hunt down the situation and rules and what not.
Comment: So from what I can find, you do 100% need a licence to preform or record a piece of sheet music that you have purchased for commercial or public use. However... Most venues have a blanket license that covers this, as you state.  The other wrench is the "compulsory license"  which means they have to grant you a license to preform but you have to pay a fee.  All covered nicely in your answer.
Comment: In the US, radio stations have to pay licence fees to the composers of the songs they play but not to performers. This is due to the Copyright Act not giving sound recordings performance rights for analogue broadcasts and specifically excluding non-subscription digital broadcasts. https://futureofmusic.org/article/fact-sheet/public-performance-right-sound-recordings
Comment: There are many incorrect statements in this answer. Most notably, the author of a literary work absolutely does have the sole right of public performance of the work.  If you don't believe me, try producing a public reading of a copyright work of fiction and see what happens.  Copyright in musical works also extends to public performance, although they are somewhat different because of the compulsory licensing scheme.  The statement that "Copyright is entirely limited to making copies" is sorely mistaken.
Answer: The answers is likely to be dependent on the country a copyright legislation. In Germany paying for official sheet music edition is not sufficient, broadcast will always require a special licensing form listing all pieces affected and from that a Gema license is computed.
Comment: Right. To elaborate, any performance – even a small event in a pub – requires by default a fee to be paid to GEMA. The organisers should also send in a listing of all pieces performed, but AFAIK this is only mandatory for big / broadcast events, and otherwise often not done honestly. Ideally, the fees are then distributed to the original authors, though how well this works in practice is quite in another book.
Comment: "Copyright" and "performing rights" are two completely different things, and "Mechanical reproduction rights" (copying or broadcasting the content of audio or video recordings) is different from both of them. Each of the three is governed by different laws. It is perfectly legal to perform live music "by ear" with no sheet music at all, for example - though in the UK you could theoretically be sued for "defamation" if your performance was considered to be a parody of the original with the intention of mocking it, but that would probably only apply to music by a living composer..
Comment: @leftaroundabout Actually the performers (in my case a village brass band) are obliged to send Gema a list of which pieces they played. The understanding is that the composers/publishers get paid every time. The band has to be able to prove that they have paid for sheet music for every piece they play. This is true for free and fee-paying appearances. Theoretically bands are not allowed to make copies, but this is tolerated (because damn drummers always lose their music) as long as you have the originals back as base. The Gema fee is paid annually AFAIK as a one-time licence.
Answer: It's going to depend on the laws of the country. In U.K. there are two organisations which control payment for this sort of thing - P.P.L and P.R.S. The money for performances are paid by the venue. So, in a way, the band is paying, as it'd get paid more, maybe, if the venue didn't have to find this fee. Occasionally a band which I've played with has been asked for a list of performed numbers, but as far as the musos are concerned, no payment came from them. Music that has been published and purchased already has a proportion of its sale price assigned to the writers, so no extra charges there, either.
Comment: This is the way it is the US too and I'm pretty sure a lot of places: the venue has to pay for a license through something like ASCAP, BMI, etc. Even if you're a small business playing a CD or mp3 player, you're supposed to be paying the yearly licensing fees or you could be sued. I don't know how many businesses do actually do that, but I'd bet live music venues almost certainly do.
Comment: That's what it's a grey area.
Comment: And is this true even for an edition of a work that is otherwise well beyond its original copyright? For instance, if a performer performs a Mozart piece using a recent (hence copyrighted) edition, then licensing is important **for the copyright of the edition** but not the piece itself?
Comment: Far better people to ask would be P.R.S. themselves. Provided the sheet music is not a photocopy, but an original, any dues on it will surely have been paid on purchase.
Comment: Guys: consult a lawyer where you live.  @Tim photocopying itself can be illegal if the copyright is valid, for one thing.
Comment: @CarlWitthoft - true enough, should have mentioned it. In U.K., a local education authority was taken to court and fined an awful lot for allowing its schools to photocopy music.
Comment: @MichaelStachowsky Copyright doesn't last forever. Compositions eventually fall into the public domain, where there is no copyright on the work at all. A recent printing doesn't matter... it's still public domain, and anyone can re-mix/arrange or even print and sell the work.. but so can anyone else. When you talk about a "recent edition", you're talking about a new arrangement, which falls into a grey area. An arrangement _may_ qualify for a new copyright if you change enough, but then it might not. You can't just change a note or two and claim a whole new copyright.
Comment: @JoelCoehoorn: what about dynamics and things like that?  would they count? I suspect that a performer would add their own anyway, so who's to say that they used a particular version?
Comment: @MichaelStachowsky "what about dynamics...?" There isn't a special copyright law for "music" in terms of  what music notation "means". The legal test is whether the alterations are "trivial" - i.e., they could have been made by anybody who understands the contents of the document. For example, randomly changing a few markings probably wouldn't count as avoiding copyright, but revising the score by comparing it with the composer's original manuscript would probably be OK - so long as you could prove you really did that, and didn't copy from somebody else who did the hard work and published it!
Answer: I can only speak for opera but in that case there is a thing called 'Grand Rights', which are payable if you perform an opera any of whose authors (i.e. including librettists) are still in copyright, i.e. in our case died less than 70 years ago. These are rather large and at the publisher's discretion, and typically involve a piece of the gate.
Contrary to the statements elsehwere here about the venue being liable, in our case the opera company was liable.
Comment: In the U.S. there are organizations such as Samuel French that will provide rental copies of the score, parts, scripts and other materials as part of a package that includes the rights for a given number of performances.  You must return all the materials.  In some cases, like major Broadway shows, the piece is not "published" at all.  You cannot buy the score or parts. Printed copies are made but are strictly controlled.  There is no "first sale", so "first sale" does not apply.  Compulsory license does apply once a recording has been make for sale.
Comment: For a work on the scale of an opera, most likely a single company is going to hire a venue for a significant amount of time (including the rehearsals, set-building, etc) so it makes sense for the legal arrangements to be directly with the company. For "general purpose" concert halls and other venues, normally the venue submits details of the music performed and pays the fees (which are averaged out over say a year, rather than assessed for each individual concert) and recovers the cost as part of the hiring charges for the hall, and/or the box office receipts from ticket sales.


Como obter os dias da semana atual ordenado de domingo/segunda

Question: Tenho um grid de alguns apontamentos de horas que tenho um filtro pro usuário preenche a data e carrega meu grid com os registros e tenho um
 que tem os dias da semana, estou conseguindo buscar os dias corretos, porém fica assim:
Segunda 12
Terça   13
Quarta  14
Quinta  15
Sexta   9
Sabado  10
Domingo 11

Esta pegando dias de uma semana anterior, mas se eu clicar na quinta-feira ele ordena corretamente.

function diaSemana($variavel2, $dayName){
    if($variavel2 != null){
        $orderdate = explode('/', $variavel2);
        $day = $orderdate[0];
        $month   = $orderdate[1];
        $year  = $orderdate[2];

        $mes = date("m");
        $ano = date("YYYY");
        $dia = date("d");
        $dia_semana = date("w");

        $mes = $month;
        $ano = $year;
        $dia = $day;

    }

    $cont=0;

    While($cont<=6)
    {
        $dia_calendario = date("d/m/Y",mktime(0,0,0,$mes,$dia-$dia_semana,$ano));
        $dia_s_calendario = date("w",mktime(0,0,0,$mes,$dia-$dia_semana,$ano));

        if($dayName == $dia_s_calendario ){
            return $dia_calendario;
        }
        $dia_semana--;
        $cont++;
    }
}

<?php if(isset($_POST['variavel'])){?>

        DOMINGO

<?php echo $dias = diaSemana($variavel2 = implode("/",array_reverse(explode("-",$_POST['variavel']))),0); ?>
        SEGUNDA

<?php echo $dias = diaSemana($variavel2 = implode("/",array_reverse(explode("-",$_POST['variavel']))),1); ?>

        TERÇA

<?php echo $dias = diaSemana($variavel2 = implode("/",array_reverse(explode("-",$_POST['variavel']))),2); ?>

        QUARTA

<?php echo $dias = diaSemana($variavel2 = implode("/",array_reverse(explode("-",$_POST['variavel']))),3); ?>

        QUINTA

<?php echo $dias = diaSemana($variavel2 = implode("/",array_reverse(explode("-",$_POST['variavel']))),4); ?>

        SEXTA

<?php echo $dias = diaSemana($variavel2 = implode("/",array_reverse(explode("-",$_POST['variavel']))),5); ?>

        SÁBADO

<?php echo $dias = diaSemana($variavel2 = implode("/",array_reverse(explode("-",$_POST['variavel']))),6); ?>

<?php }  ?>

Comment: Qual é o resultado esperado? Os dias da semana corrente?
Answer: Fiz da seguinte maneira, pego o dia atual, volto a data para o primeiro dia da semana e faço o loop até o domingo.
Ficou o seguinte código:
<?php

$translate = array(
    0 => "Dom",
    1 => "Seg",
    2 => "Ter",
    3 => "Qua",
    4 => "Qui",
    5 => "Sex",
    6 => "Sab",
);

$data = new DateTime('2017-12-12');     // Pega a data de hoje
$diaN = date( "w", strtotime($data->format('Y-m-d'))); // Dia da semana, começa em 0 com domingo, 1 para segunda...

$data->modify('-' . $diaN . ' day');

for($i=0;$i<=6;$i++) {
    echo $data->format('d/m/Y') . ' - ' .  $translate[$data->format('w')] . "
";
    $data->modify('+1 day');
}

Imagem do resultado do código acima:
Comment: Bom, a princípio funciona, mas acontece igual no meu código.

Tenta trocar:
$data = new DateTime');

Por:
$data = new DateTime('12-12-2017');

ele me retorna:

07/12/2017 - Qui
08/12/2017 - Sex
09/12/2017 - Sab
10/12/2017 - Dom
11/12/2017 - Seg
12/12/2017 - Ter
13/12/2017 - Qua

Se eu for ordernar isso, ficaria assim:

10/12/2017 - Dom
11/12/2017 - Seg
12/12/2017 - Ter
13/12/2017 - Qua
07/12/2017 - Qui
08/12/2017 - Sex
09/12/2017 - Sab
Comment: Fiz a correção, estava passando sempre o dia da semana como a data atual e não a data setada. Agora está correto. Antes deu certo pois era a data atual setada manualmente e pegava dinamicamente ela também.
Comment: Colega, obrigado por enquanto, já está dando uma baita força, porém ainda não gerou meu resultado, estou passando essa data por parâmetro.

EX:

$data = new DateTime($dataComboBox);

a variavel $dataComboBox recebe o valor de um input(datepicker) que o usuario seleciona, que após isso ele da um refresh na grid com ajax.
Comment: Você precisa formatar a data para o formato americano. Sendo "ANO-MES-DIA", no seu exemplo abaixo me parece que chegou "DIA-MES-ANO". Basta inverter as ordens, desta forma $data = implode('-', array_reverse(explode('-', $data))), desta forma, de "12-12-2017" será "2017-12-12".
Comment: Fiz o seguinte.

 $dataComboBox = date("d/m/Y", strtotime($dataRecebida));
    $data = new DateTime($dataComboBox);     // Pega a data de hoje
    $diaN = date( "w", strtotime($data->format('Y-m-d'))); // Dia da semana, começa em 0 com domingo, 1 para segunda...

    $data->modify('-' . $diaN . ' day');

    for($i=0;$i<=6;$i++) {
        echo $data->format('d/m/Y') . ' - ' .  $translate[$data->format('w')] . "";
        $data->modify('+1 day');
    }

Até o dia 13 ou segunda semana, ele me traz os valores corretamente. Após isso da erro na conversão e traz :

28/12/1969
Comment: Consegui colega, era a variável que estava vindo por parâmetro que tava no formato errado, tks.
Answer: Bom, a princípio funciona, mas acontece igual no meu código.
Tenta trocar:
$data = new DateTime');

Por:
$data = new DateTime('12-12-2017');

ele me retorna:
07/12/2017 - Qui
08/12/2017 - Sex
09/12/2017 - Sab
10/12/2017 - Dom
11/12/2017 - Seg
12/12/2017 - Ter
13/12/2017 - Qua
Se eu for ordernar isso, ficaria assim:
10/12/2017 - Dom
11/12/2017 - Seg
12/12/2017 - Ter
13/12/2017 - Qua
07/12/2017 - Qui
08/12/2017 - Sex
09/12/2017 - Sab


NFS fails to mount through openvpn tunnel

Question: I am trying to establish an nfs connection through an openvpn tunnel.
It really anoying and i dont know what to try next. The connectein test has
been made on several platforms now. used debian/centos/openwrt.
Changed server<>client
A "direct" nfs connection alway works instant by doing: (DEMO IP HERE)
mount -t nfs 192.168.2.1:/extroot test

but an:
mount -t nfs 10.0.0.1:/extroot test

always fails with: (takes forever to timeout)
mount.nfs: Connection timed out

Also i did that on a remote vps and the connection is established instant.
The openvpn tunnel seems fine. Ping ok iperf greather 100mbits soo .....
My configs atached, any help is verry welcome!
NFS:
/etc/exports: ( '*' is just for debugging here )
/extroot *(rw,all_squash,insecure,async,no_subtree_check)

/etc/hosts.allow
portmap: ALL

openvpn:
server.conf:
port 6565
proto udp
dev tun
ca /etc/openvpn/keys/ca.crt
cert /etc/openvpn/keys/server.crt
key /etc/openvpn/keys/server.key
dh /etc/openvpn/keys/dh2048.pem
server 10.0.0.0 255.255.255.0
ifconfig-pool-persist /etc/openvpn/ipp.txt
keepalive 5 30
verb 3

client.conf:
client
tls-client
dev tun
proto udp
remote hostname.of.server portnum
resolv-retry infinite
nobind
pkcs12 /etc/openvpn/nfs.p12
verb 3
remote-cert-tls server

tcpdump from nfs server while trying to connect:
http://pastebin.com/2PJ2w7vB
i know its hard ti read, sorry.
Comment: Just a thought, but you might want to do a capture on your server primary interface.  Is your NFS server attempting to do reverse DNS lookups for 10.0.0.6 and failing perhaps?  Sure all the communication between the client and server should be across the tunnel, but don't assume that is what is happening.  I would be tempted to do something like `tcpdump -ni any` on the server.  BTW are you certain you have ruled out any firewalls?  Are you certain routing is correct, do you see client sending packets out the non-tunneled interface?
Comment: You are right! This is happening all the time, till it times out. >>  http://pastebin.com/9sTwk3mb   << But why the hell is happening that? while route -n shows:  >>  http://pastebin.com/QqKX8Eze  << Why packets are going confused in a clean routing table ? ;)
Comment: Ok, i am getting closer. >> /sbin/mount.nfs -v 10.0.0.1:/extroot test -o addr=10.0.0.1,clientaddr=10.0.0.6 << produces the right tcdump output and mounting works in Debian/ubuntu. but in initramfs state i am getting  >_>_> mount.nfs: rpc.statd is not running but is required for remote locking. <_<_< Any ideas on this ?
Answer: Ok i got it. @Zoredache pointed me into the right direction. Thank you my friend :) !!
Its indeed the case that mount.nfs is trying to point to localhost instead of the vpn ip.
You can solve this by using the following mountopts.
/sbin/mount.nfs -v 10.0.0.1:/$remotepath /$localpath -o addr=10.0.0.1,clientaddr=10.0.0.6

Debug Output of mount.nfs
mount.nfs: timeout set for Sat Nov  1 08:49:42 2014
mount.nfs: trying text-based options 'clientaddr=10.0.0.6,vers=4,addr=10.0.0.1'

If You want to solve this inside initramfs, you need to add /sbin/mount.nfs to your initramfs. The generic command mounting nfs during boot for nfsroot will fail otherwise.


Algoritmo para (A+Bi)^n

Question: Preciso fazer um programinha que dado a fórmula : A + B*i ^ n
Tem que achar o menor valor de n para que seja um número real
Sendo A e B entradas e i faz parte dos números complexos.
Tenho um esboço :
#include <stdio.h>
#include <math.h>

int main(){
  int a,b,c,n;
  int I  = sqrt(-1);
  scanf("%d",&a);
  scanf("%d",&b);

  for(n=1;n<=30;n++){
    c = pow(a + (b * **I**),n);
    if (c==**Número Real**)
      printf("Valor de N é: %d",n);
      break;
    }
    return 0;
  }
}

Onde está "Número Real" não sei como representar isso codificamente e a Raíz Quadrada de -1 teria que ser i porém da um número absurdo. E eu preciso desse i para fazer a equação.
Comment: Um exemplo de uso da macro em C: http://en.cppreference.com/w/c/language/arithmetic_types#Complex_floating_types
Comment: Há a [macro `complex`](http://en.wikipedia.org/wiki/C_mathematical_functions#Complex_numbers) em C e o [pacote `std::complex`](http://www.cplusplus.com/reference/complex/) em C++, que permitem essa representação em termos da parte real e imaginária. Já tentou utilizar? E, aliás, segundo a definição, o seu número resultante vai ser real se a parte imaginária for zero.
Comment: Tentei usar porém não consegui separar os termos ( Parte real e imaginária ) . Exato vai ser real se  a parte imaginária for zero. Mas não consigo codificar isso . Sendo que preciso descobrir qual valor de n para que o imaginário zere.
Comment: Pois então, é por isso que a sua pergunta já recebeu votos pra fechar. Não está claro se a sua dúvida é sobre matemática (fora do escopo do site) ou programação (dentro do escopo do site). Se você já tentou usar (não parece, pelo código que você postou), por que não conseguiu separar os termos? Onde está dando erro? Ou seja, qual é a dúvida específica? Edite a pergunta pra tentar melhorá-la nesse sentido.
Comment: é (a + b * i) ^ n? ou só o i?
Comment: Provavelmente entendi mal a pergunta... `#include  main(){printf("0\n");}` (ok não estou a ajudar nada...)
Answer: Na verdade sua duvida se torna mais um conceito matemático do que um conceito de programação. Para trabalhar com potências complexas utilize a forma trigonométrica ou a forma de Euler. Não precisa se preocupar com o valor de "i", já que existe, na própria matemática, notação que não o utiliza, como (real, imaginário), notação que trata o número como um par ordenado do plano complexo. O "i" é uma representação que separa a parte real da complexa, não necessita ser trabalhado.
Código: (resposta para (a + b * i)^n)
Comentários no código o explicam (supondo n real):
#include <stdio.h>
#include <math.h>

#define PI 3.1415926535

/* Estrutura para forma complexa cartesiana */
typedef struct complexCart {

    double real;
    double imaginario;

} ComplexCart;

/* Estrutura para forma complexa trigonométrica */
typedef struct complexTrig {

    double raio;
    double angulo;

} ComplexTrig;

/* Converte complexo cartesiano para trigonométrico */
ComplexTrig converterTrig(ComplexCart);

/* Converte complexo trigonométrico para cartesiano*/
ComplexCart converterCart(ComplexTrig);

int main(void)
{
    /* Variável que irá armazenar a menor potência
       necessária. */
    double menorPot;

    /* Variável "cart" irá guardar número na forma
       cartesiana: a + bi, já "trig" na forma trigono-
       métrica: r(cos(Angulo) + i sen(Angulo)).
       Vale notar que basta trabalhar com os parâmetros
       em cada um desses casos, por exemplo, para trabalhar
       com dados cartesianos basta (a, b) e trigonométrico sim-
       plesmente (r, Angulo) */
    ComplexCart cart;
    ComplexTrig trig;

    printf("\nDigite um número imaginário da forma a + bi: ");
    /* Espera receber o número da forma cartesiana.
       Ex: -2 + 3i, ou 2 + -3i (imaginária negativa) */
    scanf("%lf + %lfi", &cart.real, &cart.imaginario);

    /* Converte para forma trigonométrica, essa é mais fácil de lidar
       com potências, raízes, divisões e multiplicações. Também poderia
       ser utilizada a forma de Euler */
    trig = converterTrig(cart);

    /* Mostra a forma trigonométrica com o ângulo em radianos: Somente quando
       for exibir o resultado se preocupe com a forma de escrita complexa! */
    printf("O número em forma trigonométrica (em radianos): z = %.2f(cos(%.2f)   + i sen(%.2f))\n",
         trig.raio, trig.angulo, trig.angulo);

    /* Com o ângulo calcula-se a menor potência necessária
       para que a parte do seno zere, ou seja, quando o ângulo é */
    menorPot = PI / (trig.angulo) ;

    /* Mostra a potência e o ângulo final quando a forma trigonométrica
       possui tal ângulo. */
    printf("A menor potência para tornar o número somente real é: %.2f\n", menorPot);
    printf("Ângulo da forma trigonométrica: %.2f rad\n", (trig.angulo) * menorPot);

    /* Reatribui à forma trigonométrica o valor com a potência, ou seja,
       a forma já será com o valor elevado à potência */
    trig.raio = pow((trig.raio), menorPot);
    trig.angulo = (trig.angulo) * menorPot;

    /* Converte a forma trigonométrica da potência à forma cartesiana */
    cart = converterCart(trig);

    /* Mostra o resultado trigonométrico, o seno do ângulo dev ser zero.
       Verifique!*/
    printf("Forma trigonométrica z^(%.2f) = %.2f(cos(%.2f) + i sen(%.2f))\n",
        menorPot, trig.raio, trig.angulo, trig.angulo);

    /* Aqui, na fomra cartesiana, por garantia mostra-se a parte imaginária,
       que deverá sempre ser zero. */
    printf("Forma cartesiana z^(%.2f) = %.2f + %.2f i\n\n", menorPot, cart.real,
        cart.imaginario);

    return 0;
}

/* Implementações dos Protótipos. */
ComplexTrig converterTrig(ComplexCart dadoCart){

    ComplexTrig dadoTrig;

    dadoTrig.raio = sqrt( (dadoCart.real) * (dadoCart.real) +
        (dadoCart.imaginario) * (dadoCart.imaginario) );

    if(dadoCart.real != 0)
        dadoTrig.angulo = atan( (dadoCart.imaginario) / (dadoCart.real));

    else
        dadoTrig.angulo = PI / 2;

    return dadoTrig;
}

ComplexCart converterCart(ComplexTrig dadoTrig){

    ComplexCart dadoCart;

    dadoCart.real = (dadoTrig.raio) * cos(dadoTrig . angulo);
    dadoCart.imaginario = (dadoTrig.raio) * sin(dadoTrig.angulo);

    return dadoCart;
}

No exemplo acima utilizei estruturas para idealizar melhor (e demonstrar união) do par complexo. (Poderia ter sido feito com 4 doubles independentes, mas com estrutura fica mais fácil visualizar). O resto é matemática. Lembre-se que sempre que for trabalhar com números complexos não é necessário (na maioria das vezes) lidar com o VALOR de i, basta trabalhar como um par ordenado usual, mas sujeito a certa álgebra (Não vou comentar pois sai do escopo do site).
Comment: Resposta realmente muito boa. Parabéns! :)
Comment: Corrigido o caso 0 + 0i, que anteriormente dava erro.
Answer: A resposta do Rafael resolve o problema da forma mais esperta (convertendo o complexo para uma representação trigonométrica), mas acho que seria interessante mostrar que não é difícil resolver o problema de uma forma parecida com o que você já tem.
Tudo que você precisa fazer é implementar a multiplicação você mesmo ao invés de tentar querer por números complexos em C e usar o operador * nativo.
Se você tiver dois números X = a + b*i e Y = c + d*i o produto X*Y vai ser
X*Y =
(a + b*i)(c + d*i)        =  (por distributividade)
ac + ad*i + bc*i + ad*i^2 = (por i^2 = -1)
(ac - bd) + (ad + bc)*i

Podemos representar isso em C usando um par de inteiros (a,b) para representar o número complexo a + b*i.
typedef struct {
    int r; /* parte real */
    int i; /*parte imaginaria */
} Complex;

E podemos implementar as operações sobre o tipo complexo que acabamos de criar como funções simples ao invés de operadores.
Complex addComplex(Complex x, Complex y){
    Complex z;
    z.r = x.r + y.r;
    z.i = x.i + y.i
    return z;
}

Complex multComplex(Complex x, Complex y){
     Complex z;
     z.r = x.r*y.r - x.i*y.i;
     z.i = x.r+y.i + x.i+y.r;
     return z;
}

Depois disso, fica fácil implementar uma versão que funciona do código que você já tem:
int main(){

    Complex x;
    scanf("%d",&x.r);
    scanf("%d",&x.i);

    Complex x_n = {1, 0};
    for(int n=1;n<=30;n++){
        x_n = multComplex(x_n, x);
        if (x_n.i == 0){
            printf("Valor de N é: %d",n);
            break;
        }
    }
    return 0;
}

Uma vantagem de escrever o código dessa forma é que todas as contas são feitas em inteiros ao invés de doubles, o que evita problemas de arredondamento. No entanto, os campos de x_n vão sofrer overflow após poucas iterações devido ao crescimento exponencial do "raio" de x_n. Uma versão mais robusta desse código deve representar os números complexos com um tipo de dados para "inteiros de precisão infinita" ao invés de usar int.
Comment: Mas assim nunca vai dar o resultado, esse "n" tem que ser float ou double, mesmo que "a" e "b" seja inteiros. Nem sempre o expoente será inteiro. Se você testa será raro algum resultado bater, e se bater será truncado. Por exemplo: 2 + 3i, o expoente será 3.2, mesmo com "a" e "b" sendo inteiros. Além disso testei no seu código 2 e 3, por exemplo, e nada mostrou (não alcançou o if), talvez devido a esse problema.
Comment: Mas números complexos podem ser quebrados: a + ib , "a" e "b" são pertencentes aos reais, pois o conjunto dos reais deve estar contido no dos complexos.
Comment: Bem, se esse fosse o caso, pode ser impossível achar um dado n inteiro para "a" e "b" fornecidos pelo usuário (como @JJoao) falou. Nada garante que ele seja inteiro, mesmo com potências maiores, inclusive variando até o infinito, ou seja, pode ficar sem solução. Além disso a própria definição de número complexo utiliza o termo "real" justamente por cair no conjunto dos reais quando a parte imaginária é zero.
Comment: A entrada dele é sempre inteira portanto ele só precisa tratar dos números reais com partes inteiras (inteiros de Gauss).
Comment: Dado o for da pergunta inicial eu assumi "menor n inteiro" ao invés de "menor n". São duas interpretações diferentes da pergunta
Comment: Embora seja uma interpretação possivel e a tua solução interessante, dá-me ideia que n inteiro muito raramente terá solução.
Comment: Terá solução quando o ângulo phi for da forma pi*fracionário; caso contrário não tem solução (por definição de imaginário). Teremos que escolhar a e b cuidadosamente. Ainda assim gosto da solução (+1)
Comment: O problema é o usuário escolher a e b, será praticamente um jogo de loteria. Seria interessante um programa em que o usuário digitar a (ou b) e daí sim para calcular b e n inteiros.

Algoritmo para (A+Bi)^n


Interpreting tree classification errors in Matlab

Question: I am currently using Matlab to generate random forests. I am using the TreeBagger class with the function oobError. I can plot a 2D figure which puts my tree count on the X-axis (IKA weak learners count) and classification error is on the Y-axis.
My question is: How can I interpret the actual error of my classifier (something like cross-validation which gives you a double as your classification error)?
Another question is: Is the X-axis of my figure the number of trees in bag or is it describing which tree (tree #50 for example) has the accuracy given at the corresponding point on the Y-axis?
Comment: what do you mean by "gives you a double"?  Are you referring to estimates of the two types of classification errors that can occur in a two-class problem?
Answer: If you're doing something like the example in the matlab documentation, then the plot contains the Out-Of-Bag Error as a function of the total number of trees.
If you want to cross-validate your model (which you should!), then build the TreeBagger object with some portion of your data and apply it the remaining held-out data with the predict() method. Matlab has a bunch of utility functions to make cross-validation easier. Take a look at the cvpartition class and the crossval function, though it's obviously not too difficult to write your own versions either.
Comment: Thanks for your answer, however, I have read many articles and other stuff that the out of bag error is the real measure of the CCR in random forest. The k-fold cross validation method may not be suitable.
Comment: Interesting! Looking into this a little bit more, one can do even better by correcting the out-of-bar error rate, as in Bylander (2000) http://www.cs.utsa.edu/~bylander/pubs/ml00-final.pdf.


Erro com JSPdf com VueJS

Question: estou tendo um problema ao tentar utilizar o JSPdf com Vuejs. Peguei um tutorial na internet (esse aqui) que mostra como imprimir todo o conteudo de uma div (pois não estava conseguindo. Porem, no teste funciona perfeitamente, no meu, mesmo conseguindo adaptar, o PDF vem tudo em branco, alguem consegue ajudar?
methods: {
   GerarPdf(){
        let source      = $('#div')
        let cache_width = source.width()
        let a4          = [595.28, 990.89]

        let canvasImage = ''
        let winHeight   = a4[1]
        let formHeight  = source.height()
        let formWidth   = source.width()

        let imagePieces = []

        imagePieces = [];
        imagePieces.length = 0;

        source.width((a4[0] * 1.33333) - 80).css('max-width', 'none');

        return html2canvas(source, {
            imageTimeout: 2000,
            removeContainer: true
        })
        .then(canvas => {
          console.log(canvas)
          canvasImage = new Image();
          canvasImage.src = canvas.toDataURL("image/png");
          let totalImgs = Math.round(formHeight/winHeight);

          for(let i = 0; i < totalImgs; i++) {
              let canvas = document.createElement('canvas'),
                  ctx = canvas.getContext('2d');
              canvas.width = formWidth;
              canvas.height = winHeight;
              ctx.drawImage(canvasImage, 0, i * winHeight, formWidth, winHeight, 0, 0, canvas.width, canvas.height);
              imagePieces.push(canvas.toDataURL("image/png"));
          }
          console.log(imagePieces.length);
          let totalPieces = imagePieces.length - 1;
          let doc = new jsPDF({
              unit: 'px',
              format: 'a4'
          });
          imagePieces.forEach(function(img){
              doc.addImage(img, 'JPEG', 20, 40);
              if(totalPieces)
                  doc.addPage();
              totalPieces--;
          });
          doc.save('techumber-html-to-pdf.pdf');
          //source.width(cache_width);
        })
      }
}

Answer: Olá,
Não "debuguei" seu código para entender onde o erro acontece, porém, Já usei jsPDF com jsPDF-AutoTable e acredito que isso possa servir para o que você precisa.
Pressupondo que você já tenha uma noção de JavaScript e VueJS, segue abaixo o código.

var app = new Vue({
 el: '#app',
  data: function() {
   return {
     table: [{
       id: 1, text: 'teste 1', today: new Date()
      }, {
       id: 3, text: 'teste 3', today: new Date()
      }, {
       id: 2, text: 'teste 2', today: new Date()
      }]
    }
  },
  methods: {
   pdf: function() {
      var columns = ["ID", "Text", "Today"];
      var rows = this.table.map(function(data) {
       return [data.id, data.text, data.today];
      });

      // Only pt supported (not mm or in)
      var doc = new jsPDF('p', 'pt');
      doc.autoTable(columns, rows);
      doc.save('table.pdf');
    }
  }
})

{{item.id}} - {{item.text}} : {{item.today}}

  <button @click="pdf">Gerar PDF</button>

Não existe muito segredo nesse script. A função autoTable dispoêm de 2 parametros, o primeiro é um Array com o nome das colunas e o segundo é um Array bidimenssional onde cada linha possui um array com os valores.
Qualquer dúvidas estamos a disposição, no entando sugiro que leia as instruções antes de qualquer coisa, abraço.
jsPDF
jsPDF-AutoTable
Edit

Exemplo usando o elemento HTML table e o método autoTableHtmlToJson link jsFiddle
Answer: Depois de muito tentar, consegui resolver meu caso, vou deixar o código aqui para aqueles que possuírem o mesmo problema que eu. Agradeço aqueles que tentaram me ajudar.
$('body').css('overflow', 'visible')
            $('#app').css('overflow', 'visible')
            $('#pdfCarta').css('overflow', 'visible')
            $('#pdfCarta').css('position', 'initial')
            let a4          = [595.28, 990.89]
            $('#pdfCarta').width((595.28 * 1.33333) - 80).css('max-width', 'none');
            //$('#pdfCarta').css('transform', 'scale(2)');
            let useHeight = $('#pdfCarta').prop('scrollHeight');
            //alert(useHeight)

            let winHeight   = a4[1]
            let imagePieces = []
            let canvasImage = ''
            let formHeight  = $('#pdfCarta').height()
            let formWidth   = $('#pdfCarta').width()
            let source = document.getElementById('pdfCarta')

            imagePieces = [];
            imagePieces.length = 0;

            setTimeout(function(){
                html2canvas($('#pdfCarta')[0],{height: useHeight, useCORS: true, allowTaint: true, onrendered: canvas => {
                    canvasImage = new Image();
                    canvasImage.src = canvas.toDataURL("image/png", 0.92);
                    //window.open(canvas.toDataURL())
                    let doc = new jsPDF('p', 'pt', 'a4')

                   for (var i = 0; i <= source.clientHeight / 980; i++) {

                        var srcImg  = canvas;
                        var sX      = 0;
                        var sY      = 1120*i;
                        var sWidth  = 778;
                        var sHeight = 1120;
                        var dX      = 0;
                        var dY      = 0;
                        var dWidth  = 778;
                        var dHeight = 1120;

                        window.onePageCanvas = document.createElement("canvas");
                        onePageCanvas.setAttribute('width', 778);
                        onePageCanvas.setAttribute('height', 1120);
                        var ctx = onePageCanvas.getContext('2d');

                        ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);

                        var canvasDataURL = onePageCanvas.toDataURL("image/png", 0.92);
                        var width         = onePageCanvas.width;
                        var height        = onePageCanvas.clientHeight;

                        if (i > 0) {
                            doc.addPage();
                        }
                        doc.setPage(i+1);
                        doc.addImage(canvasDataURL, 25, 0);

                    }
                    doc.save('draft.pdf');

                }})

            }, 1000)

Erro com JSPdf com VueJS


Aplicação para quando passo uma List por parametro para um Sub relatório

Question: Estou tentando passar uma Lista por parâmetro para meu Sub Relatório, porém quando chega em determinada parte a aplicação para e o relatório não é gerado. Nunca sai disso:

Estou passando a Lista dessa forma:
<code>public boolean gerarRelatorio(List list, int numeroRelatorio, String nomePrestador, String dataSistema) {
    JasperReport report = null;
    InputStream image = this.getClass().getResourceAsStream("/br/com/xml/relatorio/LOGO.png");
    filtro.put("Image", image);

    filtro.put("listaDados", listaProcedimentos);
    filtro.put("localizarRel", "src/br/com/xml/relatorio/subRelatorio.jasper");

    try {

        InputStream inputStreamReal = getClass().getResourceAsStream("/br/com/xml/relatorio/Relatorio3.jrxml");
        report = JasperCompileManager.compileReport(inputStreamReal);
    } catch (JRException ex) {
        Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Erro ao pegar arquivos!", "ERRO!", JOptionPane.ERROR_MESSAGE);
    }
    try {

        JasperPrint print = JasperFillManager.fillReport(report, filtro, new JRBeanCollectionDataSource(list));
        JasperExportManager.exportReportToPdfFile(print,
                "C:/Demonstrativos/" + dataSistema + "/" + nomePrestador + "_" + dataSistema + "_" + numeroRelatorio + ".pdf");

        return true;

    } catch (JRException ex) {
        Logger.getLogger(frmPegaXml.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Erro ao Gerar relatório, verifique se nenhum arquivo está aberto ou se o nome está correto!\n" + ex, "ERRO!", JOptionPane.ERROR_MESSAGE);
        return false;
    }
}
</code>
Alguém sabe o porquê da aplicação parar sem nenhum erro?
Answer: Cara, isso normalmente não dá muito certo, trabalho já tem um tempinho com o jasper e ele é bem encrencado pra essas partes de passagem de parâmetro, principalmente para objetos, a dica que vou te dar é a seguinte, lá no jasperreports(aconselho utilizar a 5.6), no relatório principal você cria um parâmetro do tipo list com o mesmo nome desse que você esta mandando pra ele. Na hora de que você for configurar o subreport, onde você passa o diretório, creio que por parâmetro também, você passa o seguinte na opção "Data Source Expression" "new JRBeanCollectionDataSource(listaDados)". Neste caso, "listaDados" é o parâmetro que você criou. Lembra de que tem que ser idêntico ao que você esta mandando no código. Qualquer coisa eu posso montar um tutorialzinho. Espero ter ajudado. Abraço!


Blocking USB through GPO in 2008 R2 & excluding certain users

Question: I am looking for blocking USB devices in our Win 2008R2 SP1 server. I am already aware about GPO policy "\User Configuration\Policies\Administrative Templates\System\Removable Storage Access" & it's working perfectly here.
Only there are few concern's as below.
1: I want to exclude certain users/groups from this policy.
2: All other rules/policy's in original "default domain controller policy"  should be applied to everyone like PW policies, WSUS policies etc..
Thanks,
Sandesh
Answer:
Configure your desired settings in a new GPO.
Create a Security group for the users that you DO want the policy to apply to.
Add the appropriate users to this Security group.
Configure Security Filtering on the new GPO to apply to this Security group only.
Link the OU to the location where the user objects are (either at the Domain level or at the OU level if you have your users in an OU).
Comment: How to link the OU. i.e. 5th step??
Comment: in GPMC right click the location you want to link the GPO to and select "Link an Existing GPO" from the context menu and then select your GPO in the "Select GPO" window and click OK.
Comment: Not working. I have linked both the GPO's. Default Domain policy & custom policy called USB_Deny. Still Users added into SG called USB_Block able to access it.
Comment: Still I am struggling with GPO.

Below things I did so far.

1. Created new OU called Laptop-Users & then new group called USb_Block. Added several users into it.

2. Created new GPO called USb_Deny_Gpo & added certain rules/policies to block the USB storage devices.

3. Then Right clicked on domain xyz.com to link default domain policy & Usb_deny_Gpo.

4. Added Usb_Block group into Security Filter of scope tab in Usb_Deny_Gpo with read & apply group policy permission.

This settings seems OK for me. But, still users in my network able to access USB drives.
Comment: Anyone please...
Comment: So this policy has been applied and works for you but no one else?  Have you performed a gpresult under their account ("gpresult /h gpreport.html") to see if the policy shows as a applied GPO or if its evening showing?
Answer: IMO, the easiest way to exclude users is to utilize the advanced button on the delegation tab of the group policy object. Add the user/group you want to exclude, and check the box to deny them all rights to the policy. Since deny statements take precedence over allow, this will work to exclude certain users/groups even if they are a member of a group (such as "Authenticated Users") that has rights to the GPO


How to get OEM USB driver for Samsung Galaxy SIII with model number GT-I9300

Question: I want to get OEM USB driver for Galaxy SIII. I following this official OEM USB Drivers page. So I select OEM - Samsung and visit this official Samsung website. This website ask me to enter my model number so I write - "GT-I9300". But then I can't get anything. Can you help me?
Answer: I had the same problem following the same tutorial. I'm using Eclipse IDE, on a 64-bit Windows machine. This is how I solved it:

Theoretically, the USB driver for a clone version should be the same as a regular one, hence I´ve downloaded a similar model.
I had to configure a few environment variables to make ADB work (tutorial).
Made the regular procedure: 'adb kill-server' and 'adb start-server'.
And finally, the most important one, while Eclipse IDE was open, I restarted the debug mode on my phone (just deselect an select again the option). In this step, on my phone, it asked me to confirm the connection!

I hope it works for you too. Sometimes the driver step might be skipped since Windows installed it automatically. I unistalled it and reinstalled several times.
Comment: Oh thank you very much. For that moment I've been trying throw genymotion. Everything now is working really good. Thanks
Answer: find the drivers for Samsung SIII GT-I9300 USB debugging on this page
https://samsung-firmware.org/download/GALAXY%20S%20%E2%85%A2/9O12/INS/I9300XWUGML4/I9300ODDGML4/
under flashing requirements section
hope this helps.


Mix of terms causation and dependence in 'book of why'?

Question: In the 'book of why' he says:

the listening pattern prescribed by the paths of the causal model
usually results in observable patterns or dependencies in the data

I don't understand, why he says "usually". Isn't it always the case when we have causation that we shall see some sort of dependence in the data?
Then, I really can't follow why he says this:

"There is no path connecting D and L" which translates to a
statistical statement "D and L are independent".

Correct me if wrong, but the absence of a path only means there is no causation... Why he says D and L are independent? I mean, both D and L can be highly correlated and still we could see no path connecting D and L.
Both quotes are from page 13.
Comment: For the first part, maybe the case of offsetting/cancelling effects is relevant. It is rarely plausible but not technically impossible.
Comment: There's a distinction between *path* and *directed path*, where the latter must follow the direction of causality (arrows), and the former does not.  And it sounds like you're thinking of "directed path."  So $X \leftarrow Z \rightarrow Y$, says $X$ and $Y$ are both are caused by $Z$.  $X$ and $Y$ might be correlated, but neither causes the other.  There is no directed path between them, but there is a path between them (since they have a shared cause).  Does that help?
Comment: Also remember that the lack of an arrow between two variables in a DAG means **no *direct* causal effect**, not **no causal effect**. For example, in the DAG $A \to B \to C$, $A$ is for sure a cause of $C$, even though it is not a *direct* cause of $C$.
Answer:
I don't understand, why he says "usually". Isn't it always the case
when we have causation that we shall see some sort of dependence in
the data?

No, because you can have accidental cancellations. See here for an example: Does statistical independence mean lack of causation?

Correct me if wrong, but the absence of a path only means there is no
causation... Why he says D and L are independent?

You are conflating a directed path with paths in general. Paths do not need to be causal. For instance, consider a third variable $Z$. If $Z$ is a common cause, we have the path $D \leftarrow Z \rightarrow L$ and this induces a non causal association between $D$ and $L$. We call such paths ``back-door'' paths.  This is a path very much like $D \rightarrow L$ is a path.
So when we say ``absence of paths,'' we mean a complete absence of any connection between the two variables in the DAG, directly or indirectly. If there are no paths from $D$ to $L$, be it direct or indirect paths this indeed implies independence between the two variables.
Comment: +1 Was going to answer with the link you provided if no else had. :D There is a great example of an automobile's speed and the angle of the accelerator pedal that I am trying to remember a source for that would also be a good example (it is pretty similar to the boat example Dimitriy quoted). :)
Answer: This only addresses your first question, but I wanted to point out that cancellation does not have to be accidental. It can be the outcome of purposeful human behavior. This is a key point to me since that implies cancellation (and sign-flipping of the correlation) is the norm rather than a once-in-a-very-blue-moon event.
This example is taken from Scott Cunningham's Causal Inference: The Mixtape.

But weirdly enough, sometimes there are causal relationships between
two things and yet no observable correlation. Now that is definitely
strange. How can one thing cause another thing without any discernible
correlation between the two things? Consider this example, which is
illustrated in Figure 1.1. A sailor is sailing her boat across the
lake on a windy day. As the wind blows, she counters by turning the
rudder in such a way so as to exactly offset the force of the wind.
Back and forth she moves the rudder, yet the boat follows a straight
line across the lake. A kindhearted yet naive person with no knowledge
of wind or boats might look at this woman and say, "Someone get this
sailor a new rudder! Hers is broken!" He thinks this because he cannot
see any relationship between the movement of the rudder and the
direction of the boat.
But does the fact that he cannot see the relationship mean there isn't
one? Just because there is no observable relationship does not mean
there is no causal one. Imagine that instead of perfectly countering
the wind by turning the rudder, she had instead flipped a coin—heads
she turns the rudder left, tails she turns the rudder right. What do
you think this man would have seen if she was sailing her boat
according to coin flips? If she randomly moved the rudder on a windy
day, then he would see a sailor zigzagging across the lake. Why would
he see the relationship if the movement were randomized but not be
able to see it otherwise? Because the sailor is endogenously moving
the rudder in response to the unobserved wind. And as such, the
relationship between the rudder and the boat's direction is
canceled—even though there is a causal relationship between the two.
This sounds like a silly example, but in fact there are more serious
versions of it. Consider a central bank reading tea leaves to discern
when a recessionary wave is forming. Seeing evidence that a recession
is emerging, the bank enters into open-market operations, buying bonds
and pumping liquidity into the economy. Insofar as these actions are
done optimally, these open-market operations will show no relationship
whatsoever with actual output. In fact, in the ideal, banks may engage
in aggressive trading in order to stop a recession, and we would be
unable to see any evidence that it was working even though it was!
Human beings engaging in optimal behavior are the main reason
correlations almost never reveal causal relationships, because rarely
are human beings acting randomly. And as we will see, it is the
presence of randomness that is crucial for identifying causal effect.
Comment: Great excerpt! Is there a technical term for this phenomenon? Searching for "cancelation" in this context doesn't seem to bring up much.
Comment: Endogeneity is the term used in economics. The standard example is the estimation of supply and demand curves.
Comment: +1 Wish I could give you more, 'cause we need more art. :D


Probability and Venn Diagrams

Question: The question in concern asks, "$136$ people were asked if they liked Math, Science, or Social Studies. They all liked at least one.
$40$ like Math
$17$ like Math and Science
$40$ like Science
$8$ like Science and Social Studies
$32$ like Social Studies
$11$ like Math and Social Studies
$6$ like all three subjects."
My question is that although it says $136$ people were surveyed, the results that were gathered afterwards add up to $154$. Where are the extra $18$ people coming from exactly?
Thanks in advance.
Comment: A single person can have more than one interest.
Comment: To add to @PrasunBiswas comment, one person can be counted in "like Math", "like Math and Science" at the same time, for example.
Comment: Based on these numbers, $40 + 40 + 32 - 17 - 8 - 11 + 6 = 82$ of the $136$ people surveyed liked at least one subject, contrary to the claim that each person liked at least one subject.
Comment: There are $136 - 40 = 96$ people who do not like Science, but you are correct that the denominator should be $136$.  The $40$ people who like Science include those who like both Science and another subject.
Comment: Oh! Right, I am just now seeing the 'They all liked at least one' ...  OK, then something is definitely off here!
Comment: @N.F.Taussig Using my Venn Diagram, those are the same numbers I got. A whole 54 people weren't accounted for, but the question says they were...
Comment: @TonyS.F. The probability of it all would still be counted over 136 still right? So if I was asked, for example, what's the probability of someone not liking Science, it would counted as 83/136?
Comment: Actually, something is off about these numbers.  If you apply the [Inclusion-Exclusion Principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle), you will find that the number who like at least one of these subjects is less than $136$.
Comment: @N.F.Taussig I am relooking at it, following the strategy of Bram below and I am also finding that the numbers will result to be less than 136.
Comment: Indeed,  The data is inconsistent.  By the way.  What exactly *is* the problem this data is provided for?  What were you actually asked to find?
Comment: So maybe these *are* real life numbers! :)
Comment: @Bram28 So what do I do in the case of real life numbers?
Comment: @user55614 First you should ask what this '$40$ like math' means. Second, ask for a recount!
Answer: If I were given these numbers in real life I would, like you, interpret the claim that '$40$ like Math' as '40 like Math but not Science and also not social science', given that it has separate numbers for all kinds of combination of liking subject areas. So, I can understand your confusion!
But, given as that does indeed add up to more than $136$, probably the claim means that '40 like math  .... and possibly science or social science as well'
Thus, for example, the $17$ people that like Math and Science are part of the $40$ people that like Math.
As such, you can actually use a Venn diagram to figure out exactly how many people are in each of the different regions of that diagram. For example, given that $6$ people like all three subjects, and given that $17$ people like both Math and Science, we can infer that $17-6=11$ people like Math and Science but not Social Science.
In fact, given that there will be quite a bit of overlap between the different subject areas, you'll probably get quite a few people less than $136$ that likes any subject at all: probably quite a few don't like any of the three subjects! Again, draw a Venn diagram, and you can work out all the numbers.
Answer: What you were probably missing is that one person can like more than one subject.
Let me give you a more simple example, with $2$ subjects.

$10$ people like math, $20$ like science, and $8$ like both.

First, jump to $8$ like both.
There are $10-8=2$ people who like math only.
There are $20-8=12$ people who like science only.
Now, add $8$ into your counting - the $8$ people who like both math and science.
So, there are $2+12+8=22$ people in total.
Implement this same logic, this time for $3$ subjects, and start by drawing a Venn Diagram!
Hint: Start from in to out (start from excluding people who like all $3$ subjects and counting them all the way at the end).
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/971833)
Comment: @XanderHenderson I hope it is good now.
Answer: It is a question on Venn diagrams and the data provided contains intersections. Clearly the intent is that the sets, M,S,T (for Maths, Science, and Social Studies):
$$\begin{split}n(\Omega)&=136\\n(M)&=40\\ n(M\cap S)&=17\\n(S)&=40\\n(S\cap T)&=8\\ n(T)&=32\\n(M\cap T)&=11\\ n(M\cap S\cap T)&=6\end{split}$$
Now, were you told that everbody liked at least one, or were you asked to find how many liked at least one?  Because the data would seem to state, by the principle of inclusion and exclusion, that
$$n(M\cup S\cup T)~{=n(M)+n(S)+n(T)-n(M\cap S)-n(M\cap T)-n(S\cap T)+n(M\cap S\cap T)\\\ll 136}$$
Comment: What the problem gave me was the information I listed originally above, and then it asked probability questions afterwards, i.e., "What is the probability that someone likes Science but not Math?" However, because it has been proven to be less than 136 people now that we have seen, what number would I use to calculate probability? 82 or 136?

Probability and Venn Diagrams


How to quickly figure out the chords in a major scale?

Question: If I am playing on the scale of G major which have the keys G A B C D E F#, the chords of the major scale are G major, A minor, B minor, C major, D major, E minor, and F# diminished.
I am curious if there is a fast way to determine the notes in these chords. I know major scale chords have the pattern as Major Minor Minor Major Major Minor Diminished, but like for example:
For the second note in the G scale (A): I have to map out the A minor scale, then locate the (1,3,5) fingers in that scale, and then finally I have the major chord in that scale but that takes time. Or is this something you just have to memorize?
Answer: Diatonic Chords
First, as Tim also mentioned, stick to the key of G. You shouldn't be considering "an A minor" scale at any point.

Write out (or think) the notes in G
Start from the note you want to make a chord from
Take every other note (intervals of a third)

That's how you do it at first. But the more familiar the (G) scale is to you, and the more you work with these notes as both chords and arpeggios, you just start to memorize them naturally.
Chord Formulas
Also, just as you should consider G as your frame of reference when harmonizing the diatonic chords of the entire scale, I'd also learn to use the chord root as a frame of reference when thinking about individual chords. Because remember that an Am is a chord in other keys as well. And it's helpful to be able to build the chord by itself without first placing it in a key.
So you already know the qualities of the diatonic chords (Maj7, min7, min7, etc). Now learn the formulas for each of those chords. For example a minor 7th is: 1, b3, 5, b7.

You know you want an A minor chord
Use the parallel major scale as reference (A major): A, B, C#, D, E, F#, G#
So you take the 1, b3, 5, and b7 of that A major scale to get A, C, E, G
Comment: A G major chord has a major 3rd interval (G to B) and a minor 3rd (B to D) contained within it. But if you start from a G scale and just take every other note (GMaj = G, B, D; Amin = A, C, E, etc), you'll get the same result. Each of those intervals could be called a **diatonic third** because they are thirds but change major/minor quality to stay in the key of G.
Comment: That's correct. The 3rd degree of the scale/chord is what makes it minor or major. As for the upper interval from the 3rd to 5th that obviously changes as well when you lower the third. The interval in either a major or minor chord from the 1st to 5th is a perfect 5th (G to D, A to E). That part stays the same. So in say G major B to D is a minor third, but when you lower that B to Bb to make a G *minor* chord, that distance to D increases by a half step which then makes the upper interval a major 3rd. But, yes, that pattern sticks.
Comment: Thank you. Yes I know the formula for the chords like minor7th, major7th, Dominant seventh, major, minor, etc. I just have to practice more I guess and know the scales really well. One question when you say "Take every other note (intervals of a third)", does intervals of thirds mean 3 semitones? I am always confused do I calculate in semitones or whole notes? Since G to A is 2 semitones and that is not a interval of third correct?
Comment: By "thirds" I'm not not talking about half-steps *or* whole steps because an a third could be a different amount of those steps depending on context. For example a major 3rd is 2 whole steps where a minor 3rd is 3 half steps. I mean it generally as in it could be either minor *or* major.
Comment: So I noticed that when playing the first chord G Major (has a major 3rd interval (G to B) and a minor 3rd (B to D)). Then when playing A minor (has a minor 3rd interval (A to C) and a major 3rd (C to E)). Is that a pattern? For major triad it's major third interval then minor third interval and for minor triad it is minor third interval and major third interval?
Comment: One last question if the patterns is `Major Minor Minor Major Major Minor Diminished` then for example for the A note it has to be played in the minor scale of A but we are assuming we play the A major chord in the A minor scale correct? Why is that? Why can't we play A major seventh in the A minor scale?
Answer: You could do it that way, as you say, take the second note A, then count up the A minor scale, 1,3,5 - A,C,E, then the B - 1,3,5 - B,D,F#. It works. The other way would be to stick firmly in G, so chord I is 1,3,5, chord ii is 2,4,6, chord iii is 3,5,7 (B,D,F# =Bm), except that takes you over the 8, as in chord vi is 6,8,10 (E,G,B =Em) but maybe that's not too bad.
Otherwise, as you guess - just learn them. There are many songs that use six out of the seven chords - play them in many different keys. I guess your instrument is piano. On guitar, it's probably easier to think in terms of relative fret positions for certain chord shapes - which isn't really an option on piano.
Answer: Just know your scales.  I mean KNOW them.  What notes are in them, how they're laid out on the keyboard/fretboard.   You can't even BEGIN to think about composing or improvising until you know the map.
Comment: "You can't even BEGIN to think about composing or improvising until you know the map". *Of course you can*. I fully agree that you should aim to know scales well. The more you learn your instrument the better you'll get. But let's not reinforce the myth that you need to master everything before you even begin making real music.
Comment: Not everything.  But if you don't know the language, it's hard to read a story, let alone write one.   And we've seen the sort of conceptual messes people can get into here often enough!
Comment: Knowing scale notes on a fretboard won't necessarily help in finding chord shapes. It always will on keyboard.
Comment: Indeed.  Guitarists who are interested in harmony and 'theory' would be well advised to find their way around a keyboard too.


ARMA: modelling a time series with a bimodal distribution

Question: I have a de-trended and de-seasonalized time series, and it's distribution is not gaussian (see distribution in Figure 1).
I tried modelling it with and ARMA model, but as we could expect, this model does not have good prediction capabilities (see Figure 2), especially for high values / maxima.
My question is: is there a way to use auto-regresive models to model signals with bimodal distributions? If so, how can I do it in Python / R?
Figure 1:

Figure 2:
Answer: You probably used the stock arima function to model ARMA process. The stock function uses MLE with normal distribution. If you think your errors are bimodal and the process is still ARMA, then the only solution is to get into nonnormal modeling. You may need to implement your own MLE with your own error distribution.
However, looking at your Fig.2 I'd be wary of those three spikes in 2006-2008. They're the ones making your distribution look bimodal. Is it a real phenomenon? Could these by outliers? What's worrying me is that they are accompanied by huge drops, a sort of a zig-zag move. This often indicates an error or irregularity in data. For instance, due to some rule or event you missed some observations, then picked them in next period. In this case you'll see a drop, then spike.
Bimodal distributions are possible, but settling on a bimodal distribution simply based on a histogram in levels is a stretch. I'd first study those zig-zags, at the very least, drop those observations and redraw the histogram. Chances are you'll find something unusual about these observations.
Comment: Did you mean to say "adjust these observations" rather than "drop these observations" as time series analysis requires equally spaced values in time
Comment: @IrishStat, state space representation of ARMA alloows to drop the observations. Practically in R you'd put NAs, and it should estimate just fine.
Comment: ok .. I was (as usual) locked in the time domain .


Dummy variables for linear models with multiple levels

Question: I'm currently working with data which has continuous variables and a hierarchical structure attached to it, think of measuring blood pressure, size and weight of different domestic animals (cats, dogs, birds) as well as of their species, family and order.
All data is measured on the level of the individuals, so there are no predictors on higher levels (although they could be generated by taking, e.g. the inter-level mean).
Let's say I want to predict the blood pressure ($y$) with the help of the weight ($x_1$) and the size ($x_2$).
Ignoring the hierarchical information, I could use a linear model $y= \beta_0 + x_1\beta_1 + x_2\beta_2$, which might be a very bad idea.
If I only had two different species measured, I could use one binary dummy variable $d$ and consider $y= \beta_0 + x_1\beta_1 + x_2\beta_2 + d \beta_3$.
If I wanted to consider $n$ species instead, would I need $n$ variables $d_1, \dots, d_n$ and consider
$$y= x_1\beta_1 + x_2\beta_2 + \sum_{i=1}^n d_i \beta_{i+2},$$
Is this the right approach for dummy variables if there are more than two categories?
The last model doesn't account for the hierachical structure. If I wanted to include the family as well (assuming for simplicity that there are only 2 families, but multiple species), would adding another binary predictor $\tilde d$ suffice?
$$y= x_1\beta_1 + x_2\beta_2 + \sum_{i=1}^n d_i \beta_{i+2} + \tilde d \beta_{n+3}$$
Is this the right approach to implement hierarchical dummy variables?
Edit: Removed the intercept as it was suggested in the answer of Maarten Buis.
Answer: Your first question: Close but not quite: you either need to leave one of your species out of the model as a reference category or you need to leave out the constant. In the former case each $\beta_{i+2}$ measures the difference between species $i$ and the reference species, so the parameter of the reference species is necessarily $0$, which means that the indicator variable for the reference species drops out of the model. In the latter case each $\beta_{i+2}$ is the constant for each species, which means that there is nothing left to do for the overall constant $\beta_0$ so it should drop out.
Your second question: No, all the information is already captured by the species indicator variables (a term I prefer over dummy variable), so there is nothing for the family indicator variables left to explain and they will be automatically dropped from the model due to perfect multicolinearity.
Comment: So species indicator variables can be used to reflect a 2-level structure, but they do not reflect the additional structure of a 3- or 4-level model - am I reading this correctly?
Comment: I don't understand that comment. I see only two levels: species and families. Where is that 3rd and 4th level comming from? As long as the levels are hierarchical, than indicator variables at the lowest level (e.g. species) will absorbe all the variance of all the higher levels (e.g. families).
Comment: Oh, I might be using terminology incorrectly. With 2 levels I mean the individual pet level (level 1), and the species level (level 2): I'd call the simple linear model without species indicators a 1-level model, and as soon as we have species information, we would have a 2-level model. The third level would be one which includes families as well. A fourth level (order) was not written down in the models, but mentioned in the introduction.
Comment: So family and order indicator variables will add nothing once you have included the species indicator variable. As a consequence, these will result in perfect colinearity and they will be dropped.
Comment: You could go the other way around though: first add only order, than add _only_ family (which implictly also includes order, so leave that out), than add _only_ species (which implicitly includes also family and order, so leave those out)
Comment: Would dropping the intercept work with multiple categorical variables as well?
Comment: Not in this case. Dropping the constant works when you want to include the reference category. That is not the problem Roland wants to solve.


Good examples for mathemathical problems/statements that are easely solvable/provable in one theory and hard to solve/prove in another

Question: Let $P$ be a mathematical statement or a mathematical problem. I am looking for a couple of nice examples for $P$ that satisfy the following criteria:

Given two (or more) mathematical points of view on $P$, we find that one of them views makes $P$ easy to solve/prove and the other one makes $P$ hard to solve/prove.
$P$ should (at least from the easier point of view) be understandable by someone who studied maths obtained the basics and has a quiet good understanding of mathematical problems.
It shouldn't take to much text to formulate, since I don't have that much time and space to present it.

It would be nice if the problem is prominent and it is ok if the problem is not pure math but must have a clear link to maths.
Any ideas? A short explanation of the problem from the different angels is welcome and appreciated.
Edit: I forgot to mention that by different point of view I meant somethink like looking at $P$ from an algebraic point of view and from an analytical point of view and maybe from a topological point of view. I want to point out the awesome properties of maths to transform a hard problem to another theory where the problem is easily solvable.
Comment: This is a *really* vague and broad question.  "points of view" as in different proof strategies, or as in from different fields/domains of math, or as in...different theoretical stances, e.g. assuming the axiom of choice or without assuming it...This question, as it stands, could open pandora's box!
Comment: @Aufwind, then I'll delete my answer.
Comment: @amWhy As in different fields/domain. Thanks for asking. I edited my question.
Comment: Thanks, that helps narrow things a little bit, at least!
Comment: @DimitriSurinx Sorry for my unspecified original answer. Thanks for your effort!
Comment: @Aufwind, No problem!
Comment: Check Wiener's theorem on the convergence of the Fourier series of $1/f$. He did it with brilliant hard analysis techniques but Gelfand did a three line proof using Banach algebra technique. You can look at Folland's *A Course in Abstract Harmonic Analysis* Chapter 1 to see the details.
Comment: @Aufwind: It has been suggested that this question be made [Community Wiki](http://math.stackexchange.com/privileges/community-wiki). Please consider doing this.
Comment: Dear @robjohn, I consulted the link you provided to see how to make this question Community Wiki. It states: *You can choose to make any answer you own a community wiki by ticking the checkbox under the edit area.* Unfortunately I own the question and not the answer. How do I turn the question into Community Wiki? :-)
Comment: @Aufwind: if you start to edit your question, you should see the "Community Wiki" [check box](http://i.stack.imgur.com/LsVt7.png) below and to the left of the edit box.
Comment: @robjohn: Unfortunately this doesn't work. I started to edit the question, hoping for the Checkbox to appear. I added several sentences, since I thought maybe there is a minimal amount of characters, that should be changed to make an edit valid. But nothing happened. You have my blessing to use your moderator power to change the question into community wiki, if you want. :-)
Comment: @Aufwind: so done. [Your reputation](http://math.stackexchange.com/privileges/user/9850) should allow the creation of wiki posts, so I don't know why you did not get the checkbox. I apologize for all the back and forth.
Comment: @robjohn no harm done. :-)
Comment: A nice elegant example is the existence of transcendental numbers.
Answer: The prime number theorem states that the number of primes less than a real number $x$ (denoted by $\pi(x)$ ) can be approximated by $x/\log x$ in the sense that $$\lim_{x\to\infty} \frac{\pi(x) \log x}{x} = 1.$$
Now, the very statement of this theorem uses the concept of primality and a limit of a real function, so any proof must, at the very least, use some elementary number theory and some basic real analysis. It turns out that it is indeed possible to prove the prime number theorem with only these basic tools (Selberg/Erdős discovered such a proof) but this proof is (relatively) quite difficult.
It was discovered several decades after the first proofs were found by Hadamard and de la Vallée-Poussin (independently) in 1896. Both of their proofs used complex analysis (in fact, they developed quite a lot of the theory of complex analysis largely with this purpose in mind I recall). So the Prime number theorem is an example of a theorem that can be stated with only elementary number theory and real analysis, and can be proved with much effort with only these theories, but is much more easily established by complex analytic methods.
Comment: it's not easy, even with complex analysis.
Comment: Katie Nicely stated!
Comment: It's certainly not trivial, but if you are familiar with the basics of complex analysis, you may want to look at [Newman's Proof](http://www.maa.org/sites/default/files/pdf/upload_library/22/Chauvenet/Zagier.pdf) of the PNT.
Answer: Matrix multiplication is associative:
you could prove this by a computation, but it's obvious once you realize a matrix gives a function $\mathbb{R}^n \to \mathbb{R}^n$. This one is sort of cheating, because it's not clear why you'd want to multiply matrices unless you understood this property already.
Subgroups of free groups are free: this can be shown group-theoretically but is not obvious. Topologically, this says covers of graphs are graphs, which is obvious.
Hilbert's Theorem 90 can be proved directly in a couple paragraphs, using linear independence of characters, but spotting the theory of etale cohomology it just says that there are no non-trivial line bundles on a point.
Comment: Terry Tao calls that the law of conversation of hard work. We should be careful when applying this principle before saying something is not possible though. Hardy was skeptical that an elementary proof of the prime number theorem could be found, because the PNT is equivalent to a purely complex function theoretical statement about the Riemann zeta function, so how could totally elementary arguments do that? This seems like good reasoning, especially when coming from Hardy, but with the benefit of hindsight we see that the missing "hard work" is all in proving the equivalence itself!
Comment: in all these examples, by the way, the "work" is hidden somewhere - it's rare that you can get something for nothing.
Answer:
Fundamental theorem of Algebra:
Algebraic: I know of two proofs, one using induction and doing a whole lot of algebraic manipulations that made it quite lengthy. Another one uses Galois theory.
Complex Analytic: In my opinion some real cool proofs arise from complex analysis. The most elegant( IMO) is the proof using Liouville's Theorem though proofs using minimal modulus principle is also quite good.
Finding real integrals using contour integration.(Has been mentioned before by amWhy)

Right now these two stike my mind.
Comment: But in the algebraic proofs, do they use partial analysis results? Such as every odd degree polynomial has at least one root.
Answer: I propose something of a more elementary nature.
Parallelogram Law The sum of the squares built on the diagonals of a parallelogram is two times the sum of the squares built on two adjacent sides of the parallelogram.
As it is stated this is a statement in classical plane geometry which is not that easy to prove. If you are giving a lecture you could draw a picture at the blackboard and invite the public to think a bit about it: I'm quite confident that nobody will find the solution in one minute or so.
Now if you change the point of view, moving into analytical geometry, you'll see that the problem is solved by a completely straightforward computation: indeed, vectorizing the picture (the following is taken from Wikipedia)

you see that you only need to expand the squares $(x+y)\cdot(x+y)$ and $(x-y)\cdot(x-y)$, which is a familiar task to everybody who has had a course in elementary algebra.
Answer: The following theorem is quite easy to prove using model theoretic tools, but I heard it is very difficult with plain analysis tools:

Let $f\colon\mathbb{C^n\to C^n}$ be a polynomial function. If $f$ is injective then $f$ is a bijection.

There is a nice class of theorems in forcing whose proof is unclear (if even possible) when approaching to forcing by posets, whereas the proof is immediate when working with Boolean algebras (the completion of the separative quotient of the poset).
The following theorems come to mind immediately:

If $M$ is a model of ZFC, $M[G]$ is a generic extension of $M$ and $M\subseteq N\subseteq M[G]$, such that $N$ is a model of ZFC, then $N$ is generic over $M$ and $M[G]$ is generic over $M$.
If $P$ is a non-trivial countable forcing then $P$ is equivalent to a Cohen forcing (there is a unique countable atomless complete Boolean algebra).
Comment: I don't understand forcing - Cohen's book is just about incomprehensible to me - but I wonder about Cohen's recollection (I think in an interview, likely available online) that forcing didn't involve combinatorics, but rather was a shift in philosophical outlook. What exactly is forcing?
Answer: There are uncountably many equations (e.g. $x^2 = -4$), and for that matter uncountably many problems which are unsolvable when restricted to real analysis -- but that have complex solutions. $$i = \sqrt{-1}\;\;\text{ to the rescue, so to speak}.$$
As an added side note:Similarly, a crucial advancement in mathematics occurred way back in ancient Greece, when Euclid concluded that there is no way to compute the diagonal of a $1\times1$ square in terms of the ratio of two lengths, geometrically or otherwise. From this he was motivated to establish that there must exist numbers $x$ (e.g. $\sqrt{2}$) such that $x \notin \mathbb{Q}$. In this case, $$\mathbb{R} \text{ to the rescue!}\;$$
Comment: There are only countably many equations.  There are only countably many problems.  There are countably many sentences in general, definitions, etc.
Comment: I believe it was [Hippasus](http://en.wikipedia.org/wiki/Hippasus) who first concluded that $\mathbb Q \subset \mathbb R$ (showing that the diagonal of a $1\times 1 $ square ...). As a result, because he dared to question Pythagoras who believed that $\mathbb Q = \mathbb R$, Pythagoreans throw him in the sea and he was drowned. One of Pythagoreans "motto" was "everything is made from integers" (in greek "Τα πάντα γίνονται από αριθμούς").
Comment: I learned the same, @P.. Happasus was taken to be a heretic!
Answer: This is a whole class of examples of the phenomenon you ask for, where a problem that is difficult in one theory is easy in another.
The fundamental theorem of Galois theory establishes a correspondence between field extensions and an associated group. This allows for a translation of problems in one to the other. Most of the time, it is field theoretic questions reaping the rewards - generally questions about field extensions are quite difficult, but questions about groups are easier.
For example, given a field extension E/F, could you fathom how to classify all the intermediate fields? If you are a pessimist, it seems like it even may be too hard a question to hope to be able to answer. With Galois theory however, this problem is converted to classifying the subgroups of a given group, which brings us back to much more familiar territory.
Answer: Goodstein's theorem, which makes an easily-understood assertion about easily-understood operations on integers, is not just 'difficult' to prove, but unprovable in Peano arithmetic; however, if we're allowed to use transfinite ordinals, the proof is really quite short.
As for "it is ok if the problem is not pure math but must have a clear link to maths", I think you're going to have trouble, because of things like the objections raised in Feynman's challenge.
Answer: I think this might be an example. Proving the fundamental theorem of arithmetic using topological methods. However, the proof is not very difficult. Check http://en.wikipedia.org/wiki/Furstenberg%27s_proof_of_the_infinitude_of_primes
This might be an example too. Abraham Robinson and Allen Bernstein proved that every polynomially compact linear operator on a Hilbert space has an invariant subspace using non standard analysis.
http://en.wikipedia.org/wiki/Non-standard_analysis#Invariant_subspace_problem
Comment: The second result I don't know what it is, but I thought it may be a good example because Paul Halmos proved te same result without using non standard analysis
Answer: I know that the areas concerned are not entirely different, but here's another example.
Burnside's $p^{a}q^{b}$ Theorem: Every finite group of order $p^{a}q^{b}$ (where $p,q$ are primes and $a,b\geq 0$) is solvable.
The theorem was proved by William Burnside in 1904 using character-theoretic methods (or the method of linear substitutions as Burnside referred to it). However, it was not until 1970 - over 65 years after Burnside's original proof - that David Goldschmidt - using the ideas of John Thompson - produced a group-theoretic proof in the case that $p,q$ were odd primes. In 1973, Hiroshi Matsuyama completed the proof of Burnside's Theorem by proving that a group of order $2^{a}p^{b}$ was soluble. A year earlier, Helmut Bender had also given a full proof of the theorem in his paper A group theoretic proof of Burnside's $p^{a}q^{b}$-theorem.
The character-theoretic proof is a few pages long, whilst the group theoretic one takes up 15-20 pages.
Comment: @spernerslemma Other people may correct me if I'm wrong, but I thought it was just a case of people feeling that such an important result in group theory should be able to be proved using group theoretic methods, and not by appealing to results outside the immediate subject.
Comment: Out of curiosity, why was a "group theoretic" proof desired?
Answer: Brouwer fixed point theorem has many proofs. The one via Sperner's lemma is elementary and tedious (sorry sperners lemma), but as you develop more tools in topology the proofs become shorter and shorter. It's not that any particular viewpoint makes BFPT particularly hard, but in the course of developing topological tools you make thinking about the problem easier and easier.
Hard way: Sperner's lemma, triangulation of the disk.
Easier ways:
Poincare index theorem. Homotopy invariance of topological degree. Homology and first isomorphism theorem. Use $S^2$ is not a retract of $D^2$.
If you need this for a presentation, then going into all this stuff will be way beyond your time limit probably. But at least Brouwer FPT has interesting explanations and applications.
Another interesting problem is proving that $e$ is irrational. There's Fourier's proof (from the BOOK) using Taylor series, a small variation on this approach, I've seen one using Niven polynomials, a geometric one involving an intersection of nested sets in the real line, and Euler's proof via continued fractions (which he somehow got while doing differential equations).
The interesting thing about each of these is that they all have something extra unique to them. Taylor series makes this very short and sweet. Niven polynomials are actually powerful enough to prove that any rational power of $e$ is irrational, and I believe $\pi$ as well. The geometric one allows one to derive an "irrationality measure." And continued fractions are always cool, no exceptions. All are elementary (i.e. assumes no more than differentiation, integration, and Taylor series) except for Euler's continued fraction stuff, I couldn't get at this original work to figure out what he did.


Deployment of full database dump still causes error

Question: I want to deploy my local DB to a staging server.
The local DB dump was exported with all tables. Including the "cache_" prefix table structures with no data exported.
After deployed to staging (with Jenkins), I got exceptions like Plugin missing error or field missing.

Uncaught PHP Exception RuntimeException: "Unable to determine class for field type 'daterange' found in the 'field.storage.node.field_date_range' configuration" at /var/www/html/lightnest/releases/20200227152907/docroot/core/modules/field/src/FieldStorageConfigStorage.php line 164

I cannot run update.php or rebuild.php because this error will popup again.
I also cannot run drush commands as I have no direct access to the staging.
Am I missing anything?
Answer: You can run Drush commands remotely from another server using methods such as site aliases.
https://docs.drush.org/en/master/usage/#site-aliases
So you might be able to run registry rebuild https://www.drupal.org/project/registry_rebuild
which sometimes helps with class errors.


Drupal Form in Block will NOT call Submit or Validate handlers

Question: Let me start by saying I have seen quite a few similar threads, and I have tried everything I've found so far, with none of them working.
My brother wanted a contact form to be in the footer of his site, so it gets rendered on every page. I didn't think this would be an issue, so I created a custom form and rendered it in a block. It looks great, but when I went to add in the validation and submit handlers, none of them work.
Here is what I currently have.
function opal_contact_form() {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => 'name',
    '#required' => true,
    '#default_value' => '',
    '#attributes' => array('placeholder' => 'Name'),
  );
  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => 'Email',
    '#required' => true,
    '#default_value' => '',
    '#attributes' => array('placeholder' => 'Email'),
  );
  $form['phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Phone',
    '#attributes' => array('placeholder' => 'Phone'),
    '#default_value' => '',
  );
  $form['company'] = array(
    '#type' => 'textfield',
    '#title' => 'Company',
    '#attributes' => array('placeholder' => 'Company'),
  );
  $form['topic'] = array(
    '#type' => 'textfield',
    '#title' => 'Topic',
    '#attributes' => array('placeholder' => 'Topic'),
    '#default_value' => '',
  );
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => 'Message',
    '#required' => true,
    '#default_value' => '',
    '#rows' => 3,
    '#attributes' => array('placeholder' => 'Your message...'),
  );
   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  //$form['#submit'][] = 'opal_contact_form_submit';
  //$form['actions']['submit']["#submit"][] = "opal_contact_form_submit";
  kpr($form);
  return $form;
}

function opal_contact_form_validate($form, &$form_state) {
  kpr($form);
  dd('this is from the validate');
  exit();
}

function opal_contact_form_submit($form, &$form_state) {
  kpr($form);
  dd('this is from the submit');
  exit();
}

I don't think this is relevant, but here is the block rendering part.
function opal_blocks_block_view($delta) {
  $block = array();

  switch ($delta) {
    case 'contact_form':
      $block['subject'] = t('');
      $block['content'] = build_contact_form();
      break;
  }

  return $block;
 }

 function build_contact_form() {
   $form = drupal_get_form('opal_contact_form');
   $html = drupal_render($form);

   return $html;
 }

The parts commented out in the form definition are suggestions I found elsewhere and tried. I've never had to do anything special for a standard page form, except add _validate and _submit to the name of the form in order to get a validation and submit handler to work. Perhaps things work differently when rendered in a block?
Any suggestions would be appreciated.
EDIT
I found the problem in a theme function that I didn't include in the initial post cause i didn't think it would have anything to do with it, but I obvious was wrong. I am still not sure why this is causing the problem, but when I comment it out, it works fine. I just wanted my form to be displayed in 2 columns.
function opal_blocks_theme() {
  return array (
    'opal_contact_form' => array(
      'render element' => 'form'
    ),
  );
}

function theme_opal_contact_form($variables) {
  $form = $variables['form'];
  $output = '';
  $output .= '
We would love to hear from you:
';
  $output .= '
';
  $output .= drupal_render($form['name']);
  $output .= drupal_render($form['email']);
  $output .= drupal_render($form['phone']);
  $output .= drupal_render($form['company']);
  $output .= '
';

  $output .= '
';
  $output .= drupal_render($form['topic']);
  $output .= drupal_render($form['message']);
  $output .= drupal_render($form['submit']);
  $output .= '
';

  return $output;
}

Answer: You forget to render technical form fields: form_id, form_build_id, etc.
As fix I suggest you to add the following to your theme function:
$output .= '
' . drupal_render_children($form) . '
';

Answer: Those are the only 3 differences I can see between (working) block forms I have written in the past and your code.
1) What are the exit(); lines there for? Maybe try removing those?
2) I usually also define $form and $form_state in the original form function.
3) I do usually add the render array straight to the block content, maybe prerendering that as html causes some interference? (bit unlikely but worth a try)
function opal_blocks_block_view($delta) {
  $block = array();

  switch ($delta) {
    case 'contact_form':
      $block['subject'] = t('');
      $block['content']['form'] = drupal_get_form('opal_contact_form'); // Block content can handle renderable arrays, saves you a couple of lines of coding
      break;
  }

  return $block;
 }

Comment: The exit() lines are just to terminate as a debugging method. I did define $form and $form_state in the original form, i took them out based on another posts suggestion. Neither worked. I was getting strict warning messages when i had it all one one line as you have in point 3). I was not specifying the array key "form" though. I have never seen that.
Comment: Yeah, it was supposed to be wrapped as a string, fixed that in the post. I once ran into a very odd bug with form #prefix/suffix items being wrapped around the block. Since then I always nest accordingly. Still your code looks perfectly fine so I'm afraid I'm out of ideas. If I have a minute I'll try adding it to a custom module of my own.
Comment: Thanks for looking. I edited the original post with some new code that was causing the problem, but i'm not sure why.


Bamboo sharing large artifacts between jobs

Question: I'm having issues with builds taking longer because the artifacts creation at the end of a jobs is increasing build time. Additionally, jobs that require the artifact add additional build time when retrieving the artifacts.
A solution to this issue I thought would be to have a jobs perform work on the same  work space.
What are the typically conventions/solutions for passing large artifacts between jobs or in other continuous integration tools?
Answer: There're few options:

pack your artifacts into one file to improve transfer performance between agent and server
use network drive shared between different agents to share artifacts without sending them to server.
use dedicated artifact storage server like Nexus or Artifactory
use same agent to build are jobs which require same artifact (not scalable)


Prove this monotone sequence has a bound, thus it converges.

Question: Let $r>0$ and $\frac{r^n}{n!}$ Prove that it converges.  I know that it is eventually decreasing, so it is monotone.  How do I get a bound for it to show that it converges?
Also how would I go about showing $\lim_{n\to inf} \frac{r^n}{n!}=0 $.
Would I just use the definition to show this?
Answer: Every term is the same as the previous, times $r/n$. For $n$ large enough, this ratio is less than one, so that the terms go decreasing to zero.