Do all 3rd inversion diminished and half diminished 7th chords resolve to 64 chords?

Question: I am playing around with the use of b7 as melody note in a major key and with ^2 in the bass I am able to build a diminished 42 chord (in C that is DEGBb) and I am trying to figure out how to resolve this chord. Would it be a secondary dominant type chord that resolves to a 64 chord? 64 chords sound rather dissonant themselves so how does that work?
Comment: Also important - D-E-G-Bb is a **half-diminished** 4/2 chord, not a diminished 4/2 chord.
Comment: How about: D-E-G-Bb -> C#-E-G-Bb -> D-C#-E-F#-G#-A.
Comment: Thanks. I wanted to resolve it without leaving C as the tonic... I dont mind tonicizing F though but cant see how to resolve it to F in root position
Comment: Weird, I tend to use b7 in the melody in major keys in pretty much V7/IV, I7, and bVII only.
Comment: Dekka, yes that is correct, but if I am not mistaken, both would resolve to a 64 chord
Answer: It's difficult to tell out of context, but that particular chord looks like it really wants to find an F major chord to resolve to!
In the key of F, this chord is the vii diminished.  It's a common substitute for the dominant, V (a C major or C7 chord).  There is no harm in using it, but at some point you'll have to get back to C major.
In the key of C it would work like a secondary dominant,  the vii of IV.
Resolving to a IV in second inversion does seem reasonable,  but I don't recall seeing it used this way in the literature.   And that 64 chord will have a strong tendency to feel cadential so you will have a lot of work to do to bring us back to C major.  It could be a useful tool for modulating, though.
Comment: Thanks, I actually dont mind modulating to F but I cant resolve that chord to an F in root position can I?
Comment: Well, you CAN do whatever you feel like.  You're in charge.  Depending on who plays this music, they may squawk about it.  Singers may struggle to perform it when certain notes don't go the way they expect.  The music-composition-gods may shun you.  Or, you might be writing in a more pop style and love the sound of it and it could just go exactly like you want it to.
Comment: The D-E-G-Bb in the question isn't a diminished 7th chord, it's a half-diminished 7th chord. Half-diminished 7th chords aren't common substitutes for the dominant at all.
Comment: Oooooh good point!
Comment: Dekka, Half diminished 7th chords have a tritone, why cant they substitute for a dominant chord?
Comment: @armani - Huh, I guess my music theory textbooks and courses must have given me the impression that vii half-diminished 7th was *really* rare at best and basically supplanted by vii fully-diminished 7th chords, even in major keys.
Comment: @Dekkadeci as far as I know it has several uses.  Most commonly as a ii (predominant) especially in jazz where it appears both in major and minor; sometimes as a dominant; and in late romantic works it was exploited for its expressive colors.
Answer: Your question set up is confusing.
As soon as you start with "all" in the question, the answer is simply "NO."
But why combine both diminished seventh chords and half diminished seventh chords in the question, when detail only the latter?
If you want the lowered seventh degree in major, while maintaining the major key tonic, you will get the mixolydian mode. But then you say tonicizing the IV chord is OK too. Not knowing if the tonality is supposed to be modal or tonal matters.
You can do all the things you laid out...

lower the seventh degree
maintain C as the tonic
use ^2 in the bass
use a 4/2 half diminished chord rooted on ^3

...with something like this...

...which will maintain basic part writing principles, but it will sound modal or Impressionistic.
If you want to handle the chord as viiø7 or iiø7, that's fine, but you will displace the tonic of C even if temporarily. The former will be a dominant and the later will be a subdominant.
So, the basic answer to the question is "no," it doesn't need to resolve to a 6/4 chord. But the choices have implications for the harmonic style and tonic.
Answer: 'All'?   No, of course not!
Having got that out of the way:
There's a tritone in there; E - B♭ (A♯), which can resolve the usual two ways, inwards to F - A  or outwards to D♯ - B.  So here's a couple of possibilities (with some implied bass notes). I'll leave it to you to give them functional labels!


How is the best practices to build proxy server on ubuntu?

Question: I added to my server IP Failover (32 IP / OVH). I want to build a proxy server on one container on docker on this server. Which tool/lib is the best in this situation?
I need a proxy for scraping several pages via puppeteer.
At the moment I using ten rows proxy, and I want similar links like ten rows for scraping:
curl -k "http://example.com" -L -x "http://67e5d6108f831a320d4e70e88e410a58518a9ade:@proxy.zenrows.com:8001"
I thinking about Squid, it is a good option?
Answer: Yes, squid-cache is a good option for forward-proxy.
You can use Ubuntu's docker image ubuntu/squid.
Regarding best practices:

Set authentication or at least source-IP restrictions for your proxy
Authenticate it over HTTPS. I faced a few challenges doing it a couple of years ago because most of the JavaScript libraries only supported proxy over HTTP, but, at the end of the day, it's achievable.


Validador de Senhas em C

Question: Estou tentando resolver o problema 2253 - Validador de Senhas, do URI, porém está dando 10% de resposta errada, mas todos meus testes estão dando certo, alguém consegue achar o erro?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int validade(char *S) {
    int i, maiuscula = 0, minuscula = 0, numero = 0, tam = strlen(S) - 1;
    if(tam < 6 || tam > 32)
        return 0;
    for(i = 0; i < tam; i++) {
        if(isupper(S[i]))
            maiuscula = 1;
        else if(islower(S[i]))
            minuscula = 1;
        else if(isdigit(S[i]))
            numero = 1;
        else
            return 0;
    }
    return maiuscula * minuscula * numero;

}
int main() {
    char S[100];

    while(fgets(S, 100, stdin) != NULL)
        printf(validade(S) ? "Senha valida.\n" : "Senha invalida.\n");

    return 0;
}

Answer: O maior problema é esse while que não faz sentido. Melhorei algumas outras coisas que pode dar algum ganho.
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int validade(char *S) {
    int tamanho = strlen(S);
    if (tamanho <= 6 || tamanho >= 32) return 0;
    int maiuscula = 0, minuscula = 0, numero = 0;
    for (int i = 0; i < tamanho - 1; i++) {
        if (islower(S[i])) maiuscula = 1;
        else if(isupper(S[i])) minuscula = 1;
        else if(isdigit(S[i])) numero = 1;
        else return 0;
    }
    return maiuscula * minuscula * numero;
}

int main() {
    char S[40];
    fgets(S, 40, stdin);
    printf(validade(S) ? "Senha valida.\n" : "Senha invalida.\n");
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: O problema exige o while porque a entrada do problema temina com final de arquivo, mas obrigado de qualquer forma.
Comment: Mas não faz sentido, porque esta função não retorna um fim de arquivo e sim um ponteiro.
Comment: @Alface, você pode perguntar à própria `stdin` se ela já terminou: `feof(stdin)`
Comment: Ou verificar [na documentação](https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm) que ele retorna `NULL` quando chega no fim do arquivo e não consegue ler 1 caracter sequer
Comment: Eu troquei para NULL e agora não excede o tempo limite, mas há 10% de resposta errada :/
Comment: Não faz sentido perguntar `EOF` direto no `fgets` com `stdin`. Quando trocou para `NULL` essencialmente fez o `while` não ser necessário mais, então faz o mesmo que a minha resposta, só que a minha não tem instruções desnecessárias. O objetivo desses exercícios é fazer aprender e não conseguir resolvê-los e não entender o que está lá.
Comment: Eu entendo o  que está lá, mas é que eu realmente preciso resolver como está lá, é um trabalho prático.
Comment: Bom, s´so você sabe o que está lá, e se é o que está falando, aquilo pede para fazer algo errado, ou então você está interpretando algo errado. Fica difícil ajudar mais que isto dado o que foi passado. A pergunta não falava nada disso, então o que foi perguntado já foi respondido.
Comment: Alface, seria mais fácil de explicar se você tivesse colocado um link ;-) Maniero, o Alface quer responder esse teste:https://www.urionlinejudge.com.br/judge/pt/problems/view/2253. O código dele será validado por um arquivo contendo várias linhas, por isso o 'while'.
Comment: Obrigado a todos, resolvi a questão, eu só troquei de C para C++ e deu certo.
Answer: Podes tentar usar um padrão RegEx para isso:
#include <regex.h>

E por exemplo usar como padrão:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,}$

Explicação:
^      inicio da palavra
(?=.*) "lookahead" procura para a frente
\d     numero
[a-z]  letra minuscula
[A-Z]  letra maiuscula
{4,}   pelo menos quatro caracteres
$      fim da palavra

Validador de Senhas em C


Can gateway handle different protocols?

Question: Can gateway(network device) handle different protocols. I know that it is used to connect dissimilar networks. What type of dissimilarity does it include?
Answer: The term Gateway is a very broad term. In Networking a Gateway is typically a device that sits between two network domains or at the entrance to a domain and may handle protocol translations, perform address translations, filter traffic, terminate sessions and much more.
An IP Router for example in some cases is named as a Gateway as it connects the local subnet to the rest of the network - hence the term 'default gateway' you can see on every PC IP settings.
To answer your first Q - a gateway in many cases would handle different protocols.

Can gateway handle different protocols?


Prove that if $\gcd(m,n)=d$, then $\frac{n}{d}$ is the minimum $x$ such that $mx$ is divisible by $n$

Question: I am looking for the proof in the title because I am trying to prove that if $G$ is a cyclic group of order n with generator $a$, then the subgroup generated by $a^m$ has order $n/(m,n)$. I already understand that the order of the group is the same as the order of the generator, but I fail to grasp how the order can be related to gcd.
I know there is a related question in : Let $G$ be a cyclic group of order $n$. Prove that every subgroup $H$ of $G$ is of the form $<a^m>$ where $m$ is a divisor of $n$.. But I am interested in the evaluation of the order of the subgroup.
Answer: Since $\gcd(m, n) = d$, from Bézout's identity, $\exists\, p, q$ such that $p m + qn = d$.
Suppose $\exists \,x >0$ such that $n|mx$, then $n|dx$, which means $x \geq \frac{n}{d}$. We can easily verify that $n|dx$ when $x = n/d$, thus it's the minimum.
Answer: We have that $n|mx$ and $m|mx$ which implies $l=lcm(m,n)|mx\Rightarrow\ mn|mdx\Rightarrow\ n|dx\Rightarrow\ x\ge\frac nd$
Answer: If you are using this in an exercise in Abstract Algebra we can accept this as an established arithmetic result that everyone accepts.
The proof would be $n = n'd$ and $m = m'd$ for some integers $n',m'$.  If $n'$ and $m'$ had any factors $g$ in common then $gd$ would be a common divisor of $n$ and $m$ but $d$ is the greatest common divisor of $m$ and $n$ so $m'$ and $n'$ are relatively prime.
then if  $n$ divides $mx$ that would be the same as $n'$ divides $m'x$ and and as $n'$ and $m'$ have no factors in common that would mean $n'$ divides $x$.  Clearly the smallest $x$ that is divisible by $n'$ is $x = n'= \frac nd$.
....
or, arghh, as AnotherJohnDoe points out $n$ dividing $mx$ means $mx$ is  common multiple of $n,m$ and the least such number would be the least common multiple ... which is $\frac {mn}d$.  In the back of my mind I knew it was that simple but somehow the exact words didn't come out of my typing fingers.
Answer: Isn't that implicit in the definition of $\gcd$ ? if $mn= d*x$ and $d$ is maximum, then $x$ is minimum.
Answer: Note $\ n\mid mx,nx\iff n\mid (mx,nx)\!=\! \overbrace{(m,n)}^{\large d}x \iff n/d\mid x,\, $ using the GCD Distributive Law
This proof is more general than proofs using Bezout since it works in domains like $\,\Bbb Z[x],\, \Bbb F[x,y]$ where gcds needn't have Bezout linear form, e.g. $(2,x) = 1 = (x,y)$


Csv file with first row as keys

Question: I do not understand what I'm doing wrong
I assigned the dictionary key (mydict) to the first column
With the command:
print(mydict.get('000000'))

I wanted to have the ouput of the REGISTRATION value connected with DEVICE_ID.
Example:
print(mydict.get('000000'))

output
OK-7777

I've been trying to solve this problem for a long time and I hope you can help me, thank you very much!
Code:
import csv

if __name__=="__main__":
    mydict = {}
    reader = csv.reader(open("aerei.csv", "r"))
    for rows in reader:
        k = rows[0]
        v = rows[1]
        mydict[k] = v

        print(mydict.get('000000'))

#print (mydict)

aerei.csv
"DEVICE_ID","REGISTRATION"
"'000000'","'OK-7777'"
"'000001'","''"
"'000002'","'OY-XRG'"

Comment: `dict.get` doesn't assign values, it retrieves them
Answer: It seems your print command is inside the for-loop, so it didn't finish reading all entries yet.
Also your csv file seems to have quotes inside quotes, so you want to remove them:
for rows in reader:
    k = rows[0].strip('"\'')
    v = rows[1].strip('"\'')
    mydict[k] = v
print(mydict.get('000000'))

Csv file with first row as keys


Por que usar um ponteiro nesse algoritmo?

Question: Quando retiro o código não funciona. Por que?
E por que o algoritmo de insertion sort é apropriado apenas para lista de pequenas entradas, tipo array e list (pequena)?
 void insert_sort(int *vetor, int TAM){
     int i, j, aux;
     for(i = 1; i < TAM; i++){
         aux = vetor[i];
         for(j = i; (j > 0) && (aux < vetor[j - 1]); j--)
             vetor[j] = vetor[j - 1];
         vetor[j] = aux;
     }
 }

Comment: Eu respondi a outra pergunta, mas não devia, se é outra pergunta, faça separado.
Answer: Você quer classificar uma sequencia de valores, certo? Se passar um int está passando só um valor.
Se criar uma sequência de valores em algum lugar pode só passar o endereço de onde está esta sequência e o algoritmo pode acessar esses valores e fazer o que ele precisa em cada um dos elementos.
Pode estar perguntando porque não passar a sequência toda. Provavelmente ela é muito grande para copiar tudo de um lugar para outro, o que não tem necessidade alguma de fazer isto.
Tem uma pergunta que fala sobre o uso prático do ponteiro.
O principal problema do algoritmo de classificação por inserção é que ele tem complexidade quadrática (O(n2)) no pior caso. Então para apenas 1000 elementos em ordem reversa ele tem que fazer 1 milhão de operações de cópias de dados, isto é trágico. Mas em pequenos volumes isto não é impactante e por manter localidade de referência o cache é muito mais eficiente e pode ser mais rápido do que algoritmos que fazem menos cópias mas precisam comparar mais ou que as comparações custam mais, ou que precisam de mais memória.
Comment: Dúvida esclarecida quanto ao uso do ponteiro e a complexidade. Thanks !


Set y axis limit in Pandas histogram

Question: I am using Pandas histogram.
I would like to set the y-axis range of the plot.
Here is the context:
import matplotlib.pyplot as plt
%matplotlib inline

interesting_columns = ['Level', 'Group']

for column in interesting_columns:
    data['ranking'].hist(by=data[column], normed=True)

There is a range argument that can filter x-values, but I am unaware of the y equivalent:
hist(by=[column], normed=True, range=[0, 1]) #working argument
hist(by=[column], normed=True, y_range=[0, 1]) #hypothetical argument

I've read a lot of different methods for changing plot ranges using plt attributes. They do not seem to work in a loop and for subplots.
I am struggling to grasp the right way to approach this problem.
Comment: have you tried assigning a handle to `hist` like: `h1=hist(...)` and then looking at what methods does `h1.*` have? It probably has something like `h1.set_ylim` or something similar
Answer: If you use
data['ranking'].plot.hist(ylim=(0,1))

(mind the .plot in the syntax!) it should work.
Comment: Please note: `data['ranking'].hist(ylim=(0,1)) ` does not work, but `data['ranking'].plot.hist(ylim=(0,1))` does. This is a bit confusing, because without the keyword both work.
Comment: @MartinThoma Thank you for your comment, but why is it the case?
Comment: Thank you. This applies more generally to all plotting options!
Comment: @LongLe I have no idea, but I'm interested in the answer as well. Maybe you could ask another question and post the answer here?
Answer: You can simply add option sharey=True to make all subplots share the same yaxis limit, similiary using sharex=True for xaxis
data['ranking'].hist(by=data[column], sharey=True)
Comment: Code-only answers are considered low quality: make sure to provide an explanation what your code does and how it solves the problem. It will help the asker and future readers both if you can add more information in your post. See [Explaining entirely code-based answers](https://meta.stackexchange.com/questions/114762/)
Comment: This makes all histograms have the same y-axis, but how do you limit their height?
Comment: @giusti  When all histograms share the same y-axis, the limit of y-axis is determined by the range of y values of all data points. One way (may not be the best) to limit the height is to remove the data points that's outside the y range beforehand.

Set y axis limit in Pandas histogram


Correct image path to use in template files of custom themes

Question: I'm creating a custom theme. Under my theme's folder, there is an images folder where I've put some pictures. I want to use these images in my various template (.tpl.php) files using HTML  tag... but the problem is how do i get correct path for these images (the src attribute)?
I've searched for a while but didn't get any solutions. Please help.
EDIT: I'm using nice urls (http://mydrupalsite.com/a/b/c/d) - type URLs. So, if the image src begins with / (or any relative path) it would break.
Answer: I think these functions could be useful in your templates:
print base_path() . path_to_theme();

path_to_theme() Return the path to the current themed element.
base_path() The base path of the Drupal installation.
for example, I have an image called bg-bar.png inside images directory in my template directory called garland. then I can use base_path() and path_to_theme() to get the path to the image, for example inside node.tpl.php:
print '';

Update: if you want to use the current domain, you can use global $base_root:
  $address = ''.base_path() . path_to_theme() .'/images/bg-bar.png';
  global $base_root;
  echo '';

I hope information be useful.
Comment: I've tried all these. Problem is, `base_path()` returns '/' - which does not help when I'm using nice urls (i.e. http://mysite.com/a/b/c) - in this case image source becomes '/path-to-theme/...../image.png' - which does not work. I need to use `http://` instead of `/` in image source I guess.
Comment: I updated my answer with information related with `http://`.
Comment: If you are using 'nice urls' I guess that these urls are controlled by a rewrite process, so I think that you can add exeptions. For example, review if from `.htaccess` file you can control this rewrite process, and add the respective condition with `RewriteCond` to exclude images.
Comment: Thank you! I have been looking all over for a solution for this problem!
Answer: Since my image was in a conditional block, the above syntax posed some problems and the following worked for me.   However, I am not sure if it is advisable from a maintenance perspective:
src='<?php print base_path().path_to_theme().'/images/iphone.png' ?>'


tmux, Solarized, and terminfo

Question: This is a very specific issue but, based on what I've seen online, a surprisingly common one. I'm on a rather old version of Scientific Linux 5, which is based on Red Hat. I use vim with the Solarized vim color scheme, and my TERM environment variable is usually set to xterm-256color. This worked fine until I started using tmux. On non-empty lines in vim, the color scheme only extended to the end of the document's characters, the remaining whitespace being plain back background.
The stock fix for this in online guides is to set TERM='screen-256color'. However, upon doing this I would get the ominous warning: WARNING: terminal is not fully functional  -  (press RETURN), when trying to do innocuous things like read man pages. However, everything seemed to be working fine, and the Solarized bug was fixed.
I've found a functional fix - using TERM='xterm-256color' by default and adding this line to my .bashrc:
alias v='function _vim(){ TERM='screen-256color'; vim $1; TERM='xterm-256color'; };_vim'
but it seems like a hack. Anecdotally, I've also set alias tmux='tmux -2', which is a common suggestion with color-scheme-related issues.
I also know that the terminfo screen-256color is available on my machine.
So, really, the main befuddling thing is that, when using TERM='screen-256color', I'm getting those warnings about full functionality when nothing seems to be wrong.
I don't have root access, so ideally any fix suggestions wouldn't need that.
EDIT: I should mention that TERM='screen-256color-bce' gave the same problems as TERM='screen-256color'.
Comment: `screen-256color` is the recommended `TERM` for tmux, did you try putting `set -g default-terminal "screen-256color"
` in `~/.tmux.conf`?
Comment: @romainl: I did, but the same issue was occurring. It seems that there's some issue with my system causing the "terminal not fully functional" warning to be raised when I'm running `screen-256color`, regardless of the context. This is despite the fact that my machine has `screen-256color` installed, and seems to be the root problem. Do you have any idea why this might be the case? Might it be possible to somehow install a new version of `screen-256color` in a local directory (I don't have root) and redirect the `terminfo` to it?
Answer: The user's environment is not specified, but likely using bash and less (Scientific Linux 5 does not have more).
The package list on Scientific Linux 5's ftp site, shows ncurses-5.5-24.20060715.src.rpm, which does not include screen-256color (it was added to ncurses in October 2006).  That system might have the later terminal database by some post-install change.
An application using termcap would not see this terminal description.  Scientific Linux's bash and less programs could have used termcap rather than terminfo.  A quick check of the changelog for bash-3.2-21.el5 says
* Fri Feb  1 2008 Miroslav Lichvar <email@example.com> - 3.2-21
- Link with libtermcap

On some systems, a missing termcap entry will cause a warning.  But with Scientific Linux 5, the given warning message comes from less, which checks its terminal description (using the termcap interface), to ensure that it can clear the remainder of the current line, the remainder of the screen and the entire screen.
In Scientific Linux 5, the less package is built with ncurses.  A problem with less using TERM=screen-256color would be one of these possibilities

the screen-256color entry is not really installed, or
there is some problem with the termcap interface provided by ncurses.

While there were ongoing performance-fixes for the screen program around this time, the former seems the more likely, as seen in this discussion of a poorly-written entry for screen-256color in early 2006: Re: screen-256color terminfo entry?.  What I get from reading this is that there was some poorly-written terminal description (not part of ncurses) which produced the problem.  By the time it was proposed for inclusion in ncurses (October 2006), the problem had been repaired.  In any case, it would have been corrected at that point.

tmux, Solarized, and terminfo


Style the  that has child elements

Question: I'm trying to create a top menu with a dropdown submenu function.
I want to target the list items witch have a submenu (child element) attached to it. So that i can style them with a different color list style etc.
HTML:

Home

Parrent Link

Child Link

Child Link

Parrent Link

Child Link

Child Link

Child Link

Child Link

Child Link

About

Gallery

Contact

So each Parrent link get another style than the rest.
Comment: `nav > ul > li > ul > li > ul > li { ... } `?
Comment: How do you mean like this? [**DEMO HERE**](http://jsfiddle.net/Ruddy/6uk2x/)
Comment: Best solution would be to give the parent `'s` a class
Comment: Take a look at this post http://stackoverflow.com/questions/5281556/is-there-a-css-way-to-add-an-arrow-if-a-ul-has-a-ul-child
Comment: @Legarndary Take a look at my solution. Is it helpful?
Comment: @ItayGal Yes, it was very helpfuf, it does the trick.
If somebody else wanne use this but not wanna target the first parrent just replace "if(parent.is('li')){" with "if(parent.is('ul li ul li')){"
Answer: You can do it with JQuery: example
$(function(){
    $('li').each(function(){
        var parent = $(this).parent().parent();
        if(parent.is('li')){
            parent.addClass("colored");
        }
    })
});

This solution assumes that your HTML is valid and you use
 and
 correctly.
Answer: You can't select an element based in descendent elements. Then you can't have a selector like this:

select all
 tags that contain an
 tag

In the other way you can

select all
 tags inside a
 tag

The best you can do is assign a class:

Child Link

Child Link

Parrent Link

Child Link

Child Link

Child Link

Child Link

Child Link

Comment: It's a shame. If only we could have XPath in CSS, that'd be awesome. `//li[./ul]`
Answer: I Would change the ul.class every time i make a new list.
so that, if the ul li has children, it will change automatically, if i want to have children there.
Answer: You just have to use CSS selectors as follows:
ul > li > li {
   // your css code here
}

You havethe official documentation in the W3C site.
No need tu use id's or class tags
Comment: With this you target all `li` direct childs of an `ul` tag . Not all `li` elements with an `ul` inside. OP wants *the list items witch have a submenu (child element)*
Comment: You are right, sorry! I did not understand the question well, I editted my answer so now it targets the list elements

Style the  that has child elements


event-b: is it possible generate sequence from ... to ... of prime numbers via lambda in one expression?

Question: I wonder if it's possible to generate a sequence of prime numbers with just one lambda expression in event-b. This is what I have so far:
@axm1 primeSet = {x∣ x ∈ 1‥100 ∧ ¬(∃y·y < x ∧ y > 1 ∧ x mod y = 0)} ∧ finite(primeSet)
@axm2 primeSeq ∈ 1‥card(primeSet) >->> primeSet
@axm3 ∀a,b,c,d·a↦b ∈ primeSeq ∧ c↦d ∈ primeSeq ∧ a↦b ≠ c↦d ⇒ (a < c ⇒ b < d)

@axm1 generates a set of primes, @axm2 defines the type of the sequence and @axm3 constrains this set further to a deterministic solution.  I have no idea how to do this with one lambda expression and i don't think it's even possible but I want to know what others think.
Comment: I think this is a reasonable question for SO, but if you don't get a satisfactory answer, you might also try [CompSci](http://cs.stackexchange.com/).
Comment: event-b is not covered by this site, until now, is it? strange...
Comment: What do you want to achieve? Generally, a single equation of the form `primeSet = ...` or must it really be a lambda expression of the form `primeSet = (%x. ... )`?
Comment: i had specific interest in the lambda expression. it is of no urgency as it originated from a mis-read excercise when I had the event-b course... I'm just curious if it'd be possible as my tutor back then thought it wouldn't.
Answer: I believe this lambda function satisfies your request:
@axm1 primeSeq = {size↦X| size∈ℕ ∧ X⊆ℕ ∧ ∀x·x∈X ⇒ (x∈1‥size ∧ (∀y·y∈1‥x ∧ y≠1 ∧ y≠x ⇒ x mod y ≠ 0))}

Comment: unfortunately this doesn't work... what does your primeSeq-Set look like after this? on my machine it's not the same as the above
Answer: My first attempt to the problem would be a comprehension set that is defined recursively (for simplicity, I just look at the infinite sequence of prime numbers, but it would be easy to add an additional condition like i<size to get a finite sequence):
axm1:  primeSeq1 ∈ ℕ1 --> ℕ1
axm2:  primeSeq1 = { i↦p ∣ i∈ℕ1 ∧ p∈ℕ ∧
                           ( (i=1 ⇒ p=2)
                           ∧ (i>1 ⇒ ( p>primeSeq1(i−1) ∧
                                      ∀x·(x∈primeSeq1(i−1)‥p−1 ⇒
                                          ∃a,b·(a∈2‥x−1 ∧ a∗b=x)) ∧
                           ¬(∃a,b·(a∈2‥p−1 ∧ a∗b=p))     )))}

In words: We have a hard-coded base case that 2 is the first prime number. Then for i>1: p is the ith prime number if it is larger than the (i-1)th prime number (recursion!), all numbers between the last prime and p are not primes and p itself is a prime number.
This version still needs two axioms, one just for type checking, the other with the definition. Rodin does not accept it without axm1. And it is not a lambda expression.
Now we use an ugly hack: We use a comprehension set variable ps as a local variable to define the recursive set to eliminate the need for axm1:
axm3:  primeSeq2 = { j,ps · j∈ℕ1 ∧ ps∈ℕ1→ℕ ∧
                            ps = { i↦p ∣ i∈ℕ1 ∧ p∈ℕ ∧
                                        ( (i=1 ⇒ p=2)
                                        ∧ (i>1 ⇒ ( p>ps(i−1) ∧
                                                   ∀x·(x∈ps(i−1)‥p−1 ⇒
                                                       ∃a,b·(a∈2‥x−1 ∧ a∗b=x)) ∧
                                                   ¬(∃a,b·(a∈2‥p−1 ∧ a∗b=p))     )))}
                          ∣ j↦ps(j) }

Please note, that we used another syntactical form of a comprehension set where we added an expression (j↦ps(j)) for each element of the set.
So primeSeq2 is defined by using just one expression. But it is not a lambda expression.
Again we use a trick. We surround the comprehension set by a lamda expression:
axm4:  primeSeq3 = (λk·k∈ℕ1 ∣ primeSeq2(k))

So we have a lambda expression. To have it in one definition, we just copy primeSeq2 into the expression:
axm5:  primeSeq4 = (λk·k∈ℕ1 ∣ { j,ps · j∈ℕ1 ∧ ps∈ℕ1→ℕ ∧
                                       ps = { i↦p ∣ i∈ℕ1 ∧ p∈ℕ ∧
                                                   ( (i=1 ⇒ p=2)
                                                     ∧ (i>1 ⇒ ( p>ps(i−1) ∧
                                                                ∀x·(x∈ps(i−1)‥p−1 ⇒
                                                                    ∃a,b·(a∈2‥x−1 ∧ a∗b=x)) ∧
                                                                ¬(∃a,b·(a∈2‥p−1 ∧ a∗b=p))     )))}
                                     ∣ j↦ps(j) }(k))

So, to answer your question: Yes it is possible to define such a sequence with just one lambda expression. But the result is extremely messy :)
I didn't prove (and don't plan to do it!) any properties about the expressions above. So there might be some errors in it. I just type checked the formulas.
Update: After writing down the solution above, I realized that you don't need the recursion at all. You can use your original definitions of primeSet, primeSeq, etc.  and put it into a comprehension set of the form
primeSeq1 =  (%i . i:NAT1 | ({ primeSet, primeSeq, ... . Definitions | 0|->primeSeq }(0))i)

But still, even the WD conditions would be very hard to prove.


PHP Command to Calculate Percentage of MySQL rows

Question: Firstly, I am new to PHP so I'm still learning. I have a PHP program to display a count of rows on MySQL which frequently changes. This is the echo I am using to display count and percentages -
echo"
{$row['Name']}	<td {$row['COUNT(tag_logs.tag_no)']}/75	{$row['(COUNT(tag_logs.tag_no)']}%

The first count function works just fine. For the second iteration of...
{$row['(COUNT(tag_logs.tag_no)']}%

...I would like to divide the count by 75 and multiply by 100.
I have tried assigning 75 to a string, such as -
$perc = 75;

I also tried a few variations to carry out division only -
{$row['(COUNT(tag_logs.tag_no)'/75]}%

{$row['(COUNT(tag_logs.tag_no)'/$perc]}%

However, I've had little luck as I'm unsure about where to plug in the variable. This is the error I receive -

Warning: A non-numeric value encountered in
  /Library/WebServer/Documents/count.php on line 16
Comment: What was wrong with the answer I gave to the question you subsequently deleted?
Comment: Apologies since I don't exactly remember you answering my question in particular. Would you mind reminding me of your previous answer?
Comment: I have reposted my answer.
Answer: You need to divide the value you are reading outside the quoted string. Try this:
echo "
{$row['Name']}	{$row['COUNT(tag_logs.tag_no)']}	" . round($row['COUNT(tag_logs.tag_no)'] / 75 * 100, 2) . "%
";

I would also suggest that you rewrite your query with an alias on the COUNT e.g.
COUNT(tag_logs.tag_no) AS tag_cnt

so that you can just refer to it as $row['tag_cnt'] instead of $row['COUNT(tag_logs.tag_no)']. This will also save you time if you change the expression in the query later as you won't have to change the PHP as well.
Comment: Thank you so much for your answer. I apologize about not getting around to responding the last time. If you wouldn't mind, could you very briefly explain what I did wrong in my initial code?
Comment: @OloOlo no worries. The problem with your original code was that you were doing everything inside the quoted string, and you have to do math outside quotes. Enclosing something in `{}` inside a quoted string only works for variables.


missing value patterns

Question: I am doing some data preparation with Python using Pandas and I am working with a dataset that has about 80 variables with missing values and I want to capture any patterns of missingness to cut down on the amount of missing value indicators I have but I am having trouble finding any good strategies for doing this.  here is an example of what I am getting at:
<code>MISS_1 MISS_2 MISS_3 MISS_4 MVP1 MVP2 MVP3 MISS_STR
     0      0      1      0    0    0    1     0010
     1      0      1      0    1    0    0     1010
     1      1      1      1    0    1    0     1111
     1      1      1      1    0    1    0     1110
     1      0      1      0    1    0    0     1010
     0      0      1      0    0    0    1     0010
     0      0      1      0    0    0    1     0010
     0      0      1      0    0    0    1     0010
     1      0      1      0    1    0    0     1010
</code>
One thing I tried was to create a string variable that concatenated all the missing value indicator variables like the 'MISS_STR', unfortunately the number of unique values in this variable was around 2000. Also, I know I am missing patterns that may be useful because if a pattern exists between Variable_1 and Variable_2 and Variable_3 and Variable_4 are missing completely at random, then concatenating them as strings will not capture the pattern between Variable_1 and Variable_2.  Is there a better way of doing this?  A good clustering algorithm perhaps?  Whatever I do, I need to be able to do the same thing to my scoring data.
Answer: If I understand you correctly, you have several binary features and you would like to know if they have any correlation. Exploratory work is always hard but I would think something like Principal Component Analysis would give you a good idea of the relative correlations between your features.
Also, you would have much better luck if you removed the coding part from the question. While python is great, questions belong in Stack Overflow.

missing value patterns


How long until mod_proxy_balancer reverts back from hot-standby to primary

Question: I have found just one blog entry that claims that when using status=+H
BalancerMember http://126.96.36.199:1234 status=+H

"When the default service is back on-line mod_proxy_balancer will pick that up within about 60 seconds or so and revert back to forwarding all requests to it."

But I can't find any mention of this in the documentation (and if there is any way to affect the time period).
Can anyone provide some documentation that supports this claim?
Answer: It's mentioned numerous times in the Apache documentation for mod_proxy

Key=retry     Default=60
  Connection pool worker retry timeout in
  seconds. If the connection pool worker to the backend server is in the
  error state, Apache will not forward any requests to that server until
  the timeout expires. This enables to shut down the backend server for
  maintenance, and bring it back online later. A value of 0 means always
  retry workers in an error state with no timeout.

BalanceMember inherits all keys provided by ProxyPass, so you can use
#Retry balance members every 60 seconds
BalanceMember http://app1/ retry=60

However the status=+H implys a balance member will be a 'hot standby'. So with the config
BalanceMember http://app1/ retry=30
BalanceMember http://app1-backup/ retry=60 status=+H

When app1 goes down, the hot standby will be used instead. After 30 seconds Apache will retry with app1, if it fails it will switch back over to the hot standby. 5 seconds later, app1 comes back online, but Apache will still use app1-backup until the timeout has expired, then after another 30 seconds when Apache retrys the main server it will succeed. Under normal usage, app1-backup will never be used.


preprocess function call - $vars[node_title] does not work as a parameter, while $vars['node-title'] does

Question: I am writing a preprocess function. I provided a linkIt function that does the linking for me:
function linkIt($what, $where) {

return '' . t($what) . '';

}
If I call it this way:
$test= linkIt('XXX', $vars[node_url]);

it produces a Drupal error 'Use of undefined constant node_url - assumed 'node_url''. If I call it
$test= linkIt('XXX', $vars['node_url']);

with quotes around node_urlit works fine.
The former syntax is properly evaluated if I do not pass it as a function paramter, for example in
$vars['opis'] = '' . t('XXX') . ''

Why is it so?
Answer: Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in the future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
See PHP:Arrays - Manual Chapter "Array do's and don'ts"


Category theory and real closed fields

Question: On the nlab page for real-closed fields, these following statements are made pertaining to their category theoretic nature.

(1) In fact, the category of real closed fields and order-preserving field homomorphisms is a full subcategory of the category of fields and field homomorphisms.
(2) Theorem. The full inclusion of the category of real closed fields and field homomorphisms to the category of ordered fields and ordered field homomorphisms has a left adjoint.

The latter one has a proof following it, but regardless I am interested in seeing the definitive meaning behind these notions. I checked the given references but didn't find anything in the vein of these statements. I'm interested and can extract good intuition on the matters but I would like if anyone has any good sources concerning the relationship between category theory and real closed fields. Thanks in advance.
Comment: By "the definitive meaning", do you mean translating these statements into less category-theoretic language? The first statement just means that every field homomorphism between real closed fields is automatically order-preserving, which follows immediately from the argument that the order is defined in terms of the field operations.
Comment: Cont: You shouldn't necessarily expect a reference on these matters. Full subcategories whose inclusion admits a left adjoint are a dime a dozen, so there's no reason to expect that a more expansive treatment in this particular context exists.
Comment: Thanks for the response. I misread the first one in a different context and your comment re-addressed me on that matter. I understand now.
Answer:
A subcategory $\def\c{\mathcal} \c B\subseteq\c A$ is full, if it is determined by its objects within $\c A$ so that every arrow $B\to B'$ of $\c A$ with $B,B'\in\c B$ is actually in $\c B$.
In this case it means that a field homomorphism between real closed fields preserves the order.
The inclusion functor $\c B\hookrightarrow\c A$ has a left adjoint iff $\c B$ is a reflective subcategory of $\c A$, which means that every object $A\in\c A$ has a reflection in $\c B$, which is an arrow $A\to B$ with $B\in\c B$ through which every arrow $A\to B'$ factors through uniquely.
Note that the left adjoint is just the reflection functor.
In this case, the real closure of an ordered field is its reflection.
Answer: There is an additional property here to that of reflective subcategory which is general enough to be worth mentionning.
-Let $\mathcal{A}$ be a category. let $\mathcal{P}$ be a full subcategory of $\mathcal{A}$. For an object $a$ of $\mathcal{A}$, we say that an ordered pair $(f,b)$ where $f$ is an arrow $a \rightarrow b$ in $\mathcal{A}$ is an extension of $a$.
We define the category $\mathcal{A}_a$ of extensions of $a$ as that whose objecs are extensions and whose morphisms are commutative triangles between extensions. $\mathcal{A}_{a,\mathcal{P}}$ denotes the full subcategory of $\mathcal{A}_a$ where the codomains in extensions are objects of $\mathcal{P}$.
-Let $P$ be a quality of extensions which is conservatively transitive: if $(f,b)$ is an extends $a$ and $(g,c)$ extends $b$, then $(g \circ f,c)$ satisfies $P$ if and only if both $(f,b)$ and $(g,c)$ do.
We then define the category $\mathcal{A}_{a,P}$ of $P$-extensions of $a$ as the full subcategory of $\mathcal{A}_a$ whose objects are $P$-extensions.
We say that an object of $\mathcal{A}$ is $P$-maximal if its $P$-extensions come from isomorphisms.
Then if every object $a$ of $\mathcal{A}$ has a $P$-extension  $(\varphi_a,a_P)$ with codomain $a_P$ in $\mathcal{P}$, and which is initial in $\mathcal{A}_{a,\mathcal{P}}$, then any assignment $a \mapsto (\varphi_a,a_P)$ defines a functor from $\mathcal{A}$ to $\mathcal{P}$ which is left adjoint to the inclusion $\mathcal{P} \rightarrow \mathcal{A}$. This is just the notion of reflective subcategory.
The additional property is that then for every object $a$ of $\mathcal{A}$, $a_P$ is $P$-maximal, that the functor $\mathcal{A}\rightarrow \mathcal{P}$ is essentially onto the category of $P$-maximal objects of $\mathcal{P}$, and $(\varphi_a,a_P)$ is terminal in $\mathcal{A}_{a,P}$.
For real closure, the relevant property in the category of ordered field is to be an algebraic extension. For ordered rings with injective morphisms, the property of being a degree $1$ extension yields the reflective category of ordered fields and reflective functor of fraction field. For ordered fields with cofinal morphisms, the property of being a dense extension gives the category of Cauchy-complete ordered fields with Cauchy-completion functor.

Category theory and real closed fields


jq: Add field to collection deep in nested structure, calculated from other fields at the same level

Question: I'm looking for someone who can give me a hint with jq here - it seems I'm missing out on something.
My JSON source would be similar to this:
[
    {
        "cluster": "one",
        "slots": [
            {
                "instances": [
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 0,
                                "healthy": 4
                            },
                            {
                                "name": "B",
                                "unhealthy": 2,
                                "healthy": 2
                            }
                        ]
                    },
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 6
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 2
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "cluster": "two",
        "slots": [
            {
                "instances": [
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 1,
                                "healthy": 9
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 10
                            }
                        ]
                    },
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 9
                            },
                            {
                                "name": "D",
                                "unhealthy": 0,
                                "healthy": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

What I need would be a new "status" field in each innermost collection as the sum of the "healthy" and "unhealthy" states, like this:
[
    {
        "cluster": "one",
        "slots": [
            {
                "instances": [
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 0,
                                "healthy": 4,
                                "status": 4
                            },
                            {
                                "name": "B",
                                "unhealthy": 2,
                                "healthy": 2,
                                "status": 4
                            }
                        ]
                    },
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 6,
                                "status": 6
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 2,
                                "status": 2
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "cluster": "two",
        "slots": [
            {
                "instances": [
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 1,
                                "healthy": 9,
                                "status": 10
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 10,
                                "status": 10
                            }
                        ]
                    },
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 9,
                                "status": 9
                            },
                            {
                                "name": "D",
                                "unhealthy": 0,
                                "healthy": 14,
                                "status": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Is there a way to iterate in this manner:
jq '.[].slots[].instances[].services[] += { "status": ($iterator.healthy + $iterator.unhealthy) }'
In all my attempts so far, I either couldn't access the elements at the same level for the calculation... or the rest of my data got dumped.
Answer: You're looking for |= operator.
.[].slots[].instances[].services[] |= (.status = .unhealthy + .healthy)

Comment: Exactly what I needed - thank you for pointing me in the right direction!


Why is my predictor variable being split up in a logistic regression?

Question: I am running a logistic regression. Treatment is a factor with 3 levels. I am assuming that intercept is one of these 3 levels (negative control in this case). Is there a reason the equation is splitting the predictor variable like this?
Call:
glm(formula = propgfp ~ treatment, family = quasibinomial, data = frass4glm)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.7631  -0.0001   0.6031   0.6964   0.8529

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)         -19.87    3390.23  -0.006    0.995
treatmentFrass       22.64    3390.23   0.007    0.995
treatmentPositive    22.64    3390.23   0.007    0.995

(Dispersion parameter for quasibinomial family taken to be 1.324805)

    Null deviance: 100.322  on 34  degrees of freedom
Residual deviance:  25.863  on 32  degrees of freedom
AIC: NA
```

Comment: You have a predictor with three levels. Two levels plus one (the intercept) is three. What is giving you trouble?
Answer: Your variable has three levels. One is subsumed by the intercept. One is the binary variable treatmentFrass that is $1$ when the treatment is Frass and zero otherwise. One is the binary treatmentPositive that is $1$ when the treatment is Positive and zero otherwise. This way, only the intercept is active when the treatment is neither Frass nor Positive; the parameter on treatmentFrass gives you the estimated difference in the outcome between the omitted category (that is subsumed by the intercept) and the Frass group; and the parameter on treatmentPositive gives you the estimated difference in the outcome between the omitted category (that is subsumed by the intercept) and the Positive group.
This is the same as why a three-factor variable in an ANOVA regression is split into two categories with the third subsued by the intercept.
Comment: @LiamTSullivan It would help if you explained what you meant by "the effect of treatment as a whole". This makes it sound like you lack a control group.
Comment: Fair point. Thanks for the correction. The positive and negative are the respective controls, so I am looking for the effect of the frass treatment against these two. I think I see my issue.
Comment: For clarity. I misunderstood your explanation initially, thanks all for the help here! Statistics is a weak point for me and I am glad to have your input.


Auto play em video iframe

Question: Estou tentando adiciona autoplay nessa Iframe mas não estou conseguindo, será que o servidor não aceita esse recurso?
<code> <iframe width="640" height="360" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="https://player.r7.com/video/i/59ce6d36bc1f62ee48000cea?layout=wide252p&full=true" mozallowfullscreen webkitallowfullscreen allowfullscreen></iframe>
</code>
Comment: Sei que no youtube basta passar `autoplay=1` na URL. Você tentou isso?
Comment: esse video é do site R7 e não estou conseguindo
Comment: Deve haver algum parâmetro passado na URL que só os técnicos do R7 sabem qual é.
Comment: No site deles, o video está em auto player
Answer: Testei varias formas de fazer, via html não é possível no R7. Então parti para o js que também não é possível, testei o seguinte codigo:
https://jsfiddle.net/92jcg94v/
Porém ele retorna o seguinte erro:

Esta bloqueado acesso via js, por tanto, acredito que não seja possível fazer isso neste video.
Comment: Parece que ele só da Autoplay no proprio site. no recurso iframe não vai
Comment: exato, é bloqueado a chamada de outro domínio.

Auto play em video iframe


How to compute the topological space of fibered product of schemes?

Question: I know that the topological space of fibered product of schemes is generally distinct to the usual Cartesian product of toplogical spaces of schemes. Then how can we compute the top. sp. of fibered product of sch. explicitly? Is there any systematic procedure that I can do?
Actually this question arises from when I read the Hartshorne's Algebraic Geometry. In section 4 on Chapter2, the example says that the affine line with doubled origin(I may denote it by X) is not separated over the field k. In the explanation of the book, I can see that the top. sp. of the fibered product of two X . However, I cannot understand how to compute it. (If you want the exact statement, see the p.96 of Hartshorne)
Answer: If $X,Y$ are locally ringed spaces over a locally ringed space $S$, then one can write down their fiber product $X \times_S Y$ explicitly. If $X,Y,S$ are schemes, then this fiber product is a scheme, so that it is the fiber product in the category of schemes. This provides an alternative (and in my opinion far better) construction of the fiber product of schemes which is not well-known as it should be. You can find it here. Let me sketch it:
Let $f : X \to S$ and $g : Y \to S$. The underlying set of $X \times_S Y$ consists of those triples $(x,y,s,\mathfrak{p})$, where $(x,y,s)$ lies in the underlying topological fiber product, i.e. $x \in X, y \in Y, s \in S$ and $f(x)=s=g(y)$, and $\mathfrak{p}$ is a prime ideal in $\kappa(x) \otimes_{\kappa(s)} \kappa(y)$, the tensor product of the residue fields. In other words, the fiber of the map from $X \times_S Y$ to the topological fiber product is precisely $\mathrm{Spec}(\kappa(x) \otimes_{\kappa(s)} \kappa(y))$ at the point $(x,y,s)$. Note that $\mathfrak{p}$ can also be equivalently described as a prime ideal $\mathfrak{q}$ in the tensor product of the local rings $\mathcal{O}_{X,x} \otimes_{\mathcal{O}_{S,s}} \mathcal{O}_{Y,y}$, which restricts to the maximal ideals in $\mathcal{O}_{X,x}$ and $\mathcal{O}_{Y,y}$ (and therefore also in $\mathcal{O}_{S,s}$, since $f^\#_x$ and $g^\#_y$ are local).
The topology looks as follows: If $U \times_T V$ is a basic open subset of the topological fiber product (i.e. $U \subseteq X, V \subseteq Y, T \subseteq S$ open wih $f(U) \subseteq T \supseteq g(V)$) and $f \in \mathcal{O}_X(U) \otimes_{\mathcal{O}_S(T)} \mathcal{O}_Y(V)$, then $\Omega(U,V,T,f) \subseteq X \times_S Y$ consists of those $(x,y,s,\mathfrak{q})$ such that $x \in U, y \in V, s \in T$ and that the image of $f$ in $\mathcal{O}_{X,x} \otimes_{\mathcal{O}_{S,s}} \mathcal{O}_{Y,y}$ is not contained in $\mathfrak{q}$. These sets form a basis for a topology on $X \times_S Y$. The structure sheaf is defined in such a way that on local rings $\mathcal{O}_{X \times_S Y,(x,y,s,\mathfrak{q})} = (\mathcal{O}_{X,x} \otimes_{\mathcal{O}_{S,s}} \mathcal{O}_{Y,y})_{\mathfrak{q}}$. A general section in $\mathcal{O}_{X \times_S Y}$ is a function valued in these stalks, which is locally a fraction.
Of course, all this is not needed to see that the affine line with doubled origin is not separated. And once again I cannot recommend to read Hartshorne for the basics of algebraic geometry. If $X_1$ and $X_2$ are equal affine schemes and $U$ is an open subscheme, then $X=X_1 \cup_U X_2$ is separated iff $X_1 \times_X X_2 = X_1 \cap X_2 = U$ is affine, and $U \to X_1 \times X_2$ is a closed immersion. In particular, the affine line with a doubled origin is not separated.
Comment: +1 for the Hartshorne comment.  And this alternate construction of the fiber product looks very interesting, thanks for sharing.
Comment: I appreciate the Hartshorne comment too. It was this answer of yours + the suggestion to read Liu (and others) that you gave in another post what made me change books, and I only regret not doing it sooner.
Answer: You can read the precise construction in Hartshorne's proof of the existence of the fiber product.  Suppose we have $S$-schemes $X \xrightarrow{f} S$ and $Y \xrightarrow{g} S$.  Let $S = \bigcup_i W_i$ be an affine open cover and also take affine open covers $f^{-1}(W_i) = \bigcup_{j} U_{ij}$ and $g^{-1}(W_i) = \bigcup_{j} V_{ij}$ for each $i$.  The fiber products $U_{ij} \times_{W_i} V_{ij}$ are just the spectrums of the tensor products of the coordinate rings.  Now the fiber product $X \times_S Y$ is constructed by gluing these affine schemes, on certain open subsets, first to $f^{-1}(W_i) \times_{W_i} V_{ij}$, then to $f^{-1}(W_i) \times_{W_i} g^{-1}(W_i)$, and finally over the base to $X \times_S Y$.  You can read about the gluing construction in (Marco Lo Guidice's notes, 2.3).
Basically, given schemes $X$ and $Y$ with open subsets $U \subset X$, $V \subset Y$ and an isomorphism $\phi : U \stackrel{\sim}{\to} V$, one constructs the underlying topological space of the gluing by taking the disjoint union of the spaces quotiented by the equivalence relation identifying $u \sim \phi(u)$ for each $u \in U$.
I happen to have a detailed construction of the fiber product of the affine line with double origin with itself that I wrote for homework at some point, here it is.  I've just copied and pasted without proofreading again, so there may be typos, etc. $\newcommand{Spec}{\mathrm{Spec}\ }$
Consider the affine schemes $X_1 = \Spec k[x]$, $X_2 = \Spec k[y]$.  Between the open subsets $U_1 = \{ (x - a) : a \ne 0 \} \subset X_1$ and $U_2 = \{ (y - b) : b \ne 0 \} \subset X_2$ there is a natural isomorphism $\phi : U_1 \to U_2$.  Let $X$ be the scheme obtained by gluing $X_1$ and $X_2$ along $\phi$.  Topologically, its points are equivalence classes of the disjoint union of $X_1$ and $X_2$ by the relation $\sim$ under which points $(x - a)$ are identified with their images $(y - a)$, for $a \ne 0$.  Let $\bar{U_i} \subset X$ be the images of $U_i$ by the natural maps $X_i \to X$.  Note $\bar{U_1} \cap \bar{U_2} = \{ [(x - a)] : a \ne 0 \}$.
To compute the fiber product of $X$ with itself over $\Spec k$, we follow the construction of Hartshorne of the fiber product of general schemes: first we glue $X_1 \times_k X_1$ and $X_2 \times_k X_1$ by certain open sets to obtain $X \times_k X_1$, and we glue $X_1 \times_k X_2$ and $X_2 \times_k X_2$ to obtain $X \times_k X_2$, and then we glue these together to obtain $X \times_k X$.  We can compute $X_1 \times_k X_1 = \Spec k[x] \otimes k[x] \cong \Spec k[t_1, t_2]$ and $X_2 \times_k X_1 = \Spec k[y] \otimes k[x] \cong \Spec k[t_3, t_4]$.   Let $p_1$ be the first projection map associated with $X_1 \times_k X_1$.  Note $p_1$ maps the equivalence class $[(x-a)] = \{(x - a), (y - a)\} \in X$ to $(x - a) \in X_1$ and the class $[(0)] = \{(0)\}$ to $(0) \in X_1$.  Now consider the open set $U_1' = p_1^{-1} (\bar{U_1} \cap \bar{U_2}) = \{ (t_1 - a, t_2 - b) : a \ne 0, b \in k \}$.  Similarly let $U_2' = p_2^{-1} (\bar{U_1} \cap \bar{U_2}) = \{ (t_3 - a, t_4 - b) : a \ne 0, b \in k \}$, where $p_2$ is the first projection map associated with $X_2 \times_k X_1$.  Hartshorne shows that the result of gluing $X_1 \times_k X_1$ and $X_2 \times_k X_1$ via the natural isomorphism $\phi' : U_1' \to U_2'$ is the fiber product $X \times_k X_1$.  Topologically we find it is the disjoint union of $X_1 \times_k X_1$ and $X_2 \times_k X_1$ with $(t_1 - a, t_2 - b)$ identified with $(t_3 - a, t_4 - b)$ for all $a \ne 0, b \in k$.  Analogously we find $X \times_k X_2$ to be the disjoint union of $X_1 \times_k X_2$ and $X_2 \times_k X_2$ with $(t_1 - a, t_2 - b)$ identified with $(t_3 - a, t_4 - b)$ for all $a \in k, b \ne 0$.
Now we glue $X \times_k X_1$ and $X \times_k X_2$.  Let $q_1$ and $q_2$ be the second projection maps associated with $X \times_k X_1$ and $X \times_k X_2$, respectively.  Note that $q_1$ maps equivalence classes $[(t_1 - a, t_2 - b)]$ and $[(t_3 - a, t_4 - b)]$ to $(x - b) \in X_1$ and similarly $q_2$ maps them to $(y - b) \in X_2$.  Let $U_1'' = q_1^{-1} (\bar{U_1} \cap \bar{U_2})$.  This consists of equivalence classes $[(t_1 - a, t_2 - b)] = [(t_3 - a, t_4 - b)]$ with $a \ne 0$, $b \ne 0$, and classes $[(t_1, t_2 - b)]$, $[(t_3, t_4 - b)]$ with $b \ne 0$.  Similarly let $U_2'' = q_2^{-1} (\bar{U_1} \cap \bar{U_2})$ consists of the equivalence classes $[(t_1 - a, t_2 - b)] = [(t_3 - a, t_4 - b)]$ with $a \ne 0, b \ne 0$, along with $[(t_1 - a, t_2)]$ and $[(t_3 - a, t_4)]$ with $a \ne 0$.  We have an isomorphism $\phi'' : U_1'' \to U_2''$ which maps $[(t_1 - a, t_2 - b)] \mapsto [(t_1 - b, t_2 - a)]$ and $[(t_3 - a, t_4 - b)] \mapsto [(t_3 - b, t_4 - a)]$.  The result of gluing $X \times_k X_1$ and $X \times_k X_2$ via $\phi''$ is the fiber product $X \times_k X$.
Comment: Many Thanks! It seems fairly complicate and annoying computation. Maybe, that is the reason why I hesitate to compute along with the proof of the existence of fiber product(as you know, there are many things such as finding top. sp. of subspace, gluing etc).


What does it mean mean by "Expected a statement" in C++

Question: I have entered an if else code in C++ in visual studio and it shows that a statement is expected at Else and Else if
My code is
#include <iostream>
using namespace std;
int main()

{
float marks, result;
cout << "Enter your Marks:";
cin >> marks;
if(marks>=50 && marks <= 100);
{
    cout << "Passed";
}
else if (marks < 50 && marks>=0);
{
    cout << "The grade is F ";
}
else
{
    cout << "Enter marks correctly";
}
}

output is

Enter your marks:97
passedenter marks correctly

both statements in if and in else are printed out why ??
Comment: `if(marks>=50 && marks <= 100);` after if there should be a statement but you put a `;` voting to close as typo
Comment: Your question is ambiguous. You say you get build errors, and you say that the code runs but give unexpected results. It can't be both: You *either* get build errors which means there will be no executable to run; Or you *don't* get build errors and the program runs (with possible unexpected results).
Comment: Please include the full error message. In which line is the error?
Comment: even more offtopic: Am I the only one who wonders why there are so many sad smilies in correct syntax and so little happy ones?
Comment: @StoryTeller now that's a killer epitaph! (heh, *killer*)
Comment: @user463035818 - `;` *is* a statement :P
Comment: @StoryTeller But will cause problem with the `else` later. So it's still to blame... :)
Comment: @StoryTeller meh I knew it was wrong. One day I will read the books from chapter one, but until that I will make mistakes like that :P
Comment: its a matter of style, but for me this is just another good reason to put the `{` in the same line. It is common to have lines ending with `);` but a line ending with `{;` would not cause that error and `;{` looks uncommon enough to be spotted easily
Comment: Also please read [the help pages](http://stackoverflow.com/help), take [the SO tour](http://stackoverflow.com/tour), read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/).
Comment: @user463035818 It's because you don't parse `;}` as the happy face it is.
Comment: @user463035818 `goto happy_place; /* .... */ happy_place :}`
Comment: @user463035818 Or `<=` :)
Comment: @StoryTeller considering that's where all local objects die, this has quite a grim sound to it.
Comment: @Quentin - Death is an important part of life. Can't have RAII without it
Answer: The problem is that here
if(marks>=50 && marks <= 100);

You have that ; which shouldn't be there. Due to that, the ; is the body of the if statement. It means "do nothing". As a result, the following
{
    cout << "Passed";
}

...has nothing to do with the if statement and will always be executed. After that is this:
else if (marks < 50 && marks>=0);

Same problem here, but the else can't compile, because there was no if before it. Remember, the block before the else is mistakenly not part of the if. Instead, what you want is this:
if(marks>=50 && marks <= 100)
{
    cout << "Passed";
}
else if (marks < 50 && marks>=0)
{
    cout << "The grade is F ";
}
else
{
    cout << "Enter marks correctly";
}


How do I use the OpenFileDialog class such that it opens on the Network area as default?

Question: How do I use the OpenFileDialog class (in C#, WPF etc.) such that it opens on the Network area as default?
This does not work:
  OpenFileDialog openFileDialog1 = new OpenFileDialog();
  openFileDialog1.InitialDirectory = "Network";

I also tried having "\" as an InitialDirectory and that did not work.
I also tried having "\\" as an InitialDirectory and that did not work either.
Answer: I haven't tried it, but this should work:
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.NetworkShortcuts);

Environment.GetFolderPath returns the path corresponding to an Environment.SpecialFolder enumeration entry as a string.
Environment.SpecialFolder.NetworkShortcuts is defined as

A file system directory that contains
  the link objects that may exist in the
  My Network Places virtual folder.
Answer: Customize Your Open File Dialog from the Microsoft MSDN Magazine has a lot of information on the dialog. I haven't had chance to read it all, but this caught my eye:

A Custom Places Bar
  ...
You'll need a REG_SZ entry if the name of the folder is an absolute or relative path. You need to use the folder-specific number if you want to target a special folder (see Figure 6 for a list). In this case, a REG_DWORD entry is needed.
Figure 6
Folder IDs
ID    Folder
  0   Desktop
  2   Programs folder on Start menu
  3   Control Panel
  4   Printers
  5   My Documents
  6   Favorites
  7   Startup folder on Start menu
  8   Recent Files
  9   Send To
  10  Recycle Bin
  12  Start menu
  17  My Computer
  18  My Network Places
  20  Fonts

I've missed a whole load of stuff out (because it's a very long article), but it looks like you can set the ID value to 18 to get your network places. However, as @Nelson points out this might part looks like it's adding an entry to the bar, so double check it before using.  As I said before the post I've linked to contains a lot of information, so what you need may well be buried somewhere in it.
Update:
On Windows 7 PC's it doesn't work. eg:
OpenDialogPlaces o = new OpenDialogPlaces();
//o.Places.Add(18);
//o.Places.Add(5);
//o.Places.Add(6);
o.Init();
o.OpenDialog.ShowDialog();
o.Reset();

Still shows everything in the left-hand:

It did work in previous versions of Windows:

Another thing it appears Microsoft has changed the ComDlg32's location, I tried both places but no luck.
Comment: Sounds like that would add it to the bar (as a shortcut), but not actually start there?
Comment: @Nelson - As I said, I haven't had chance to double check everything on that page, but I thought it would be a useful starting point. I'll update the answer to reflect your doubt.


Sharing photo/photos to my ionic 2 application from "share" button in gallery images

Question: When I choose picture/pictures from gallery of my android phone and click on share button, a list of apps appear. Here, those selected photos can be shared. I want my ionic2 application to appear in that list so that photos can be shared in my app.
//07-03-2017 updating this question
As per latest update to this question.
Now my application appears in that list. but i am not been able to post pics , as i click the app icon , it takes me to the main page of the application and not the the desired page!
Comment: How did you do this?
Comment: @hydrococcus https://github.com/napolitano/cordova-plugin-intent , followed this
Answer: You need to update your Android manifest as well as handle the received intent in your Activity. Please see the official guide: https://developer.android.com/training/sharing/receive.html#update-manifest
Comment: i am using Ionic framework, so there is no concept for intents.
Comment: My bad, I am not really familiar with ionic, but I came across this http://stackoverflow.com/questions/32856046/sending-url-to-ionic-android-app-via-webintents-from-another-app it's not exactly your case but it might be a starting point?
Comment: thanks a lot for the reference , but i am afraid it won't work , as i am working with Ionic 2 and the link mentions about ionic 1.1
Comment: I agree to @PiotrZawadzki. You might not find a 1-on-1 solution to your question, but he's pointing you in the right direction. Note there is also a WebIntent plugin for Ionic 2. https://ionicframework.com/docs/v2/native/webintent/
Comment: @JoeriShoeby yeah !after digging more into it , i found this https://github.com/napolitano/cordova-plugin-intent and then my app was visible in share options . i have updated the question accordingly

Sharing photo/photos to my ionic 2 application from “share” button in gallery images


discord.py: Inexplicable Missing Access error

Question: I try to do a bot, who makes temporary Voice Channels. There's a command which "locks" the channel. Means nobody can join anymore.
Code who locks the channel:
# line 381
permstemplock = {
  ctx.guild.default_role: discord.PermissionOverwrite(connect=False),
  ctx.guild.me: discord.PermissionOverwrite(view_channel=True, manage_roles=True,
                                            manage_channels=True, manage_permissions=True),
  ctx.author: discord.PermissionOverwrite(manage_channels=True, connect=True,view_channel=True),
}

await tempc.edit(overwrites=permstemplock)

And the opposite of the lock command, unlock:
permstempunlock = {
  ctx.guild.me: discord.PermissionOverwrite(view_channel=True, manage_roles=True, manage_channels=True,
                                                                              manage_permissions=True),
  ctx.author: discord.PermissionOverwrite(manage_channels=True, connect=True,view_channel=True),

}

await tempc.edit(overwrites=permstempunlock)

Server permissions of the bot:
- Create Invite
- Manage Channels
- View Channels
- Send messages
- Manage messages
- Embed links
- Attached Files
- View message history
- Use external emojis
- Add reactions
- Move members
- Use Voice Activity

Error:
Ignoring exception in command voice:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "F:/DiscordBot/PyCharm/AmongUsDeutsch/Tempchannels/tempchannels.py", line 381, in voice
    await tempc.edit(overwrites=permstempunlock)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\channel.py", line 694, in edit
    await self._edit(options, reason=reason)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\abc.py", line 309, in _edit
    data = await self._state.http.edit_channel(self.id, reason=reason, **options)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\http.py", line 241, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50001): Missing Access

Answer: From the docs: The error is thrown when status code 403 occurs. In other words, you're bot doesn't have access to the channel. This is probably because the channel is syncing permissions with the category which is disabling the bot its needed permissions.
You can fix this by setting up your role perm or category perm hierarchy so the bot will have access to all channels that are created.
Another possible cause is that you're locking the permissions for @everyone first which is locking the bots permissions. If this is the case, just add the line ctx.guild.me before the ctx.guild.default_role line.
Comment: Okay thanks, I will test it as soon as I'm at home. But I have a question. You said that a possible cause could be that `ctx.guild.default_role` is before `ctx.guild.me` and it's locking the bot permissions. Thats true for this command. But if the bot have to change the permissions again we have the same problem as before, haven't we?
Answer: Solution
The Bot (ctx.guild.me) needs the permission connect. Doing connect = True solved the problem:
permstemplock = {
  ctx.guild.default_role: discord.PermissionOverwrite(connect=False),
  ctx.guild.me: discord.PermissionOverwrite(view_channel=True, manage_roles=True,
                                            manage_channels=True, manage_permissions=True, connect=True),
  ctx.author: discord.PermissionOverwrite(manage_channels=True, connect=True,view_channel=True),
}

await tempc.edit(overwrites=permstemplock)


Pairs forming perfect square

Question: Question: Determine all pairs of positive integers $(x,y)$ for which $2^x+3^y$ is a perfect square.

Doubt: This question was posted before and a screenshot of one of the hints is attached. I don't understand how do we arrive at $ 2^{s+1} +1=3^y$.
Doesn't that require us to assume the factors are $1$ and $3^y$? Why can't both the factors be powers of three other than $0$?
Comment: By $m$ and $n$, do you mean $x$ and $y$?
Comment: Oops. Yes I did mean that.
Answer: If  $$z - 2^s = 3^a$$
and $$z + 2^s = 3^b$$
Note that $b \gt a$.
Subtracting the first from the second gives us
$$2^{s+1} = 3^b - 3^a = 3^a(3^{b-a} - 1)$$
Since the left side is a power of $2$ which is not divisible by $3$, we must have $3^a = 1$ and so $a = 0$.
Comment: Ohhh yes! Also I wanted to ask an additional question. By brute force I found that the difference $b-a$ must be either $1 $ or $2$ for $3^{b-a} -1$ to be a power 2. So does this mean that $b= 2 $ or $b=1$ are the only two cases? Am I correct ?
Comment: @Viraam: That $b = 1$ or $2$ needs to be shown. Brute force won't work (did you exhaust all possibilities?).
Comment: Yes I agree. I just noticed it for a few powers. Saw that after $3^2-1$ the any number of the form $3^m-1 $ has factors other than 2.
Comment: @Viraam: See this answer for some ideas which might work: https://math.stackexchange.com/questions/6324/are-there-integer-solutions-to-9x-8y-1/6326#6326
Comment: Ok. Suppose I take my first case to be $ 3^{b-a} = 2^n$ such that $n > 1$. Then I can use mod $4$ and I get that the difference $b-a$ has to be even. How can I prove it has to be equal to 2. Just a hint would be fine as well.
Comment: @Viraam: $3^y = 2^{x} + 1$. Now if $x = 1$ or $2 \mod 3$, then $2^x = ? \mod 3$.
Comment: So if $y$ is even (your $b-a$), and $x$ is a multiple of $3$ you have the exact same question which I linked to.

Pairs forming perfect square


Active directory and firewalls

Question: I am not familiar with active directory and have very limited knowledge of firewalls.  I am trying to understand how 'trusts' work.  Say there is a situation like the following:

There are 2 separate networks
An external trust is to be given to a domain in network1 to another domain in network2

Wouldn't the users in domain in network1 need go past the firewall in network2 first? How does the set up work?
Answer: Yes, traffic would have to be allowed between the two networks, but its less clients and more AD servers that need to exchange domain related data. remember trust is a cryptographic construct, so it has nothing really to do with firewalls. I would recommend that you use some form of tunneled connection (VPN, SSH, etc) to enable inter-lan communication though, since there is danger in exposing those linkages across the internet.
Answer: If you are talking about establishing a trust over the internet - don't do that.  Use something like AD Federated Services for that.
But I assume you are not talking about establishing an AD trust across the internet and instead are just talking about traversing internal firewalls on your networks.
This article lays it out exactly. View the link or open this image in a new tab to view full size:

So basically you just want the same ports you want for a member server to authenticate with an AD. A DC uses the same ports to establish a trust with another DC. Kerberos, LDAP, etc. etc.
Of course you need name resolution too.  That's usually handled with a stub zone or conditional forwarder in DomainA that allows it to resolve DomainB.
For RPC, you can restrict the dynamic RPC range of your computers via the registry. If you don't like opening 10,000 ports for dynamic RPC across your firewall, you can at least restrict it to a few hundred dynamic ports.

Active directory and firewalls