Saxophone vs Trumpet: range, overtone series and intonation

Question: Overtones
I'm learning the trumpet, and I chose it over the saxophone because it has fewer keys to press. I also liked how the trumpet relies on the harmonic series to play all the notes since it can only play half an octave without using overtones.

What is the range the saxophone can cover without using overtones?

Intonation
Whenever I pick up the trumpet, I have to listen to a Bb on my computer before I can start playing because the trumpet allows you to play a little higher or lower (especially in the low register). If I try to play the low Bb (no valves pressed), I could be playing any of the notes Ab, A, Bb and B and I can hardly tell which one I'm playing unless I hear the Bb in my head first.

Is the saxophone (and reed instruments in general) as hard as the trumpet to play in tune?
How much can you alter the pitch without changing the fingering or moving to another overtone?
Comment: Saxophones can be ["overblown"](http://en.wikipedia.org/wiki/Overblowing) to produce higher tones of the harmonic series using the same fingering as for the fundamental (as demonstrated by Michael Brecker in [Delta City Blues {see 2:38...}](http://www.youtube.com/watch?v=5IyFNKMVxd0)). However that is considered an extended technique. Normally for the upper register you press the [octave key](http://en.wikipedia.org/wiki/Octave_key) which opens an appropriate "speaker" hole that kills the fundamental, and so your first question isn't really applicable; all notes have their own fingering(s)!
Comment: In simplified terms, though, you could say that the saxophone repeats its fingerings by the octave.
Comment: Can you explain how you finger a low Bb? It's the open note at the beginning of the harmonic sequence, isn't it ? I used to tap the mouthpiece with an open palm, and that gave me the reference.I wonder if you're asking about initial tuning, to start at concert pitch.
Comment: Yes it's the open note. But you can call it a fingering, can't you? I'll edit the question to avoid confusion. I don't know what initial tuning means ; I'm not talking about the tuning slides, just buzzing in tune.
Comment: Saxophones are easy to control, so long as you use proper embrochure and breathing techniques. Saxophones provide a richer tone and are easy to memorize the keys. I play Alto Saxophone, and it is incredibly fun to play.
Answer: All instruments are equally difficult for different reasons.  You can't escape by choosing an "easy" instrument because there are none.
All pitches from all instruments have overtones.  It is impossible not to use an overtone as they are inherent in the physical properties of vibration that actuate the pitch.  It is precisely the reliance on the ear to negotiate the harmonic series on brass instruments that make them so difficult to play.  I believe you're looking for the term "partial" - as in a particular note from the harmonic series.
Brass players have a saying that if you can hear it, you can play it.  Next time you go to play, hear the Bb first and then sing the pitch, making sure it doesn't waver.  Next, bring the mouthpiece (not the whole trumpet!) up to your mouth and buzz the Bb into just the mouthpiece.  Do this several times until the pitch does not waver.  Next, use your lips to bend away (higher and lower) from the pitch and see if you can come exactly back to it (it's okay to use the computer as a drone if necessary.)  Repeat this a few times.  Now add the mouthpiece to your trumpet and play.
You may want to read my answer on "Audiation" as I think that might help a little bit - at least in terms of understanding why what I just told you is important.
Like the trumpet, the saxophone is a transposing instrument, so it's important to specify if you're looking for written range or sounding range.  For all saxophones, the written range is Bb3 - G6.  As alluded to earlier in my answer, it is impossible not to use overtones when playing the saxophone.
Yes, the saxophone is just as difficult to play in tune as all other instruments.  You are using different muscles in a different embouchure and that requires different technique.
On brass instruments, altering the pitch without changing the fingering is actually a lip-exercise used to develop flexibility and intonation.  First, do not worry that you're having a hard time with the first note - almost everyone feels lost at first when beginning to learn a brass instrument.  Most students have a much easier time playing the "G" (written) because it is easier to slot at first.  Because the trumpet mouthpiece is small, the low range is actually difficult to produce satisfactory sounds and takes easing into.
To answer your question more directly, generally you can bend a full 1/2 step (semitone) in either direction.  In the lower range, and especially on larger brass instruments, you can bend as much as a perfect fifth (as is the case of the tuba.)
I hope that answers your questions.
As a side note, I think you made a good move going for brass - now everyone doesn't have to hear you complain about reeds. :P
Hope that helps!
Comment: @Anthony - yes, sax players can pinch their embouchure in the lower register to get the octave up, however, it's not usually desirable.  In the same way, flute players can overblow and get the octave or a different partial as well.  Also like clarinet, sax players typically can reach different partials in the altissimo register of the instrument - where the notes are very close together.  Sometimes this is done for intonation, other times to facilitate playing ease. I should note here that the two instruments are *very* different in function and we are talking about extreme examples.
Comment: @Anthony I was going to mention that: with some practice, you can get several overtones by "tightening up" on the reed and boosting the air pressure. Alternatively, skilled reed players will find that if they're planning one note but finger another, there may be no sound output; albeit this is much less common than with a brass instrument. (and both brass & reed instruments are susceptible to a variety of squeaks and clams when there's a mismatch of one sort or another)
Comment: @jjmusicnotes Thanks for explaining overtones. I just need one extra piece of information I couldn't find on Wikipedia. Sax players have a technique (I have seen videos on Youtube) that allows them to jump to next note in the harmonic series (just like the trumpet) by adjusting their embouchure.However the sax (I think) has a good enough range playing the full notes (the lowest notes in the series for a given fingering), how many octaves can it play like that?
Answer: Brass players talk about "slotting" - the idea that when you play a note the instrument supplies a correction, pulling you towards a certain pitch. When you first start playing brass instruments, there can be a tendency to compress the lips together as you work too hard to make them produce the vibration.
Side effects of this are that the quality of the sound is also compressed and dull, and it tends to override any slotting help the instrument would naturally give to pull towards the true pitch. You want your lips to excite the resonance of the instrument, but by compressing them you decouple them from the instrument resonance. So you can play a wide range of pitches with a single fingering, which sounds like what's happening here.
When you whistle, you set a particular mouth cavity size and form your lips just right and then you just exhale - you're not actually making the vibration. Try to adopt a similar thought process with the brass note production - set up embouchure consistently and then supply the breath. Don't think about forcing your lips together to make them buzz, and you'll find those slots.


How to find which content types have comments enabled?

Question: I just want, quickly, to know which content types have comments enabled, without having to go from content type to content type and view the configuration page of each, especially if there are more than fifteen.
Answer: I searched but I found nothing relative, so I take the initiative to answer my own question.
MySQL seems to be the answer:
mysql> select type from comment c, node n where c.nid = n.nid group by type;
+------------------+
| type             |
+------------------+
| my_content_x     |
| my_content_y     |
| my_content_z     |
+------------------+

This can be equally used:
mysql> select entity_type, bundle from  field_data_comment_body group by entity_type, bundle;
+-------------+-------------------------------+
| entity_type | bundle                        |
+-------------+-------------------------------+
| comment     | comment_node_my_content_x     |
| comment     | comment_node_my_content_y     |
| comment     | comment_node_my_content_z     |
+-------------+-------------------------------+

All nodes which at least have one comment:
mysql> select type, n.nid from comment c, node n where c.nid = n.nid group by n.nid  order by type;
+--------------+------+
| type         | nid  |
+--------------+------+
| my_content_x |  115 |
| my_content_x |  90  |
| my_content_y |  521 |
| my_content_y |  295 |
| my_content_z |  127 |
| my_content_z |  11  |
+--------------+------+


How to use field_info_instance?

Question: I am currently working with an Entity Reference field in Drupal 7, and I need to alter the results using field_info_instance. The field type is Entity Reference. Below are the steps I've taken:
$field_instance = field_info_instance('node', 'field_branch_vod', 'employee');
kpr($field_instance);

Could you please provide guidance on how to use field_info_instance to effectively alter the field results for an Entity Reference field?
Answer: Neither of those bits of information relate to the instance, they relate to the field itself (regardless of what it's attached to).
As such you need to use field_info_field() to get them:
$field_info = field_info_field('field_branch_vod');
$target_type = $field_info['settings']['target_type'];
$target_bundles = $field_info['settings']['handler_settings']['target_bundles'];

How to use field_info_instance?


Sizes calculation with JavaScript and jQuery

Question: Sometimes i'm facing problems, trying to get sizes of an HTML element in question.
I'm tracing JavaScript code and see, that width and height of this element are returned as 0.
When i do the same piece of code in browser's console, correct sizes are returned.
Example code, that demonstrates this problem is following:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Decorate image with button</title>

This code takes an image, wrapped to anchor and decorates it with "Play" button, that must be centered over it.
Table cell is used for centering.
In Firefox it works well, but does't in Safari 5.
When we trace the code, where "w" and "h" variables getting width and height, we will see, that they have zeros.
When we say from browser's console
$("a > img").width()

we will get correct sizes of image.
I think, i'm missing something ...
I think, i must catch "rendering complete"-like events ... But, as far, as i know, they are not presented in DOM.
How can i get to know, when the HTML element is rendered and displayed to be 100 % sure, that i'm dealing with correct sizes ?
Comment: Looks like the images are completely loaded when you request the dimensions. So you will have use a mechanism to ensure that all the images are loaded before you query the dimensions. Take a look at :http://stackoverflow.com/questions/1285375/how-to-ensure-images-are-loaded-inside-a-jquery-plugin
Answer: The problem is solved.
As mentioned in question How to ensure images are loaded inside a JQuery plugin?

webkit browsers like Chrome often return 0 size for images because they're loaded in parallel.

All, what i need to do, is to use "load" event for image.
$("a > img").load(function(){
    var img = $(this);
    var a = img.parent();

    var w = img.width();
    var h = img.height();

    a.html(" \

 \

 \
                 \
                     \
                	 \

 \

");
    a.append(img);
    // Make height of table equals to height of image
    a.find("> table").width( w );
    a.find("> table").height( h );
});

Now, i'm getting correct sizes.


SSH: "no matching key exchange method found" when KexAlgorithm is listed as available

Question: When I try to ssh to one of my switches I get the following error:
$ ssh remotehost
Unable to negotiate with 184.108.40.206 port 22: no matching key exchange method found. Their offer: diffie-hellman-group14-sha1

If I list available key exchange algorithms I can see that we do have it;
$ ssh -Q kex
...
...
diffie-hellman-group14-sha1
...

Specifying it manually as an option does work, as well as creating an .ssh/config entry for it, but shouldn't this be automatically picked if it's in the kex list?
ssh -o KexAlgorithms=diffie-hellman-group14-sha1 user@remotehost

.ssh/config
Host remotehost
    KexAlgorithms +diffie-hellman-group14-sha1

Answer: The diffie-hellman-group1-sha1 key exchange method is disabled by default in recent SSH versions. The config option is your only way to do it. Check the openssh legacy issues page for details
Answer: Working for me:
ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 -c 3des-cbc user@remotehost

Not working for me .ssh/config:
Host remotehost
  Ciphers 3des-cbc
  KexAlgorithms +diffie-hellman-group1-sha1

Answer: For MobaXTerm
----
mkdir -p .ssh
touch .ssh/config
----
vim .ssh/config
----
Host 10.64.88.189
#Legacy changes
KexAlgorithms +diffie-hellman-group1-sha1,diffie-hellman-group14-sha1
Ciphers +aes128-cbc


Porque o JSF não reconhece o id do componente na View?

Question: O JSF não está reconhecendo o id "dialogo-analise" que está na view e está dando o erro :
FATAL: Cannot find component for expression "dialogo-analise" referenced from "frmAtividade:tab:itens-rh:0:j_idt275".javax.faces.FacesException: Cannot find component for expression "dialogo-analise" referenced from "frmAtividade:tab:itens-rh:0:j_idt275".

Código que estou chamado o

        <h:graphicImage value="/img/setas_2544_Run2.png" width="17"/>

Quando retiro o id do dialog "dialogo-analise", funciona mas não faz o que preciso. Eu estou usando o tabView do primefaces e o botão está dentro de uma datatable, no qual e seleciono uma linha.
Existe um método no meu bean que chamo antes de  abrir o diálogo. Seleciono alguns dados na tabela e tento exibir neste diálogo. Debugando os dados são atribuidos aos setters dos atributos, mas não são exibidos.... muito estranho.
Código do diálogo

Comment: Se estiver fora da tabview provavelmente é  `update=":frmAtividade:dialogo-analise" `
Comment: Sim, ou você pode atualizar a tabview inteira(se necessário). vou postar uma reposta com a solução.
Comment: Esse problema está acontecendo no update?
Comment: Sim, quando incluo o id do diálogo, ele dá o erro que o componente não existe
Comment: O problema não é ele reconhecer o id, ele não está encontrando o id. Eles estão dentro de um mesmo form?
Comment: Sim, estão dentro do mesmo form.
Comment: Tem alguma coisa a ver com o tabView?
Comment: Poste seu código para ver como está hierarquia da sua pagina.
Comment: Provavelmente esse é o componente que está faltando o ID: `j_idt275`
Comment: Faça um teste dessa forma: `update="j_idt275:dialogo-analise"`
Comment: j_idt275 é provavelmente o o commandLink dele, precisa ver onde tá o dialog dele pra colocar o caminho correto no update do commandLink
Comment: Rafael, funcionou da forma que descreveu. Eu coloquei o dialogo fora do tabView.... agora me restou um outro problema. Quando eu finalizava a atualização desta tela eu atualizava um datatable que estava dentro de um tab. Agora não atualiza mais pelo fato de eu ter tirado o dialogo do tab. Para eu atualizar esta datatable eu preciso informar todo o caminho desta id, por exemplo: frmAtividade:tabview:tab:datatable?
Comment: Rafael, blz.... deu certo muito obrigado pela ajuda! Abraços
Answer: O problema não é ele reconhecer o id mas sim ele não está encontrando o caminho correto do id do dialog.
o caminho correto seria update=":frmAtividade:dialogo-analise".
Alguns componentes é necessário fazer isso, como por exemplo tabView , dataTable e dialog, ao fazer um update para fora deles é necessário colocar o caminho, iniciando pelo id do form, até o componente desejado.
Uma alternativa é usar update="#{p:component('idComponente')}"


Interaction between two Clouds

Question: I have setup the Cloud-A with 1 - [CLC+CC] and 2 - [NC] computers. I have another Cloud-B with same configuration using the Ubuntu Enterprise Cloud
Both of them working fine individually, in the same LAN.
Now if I want to add the NC of Cloud-A to CC of Cloud-B, [in case the resources of Cloud-B are exhausted] how can I make it possible ? I guess this calls for the interoperability stuff...
Could you please explain what happens exactly when we ask for instance, the direct interaction happens between the client and NC or it goes through the CLC and CC ?
What I want to say is, say there are multiple cloud providers. A user is subscribed to any one of them, say Cloud-A for IaaS. As the requirements are dynamic, all the resources of Cloud-A may get exhausted. There may be another Cloud-B which can provide the services but that Cloud-A can't ask the client to go for Cloud-B.
So if it is possible to have some co-ordination between this two providers to share resources mutually, making client fully unaware of whats going on in the background....?
Comment: Thanks all for replying..
@ Scaine : I mentioned that I am using the UBUNTU enterprise cloud and I got this problem while having two clouds..  :)
@ Bubblegun : yup sure.. but this does not address the issue I raised.. please let me know if you have any idea.. :)
@ codeMonk : I guess this is better than ServerFault, as am getting comments no matter what they are.. ;)
Comment: Can you make clear how this is related to Ubuntu?
Comment: Ubuntu server comes with stuff to create cloud infrastructure
Comment: You might have better luck asking this on ServerFault.
Comment: I think you might want to rephrase your question here. What I see when I read your question, I have cloud A, and cloud B working individually. I want to use resources on cloud B, when the resources in cloud A are depleted, or unavailable.

When I get asked questions like that, I would say, allocate the resources you need to accommodate what you wish to do.
Answer: This is definitely possible but you would need to post your exact NIC configuration to make it easier.
Is there a good reason to have two clouds here? If you went down to one cloud the issue would solve itself.

Interaction between two Clouds


Why does my Drush post_make hook not run from bash script?

Question: I have written a drush extension that runs some post_make operations.
It's all good when I run $ drush make normally.
I have also written a bash script, which with some arguments, perfoms also drush site-install and other file structure stuff. The problem is when I execute this script and bash runs my drush make, my extension and post_hook is not running.
I know it's more of a bash permissions/ownership thing or something, than a drush issue, but does anyone have an idea?
My extension lives in ~/.drush/extension.
I'm using drush 5.9 and this is the actual script.
Answer: Do you run the script as the same user that you run the drush make directly as?  Or do you perhaps run the script from cron?  Check to make sure that your $HOME environment variable is pointing to the expected directory; if $HOME is not set, then Drush will not find your commandfiles.
Comment: Thanks, $HOME var points to the correct location, also if I echo it from the script I get the correct location...what else to look for?
Comment: Does your Drush extension, or any Drush extension in the same directory, define any Drush commands?  Put `drush help commandname` in your script, and see if Drush is finding the commandfile. If you don't have any commands, just download one, e.g. `drush dl drushify`
Comment: Project drushify (7.x-1.0) downloaded to /home//.drush/drushify.Same location as my extension, I can see drushify help from that location..
Comment: Run `drush ev 'return drush_commandfile_list();'` and see if it includes your commandfile. Also, you should do these operations both from the command line and from your script, and look for any variations in behavior.
Comment: That was useful. From both ends I get the same array containing my extension from /home//.drush/, drushify, and also the core extensions from /usr/share/drush/commands. Weird stuff - I can also verify that if I  execute my drush-make from a bash alias, it will work (!) but still not working from the script :(
Comment: Okay, next run your Drush make command with the --show-invoke flag. This will cause Drush to print out all of the commandfile hooks for the make command. You must have this right if your hook is being called sometimes, I would imagine, so this is a difficult question. If your commandfile is listed in the commandfile list, then it should be called for all of the valid hooks that Drush invokes.


Can I use VestaCP with NGINX?

Question: I want to host website using VestaCP with nginx + php + mysql. Is it possible? If anyone knows about it, please let me know. Thanx!
I am using Ubuntu 14.04 LTS
Comment: A crazy and controversial idea, how about [reading the documentation](https://vestacp.com/docs/)? Before posting a question, you should have done the proper research. Please read [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) and also [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask)
Comment: Thank you ... In the future I will do proper research and write down questions.
Answer: Yes you can. It requires fresh install of ubuntu.

For a smooth installation you will need clean system "minimal install base"

Just follow their documentation and all should be ok.
https://vestacp.com/install/
OR https://vestacp.com/docs/#how-to-install-vesta

Can I use VestaCP with NGINX?


Solution to $|2^m-3^n|=35$?

Question: As in a previuos question I'm wondering about equations like $|A^m-B^n|=C$, where $A,B,C\in\mathbb N$ are given and solutions $m,n\in\mathbb N$ are wanted. As it seems there are no known general method: either there are solutions to be found or there are non existence proofs to be found (I guess by modular arithmetic methods).
The function $\displaystyle f(m)=\min_{n\in\mathbb N}|A^m-B^n|$ is approximately exponential with some pseudo random minimal values when $f(m)$ happens to be small. Therefore, if $A,B,C$ are "small" the probability of a match for a "big" $m$ is very small. It's interesting that this probability somehow is connected to the existence of counter proofs.
I'm interested in cases where there are no "small" solutions and to see how the proofs are constructed.

Is there a proof that $|2^m-3^n|=35$ doesn't have any solutions $m,n\in\mathbb N$?

I've tested for $m,n<500$ without finding a solution to $|2^m-3^n|=35$.
Comment: See the entry for $n=35$ at https://en.wikipedia.org/wiki/Catalan%27s_conjecture#Generalization
Comment: See also [this question](https://math.stackexchange.com/questions/2493414/are-there-natural-numbers-m-n-such-that-2m-3n-21), where the comment suggested $35$.
Answer: Modulo $85$, powers of $2$ are only equivalent to elements of $\{1,2,4,8,16,32,64,43\}$, while powers of $3$ are only equivalent to elements of $\{1, 3, 9, 27, 81, 73, 49, 62, 16, 48, 59, 7, 21, 63, 19, 57\}$.
It can simply be bashed out that $2^m-3^n \not\equiv \pm 35\bmod 85$ for any integers $m,n$ (as the set of values of $2^m\pm 35 \bmod 85$ is disjoint with the set of values of $3^n$).
Comment: @Lehs It is pretty general; all of the problems of this form I have seen can be solved by choosing the right modulus.
Comment: It looks like a rather general method...
Comment: Is there a method to have a good guess for the modulus?
Comment: @GottfriedHelms Not that I know of. It would be interesting to look into.
Comment: Hmm, perhaps make it a separate quesion? (At the moment I'm too tired, it's late night here)
Comment: Very  interesting strategy .. I wonder what other moduluses could be appropriate for this $2^m-3^n$ case... 85 is the least ?
Comment: @Widawensen : surely you have seen the other question/answers. But for the lurking reader here a link to my related answer giving a short list of such moduluses. See https://math.stackexchange.com/a/2496175/1714
Comment: @GottfriedHelms Thank you Gottfried for the link
Answer: $$ 2^m - 3^n = \pm 35.  $$
If both $m,n$ odd, we have $2 x^2 - 3 y^2 = \pm 35 \equiv 0 \pmod 7.$ But the discriminant of the binary form is $24,$ and we find Legendre symbol
$$  (24|7) = (6|7) = -1.  $$ Which means that we cannot have success modulo $7$ unless both $x,y$ are divisible by $7,$ which does not apply here, $x$ is a power of $2$ and $y$ is a power of $3.$ See proof of Proposition at Prime divisors of $k^2+(k+1)^2$
Similar for one of them odd, give me another minute to type. If both are even, difference of squares factors.
If $m$ odd, $n$ even, $2 x^2 - y^2 = \pm 35.$ Discriminant is $8,$ and
$$ (8|5) = (3|5) = -1.  $$
If $m$ even, $n$ odd, $ x^2 - 3y^2 = \pm 35.$ Discriminant is $12,$ and
$$ (12|5) = (2|5) = -1.  $$
If both are even, we have $2^{2t} - 3^{2u} = (2^t + 3^u)(2^t - 3^u)= \pm 35.$ Here we use inequalities, since the possibilities are $2^t + 3^u = 1,5,7,35.$ If  $2^t + 3^u = 5,$ perhaps $t=u=1$ and $2^t - 3^u = -1,$ no good; or  $t=2, u=0$ and $2^t - 3^u = 3,$ no good.
If  $2^t + 3^u = 7,$ then $t=2, u=1$ and $2^t - 3^u = 1,$ no good. Finally, two possibilities: if  $2^t + 3^u = 35,$ perhaps $t=5, u=1$ and $2^t - 3^u = 29,$ no good; or  $t=3, u=3$ and $2^t - 3^u = -19,$ no good.
Answer: We find, empirically,
$$ 35 = 2^3+3^3 \qquad \qquad \text{and} \qquad (35 = 2^5+3^1)$$
The first option, using $2^m - 3^n=35$ from $|2^m-3^n|$ is easy. The second option, using $2^m-3^n=-35$ is not so easy, and I've not completed that part yet.

First option:
Equalling the first expression for 35 with our equation with unknowns we write $$ 2^m - 3^n = 2^3+3^3$$.
Reordering for equal bases on each side gives
$$2^m -2^3 = 3^n +3^3 $$
We see, that $m>3$ is required. So let $m=3+u$  then
$$2^3(2^u -1) = 3^n+3^3$$
But now, $\pmod {2^3}$, the residue of the lhs is zero but of the rhs one of  $\{4,6\}$. So no solutions is possible.

Second option:
We use the second equation:
$$ 3^n-2^m = 35 = 2^5+3^1 $$
Then we can reorder
$$ 3^n - 3^1 = 2^5+2^m $$
By the minimal magnitude of the rhs it follows that $n \ge 4$ and from this follows that $m \ge 5$ because $3^4-3 = 78 > 2^5+2^5$. Then we can factor
$$ 3(3^u-1) = 2^5(2^v+1) \qquad \qquad \text{ setting  $u=n-1$ and $v=m-5$ }$$
Now to have $(3^u-1)$ containing $32=2^5$ as factor we need that $2^3$ is factor of $u$ but not $2^4$ - otherwise we had too many powers of $2$ here. So we need to have
$$ 3(3^{8+16u'}-1) = 2^5(2^v+1) $$
Next, to have in the rhs $3$ to the first power, but not to the second, we must have the exponent being odd and in particular of the form $6v' \pm 1$ so we must have exponents fulfilling the equation
$$ 3(3^{8+16u'}-1) = 2^5(2^{ 6v' \pm 1}+1) $$
But having such a regular exponent on the lhs includes also the primefactor $5$ which occurs always when the exponent is divisible by $4$, and this is always the case in this configuration.
On the other hand, for the same primefactor $5$ to appear as well in the rhs, we must have an even exponent and namely of the form $2^{2+4v"}$
So, for to have in the rhs exactly one factor $3$ the exponent must be odd, but to have the rhs also to contain the factor $5$ the exponent must be even - contradiction.
Comment: well, this version might look no so nice/smooth as the other one which uses only a single modulus $85$ for both options. But we have here smaller moduli ($8$ in the first option and $64$ and $9$ and $5$ in the second option) and we have some path which leads systematically to the contradiction (if it exists) by some sort of "iterative mutually adapting the exponents" and checking the occuring primefactors beginning with the smallest occuring ones.
Comment: It seems that also $2^m -2^4=3^n+19 \pmod{2^4}$ might be appropriate for the first case.. but how to find a solution for the second case?.. I've tried some possibilities - without success,.. interesting this asymmetry of cases...
Comment: @Widawensen: "interesting this asymmetry" - you say what! I'd naively assumed the same procedure would be applicable symmetrically but always run into mess. Really tricky this second option. I was going to unpack my old tool of primefactorizing the both sides of the equation, adapt exponents to run into contradictions - but that would be much more complicated than all what we have already seen here by others. So I'll see a bit more for some simple path but I'm nearly giving up... Likelihood of existence of a smart&short path decreases too much...
Comment: @Widawensen : please see my update of the answer
Comment: You did a good work Gottfried.. I'm also slowly studying your paper..
Answer: We need
$2^m\equiv3^n\pmod7\  \ \  \  (1)$
$\iff2^{m+n}\equiv(-1)^n$
Now as the residues of $2^a\equiv2,4,1\pmod7, n$ must be even $=2r$(say)
$\implies2^{m+2r}\equiv1\implies3|(m+2r)\  \ \  \  (i)$
and
$2^m\equiv3^n\pmod5\  \ \  \  (2)$
$\iff2^{m+n}\equiv6^n\equiv1\iff4|(m+n)\  \ \  \  (ii)$
$\implies4|(m+2r)\implies m$ must be even $m=2s$(say)
$\implies2|(s+r)\  \ \  \  (iii)$ and by $(i),3|(s+r)\  \ \  \  (iv)$
By $(iii),(iv)$ we need $6|(s+r)$
Ex:
If $s\equiv5,r\equiv1\pmod6$
Consequently, $2^m-3^n\equiv2^{10}-3^2$ which is clearly divisible by $35$
We have $m+n\equiv0\pmod{12}, 2^m-3^n=\dfrac{2^{-n}-3^n}{2^{12u}}=\dfrac{1-6^n}{2^{12u+n}}$ for some integer $u$
Now as $n$ is even $6^n\equiv1\pmod{35}$
and as $(35,2^{12u+n})=1,35$ will divide $$\dfrac{1-6^n}{2^{12u+n}}$$

Solution to $|2^m-3^n|=35$?


Mass 301 redirect URLs with Nginx

Question: I have a list of 600 urls. Due to a change in the system the urls will change to a new format. I will have a list with the old urls and corresponding new ones. But how do i 301 redirect all of them?
example:
/news/post-name -> /news/post-name.html
/wordpress/στα-ελληνικά -> /wordpress/sta-ellinika.html (in greek)
/cms/a-big-long-title-with-a-lot-of-te -> /cms/a-big-long-title-with-a-lot-of-text.html

There is no real pattern that could automate the work.
So what is the correct way to redirect all of them?
Comment: Are there any valid urls that look like these but don't have a .html at the end? Though to be honest I'm wondering why would you need to change them to that. Archives perhaps?
Answer: You could use the map module to simplify the nginx configuration somewhat, but you're going to have to write a script to convert your list of URLs into the correct format for nginx. I would suggest generating the map directive into a separate file which is then included by the main configuration.

Mass 301 redirect URLs with Nginx


Como funciona a nomenclatura de versão para projetos privados ou públicos?

Question: Estou desenvolvendo um projeto que serve como bootstrap para futuras contribuições via Git, e gostaria de saber qual o esquema de versão mais utilizado, digo "versão" relativa ao estado que se encontra o software, exemplo
versão 0.1.1
Seguindo as diretrizes básicas de software versioning, como escalar a versão de acordo com as contribuições?
Utilizando somente branch's e tag's? Ou existe outras boas práticas?
Comment: Você está procurando algo assim? http://nvie.com/posts/a-successful-git-branching-model/ . Aqui tem mais detalhes: https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow/. Se for, eu coloca uma resposta mais completa.
Comment: Obrigado @Dherik é exatamente esse o conceito que preciso para organizar o projeto, é mais o menos o que imaginava, mas precisava de um exemplo profissional. vlw
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Um modelo conhecido e que muitas empresas adotam é o GitFlow:

Como pode notar, ele abrange grande parte dos aspectos do desenvolvimento de software: tags para marcar versões, uma branch da versão estável (master), branch de desenvolvimento (develop), branch das atividades (feature branches), branch para correções (hotfixes) e assim por diante.
Outro link que posso te indicar, que dá mais alguns detalhes de como este modelo funciona na prática, pode ser encontrado aqui.
Embora este modelo pareça um pouco burocrático, ele ajuda a organizar o processo de desenvolvimento de software. Logicamente, você não é obrigado a adotar este modelo de forma rígida, podendo flexibilizá-lo de acordo com as necessidades do seu projeto.
Sobre o número das versões, como dito anteriormente, é usado as tags do Git para isto. Um exemplo, criando a versão 0.1:
git tag -a 0.1 -m "Versão 0.1, com melhorias na consulta de pessoas"

A nomenclatura da versão em si pode variar (0.1, v0.1, etc), mas perceba que ela sempre ocorre na branch master, que é para ser a branch estável do sistema neste modelo.
Se tiver dificuldades em seguir o modelo, a ferramenta SourceTree com o plugin do GitFlow poderá auxiliar você e sua equipe. Mas recomendo entender o modelo e não depender de ferramentas deste tipo no futuro. O ideal é cada membro da equipe sentir-se livre para usar a ferramenta que achar mais adequada.
Comment: Fica a seu critério, mas acho o _pull request_ bem útil.

No caso do `merge`  via _pull request_ das branches do tipo _feature_ para _develop_, elas podem ser realizadas por algum membro da equipe que não participou da atividade. É possível, inclusive, aproveitar esta etapa para fazer o _code review_ do código por quem vai fazer o **approval**. Lembrando que, no modelo proposto, as únicas branches que fazem merge direto com a master são as de release e hotfixes.
Comment: Com certeza. Achei esse modelo o ideal e vou enxuga-lo de acordo com as necessidades do meu projeto. Só tenho uma questão básica, considerando a branch MASTER como a principal e também a branch que lanço as TAG's de versões, todas as sub releases que estão entre DEV e MASTER, serão mescladas a master por qualquer integrante? ou seria uma boa pratica fazer o **approval** dessas features na master através de pull request?
Comment: Show de bola, vou convecionar o **pull request** e por enquanto eu mesmo faço o papel do **approval**. Obrigado pela ajuda, irmão.
Answer: Não dá para afirmar qual é o mais usado, e mesmo que desse isto não lhe serviria para nada.
Tem algumas diretrizes que podem ser adotadas dentro do que se usa, mas você pode escolher a melhor forma para o seu projeto. Se espera que outras pessoas contribuam talvez elas quererão influenciar nisto.
Comece fazer de um jeito, se não der certo, mude. Só a experiência pode determinar o melhor jeito para cada projeto.
Tem linguagens ou tecnologias que indicam uma forma de fazer.
Há uma lista de formas diferentes no Software Engineering. Eu coloquei uma resposta com versionamento baseado em datas que pode ser útil em certos cenários e ela foi bem votada.
Se quiser saber sobre o Semantic Version já tem uma pergunta sobre o assunto. Ele parece estar sendo mais adotado agora. Mas como minha resposta lá indica, o ponto exato de troca é subjetivo. Só dá para determinar linhas gerais.
A página que você mencionou já dá outras formas e você pode pesquisar em projetos em repositórios públicos por outras formas.
Algumas pessoas gostam de por letras também. Ou números negativos mais raramente. Alguns usam números com algum significado específico.
Alguns usam o hash do commit que gerou uma tag no Git para ajudar localizar no repositório. Depende de como trabalha pode ser útil mas muitas vezes é redundante já que a tag deveria conter a informação da versão. Em alguns casos pode-se usar no branch também, mas é confuso. Em geral, apenas tags deveriam ter versões (mesmo no SVN). Exceção talvez quando o branch seja criado para organizar um release ou pelo menos builds.
Alguns preferem esquemas bem complicados. É válido, mas a não ser que tenha um bom motivo para isto, sugiro evitar. Quase sempre é uma complicação desnecessária e pouco ou nada vantajosa. O mesmo vale para trocas frequentes que fazem os números ficarem altos. Lembre-se que você vai falar, escrever e manipular muito esta designação. Facilite.
Se você quiser trocar a versão a hora que bem entender, pode e funciona. Só não vá criar versões novas decrementando números, aí gera confusão. O resto é gosto de adaptação ao fluxo que achar atender melhor a equipe.
Lembrando que você pode ter nomenclaturas diferentes para uso interno do projeto e para divulgação "comercial".
Coloquei no GitHub para referência futura.
Comment: muito bom o seu comentário, com certeza vai me ajudar a aprimorar meu conhecimento e conseguir lançar esse projeto para que os outros integrantes possam contribuir de forma unificada.
Também prefiro trabalhar de forma livre (sem dependencias de tecnologia). Já arriquei a versionar um projeto pela HASH dos commits, mas acabou virando bolo de gato, não recomendo muito, a não ser que seja muito especifico mesmo. Obrigado irmão.
Answer: Vou dar uma resposta baseada na proposta do site SemVer.org (semantic versioning):

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes,
MINOR version when you add functionality in a backwards-compatible manner, and
PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

Tradução:

Dado um número de versão no padrão MAIOR.MENOR.PATCH, incremente:

a MAIOR versão quando você introduz alterações incompatíveis na API,
a MENOR versão quando você adiciona funcionalidade de uma forma compatível com o que já existia (backwards-compatible), e
a versão do PATCH, quando você introduz correções compatíveis com o que já existia.

Etiquetas adicionais para informações de pré-release e dados de build estão disponíveis como extensões ao formato MAIOR.MENOR.PATCH.


Has Arcsinh ever been considered as a neural network activation function?

Question: The function
$y = arcsinh(x)=ln(x+\sqrt{x^2+1})$
has some nice features that I could imagine being useful as an activation function in a neural network. It has sigmoid behaviour around zero, but far from the centre exhibits logarithmic growth which means the slope of the function doesn't diminish nearly as quickly as the sigmoid function, which means the problem of one neuron becoming 'stuck' in a region where the slope is vanishingly small (and therefore can't move from its large value) is avoided.

I suspect there's a problem with computation - I don't know how arcsinh is normally calculated, but it's probably too computationally intensive to be efficient compared to other activation functions.
I've not seen any evidence of Archsinh used or even considered anywhere. Are my guesses about its features and drawbacks accurate?
Comment: Random googling  yielded https://github.com/tensorflow/tensorflow/issues/7531
Comment: I'm sure this has been tried before. I've more commonly seen $\tanh$ activations, as anecdotally they do slightly better than sigmoids in terms of convergence speed (for example in LSTMS), and they immediately give you an output in $[-1,1]$ as opposed to sigmoids (which you could try shifting/scaling).
Answer: Well, I tried it. Yes it is slower to compute than other functions (e.g. tanh, arctan, softsign), in gfortran anyway. And I found other drawbacks: the mean squared error was usually worse than other functions after same number of epochs. And it could not tolerate as high a learning rate as others before going unstable. I was only doing simple classifier with 1 or 2 hidden layers. I did wonder like you whether the slow decay of the derivative would help. Maybe it does in deep learning (many layers)?
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stats.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://stats.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/359336)
Comment: Thanks for going and actually trying it out. The slowness of computation is as expected, but the MSE being worse is slightly surprising, as I would expect it to be somewhat similar to other activation functions. I'll accept this answer, but was also wondering if you could provide some facts and figures too?
Comment: @Pedro Valdez Now that I've thought about a bit more, it makes sense. Converging towards zero for at least part of the function is very important for a useful activation function. It means the activation function is fitting a curve somewhere, whilst not interfering elsewhere. Any arbitrary shape can be fitted by bricks because the shape of any given brick is a strictly local thing. Arcsinh, to put it in a handwavey way, is non-local. It's doing something everywhere along the real line. Sure the behaviour is logarithmic as you go further out, but it still tends to infinity.
Comment: Which means that any function you're trying to fit that has both a steep slope near the centre and limiting behaviour towards a constant value elsewhere (such as a gaussian distribution with small $\sigma$), isn't going to be fitted well by an Arcsinh function.


cryptsetup cannot close mapped device

Question: When I run:
LANG=C cryptsetup --debug luksClose /dev/mapper/Pool-A

it fails as follows:

    device-mapper: remove ioctl on Pool-A failed: Device or resource busy

Device /dev/mapper/Pool-A is still in use.
Command failed with code 16: Device or resource busy

(...) (It repeats a lot of lines like that)
# cryptsetup 1.7.2 processing "cryptsetup --debug luksClose /dev/mapper/Pool-A"
# Running command close.
# Locking memory.
# Installing SIGINT/SIGTERM handler.
# Unblocking interruption on signal.
# Allocating crypt device context by device /dev/mapper/Pool-A.
# Initialising device-mapper backend library.
# dm version   OF   [16384] (*1)
# dm versions   OF   [16384] (*1)
# Detected dm-crypt version 1.14.1, dm-ioctl version 4.33.0.
# Device-mapper backend running with UDEV support enabled.
# dm status Pool-A  OF   [16384] (*1)
# Releasing device-mapper backend.
# Trying to open and read device /dev/sdb1 with direct-io.
# Allocating crypt device /dev/sdb1 context.
# Trying to open and read device /dev/sdb1 with direct-io.
# Initialising device-mapper backend library.
# dm table Pool-A  OFW    [16384] (*1)
# Trying to open and read device /dev/sdb1 with direct-io.
# Crypto backend (gcrypt 1.5.3) initialized in cryptsetup library version 1.7.2.
# Detected kernel Linux 3.10.0-327.36.3.el7.x86_64 x86_64.
# Reading LUKS header of size 1024 from device /dev/sdb1
# Key length 32, device size 3906961375 sectors, header size 2050 sectors.
# Deactivating volume /dev/mapper/Pool-A.
# dm status Pool-A  OF   [16384] (*1)
# Udev cookie 0xd4d14d3 (semid 917504) created
# Udev cookie 0xd4d14d3 (semid 917504) incremented to 1
# Udev cookie 0xd4d14d3 (semid 917504) incremented to 2
# Udev cookie 0xd4d14d3 (semid 917504) assigned to REMOVE task(2) with flags         (0x0)
# dm remove Pool-A  OFT    [16384] (*1)

(...) (It repeats 25 lines alike)
# Releasing crypt device /dev/sdb1 context.
# Releasing device-mapper backend.
# Unlocking memory.

I've found that this problem arises when I tri to use udev rules like that:

ACTION=="add",ENV{ID_SERIAL_SHORT}=="57584E314135364632334141", RUN+="/etc/bacula/openmount.sh A"
ACTION=="remove",ENV{ID_SERIAL_SHORT}=="57584E314135364632334141", RUN+="/etc/bacula/umountclose.sh A"

This the low level info:
[root@backup ~]# dmsetup info Pool-A
Name:              Pool-A
State:             ACTIVE
Read Ahead:        256
Tables present:    LIVE
Open count:        1
Event number:      0
Major, minor:      253, 3
Number of targets: 1
UUID: CRYPT-LUKS1-2b69b6e48b6d4bd1942ae7505d530f27-Pool-A

And block device info is as follows:
    lsblk -o +UUID /dev/sdb
NAME       MAJ:MIN RM  SIZE RO TYPE  MOUNTPOINT UUID
sdb          8:16   0  1,8T  0 disk
└─sdb1       8:17   0  1,8T  0 part
  └─Pool-A 253:3    0  1,8T  0 crypt            48c1accf-47a6-45ec-aacc-6686e8a8a2fa

My OS is:
CentOS Linux release 7.2.1511 (Core) with kernel 3.10.0-327.36.3.el7.x86_64
Is it a systemd-udev problem? How can I fix it? Or is that a innocuous warning?
Comment: What is this device used for? Have you unmounted the filesystem before trying to close the LUKS?
Comment: Device is /dev/sdb, is an external usb drive. Yes I unmounted, checked and re-checked with lsof that is not being used.
Comment: 5 years later I have a similar issue, did you ever find a way to list what has a lock?
Comment: same here.. not mounted, no processes holding.. not sure why luksClose doesn't work
Answer: This is a difference between systemd-udev and classic udev.  systemd-udev mounts in a separate namespace, so mounts in RUN scripts won't be visible to users.  You can try systemctl restart udev and if that releases the lock, it's the issue.  To do this correctly, you'll have to work within systemd.   What's working for me is the following: a udev rule to catch the USB drive being plugged in:
ACTION=="add", KERNEL=="sd?1", ENV{ID_SERIAL_SHORT}=="575...", SYMLINK+="offsitebackup", TAG+="systemd", ENV{SYSTEMD_WANTS}+="offsite-backup.service"

This creates a /dev/offsitebackup link pointing to the first partition of the drive and triggers the service.  The service file is:
[Unit]
Description=Offsite Backup script
Requisite=dev-offsitebackup.device
BindsTo=dev-offsitebackup.device
After=dev-offsitebackup.device

[Service]
ExecStart=/usr/local/scripts/offsite-backup.ksh offsitebackup
Type=oneshot
StandardOutput=journal

[Install]
WantedBy=dev-offsitebackup.device

The script then does luksOpen/mount/copy/umount/luksClose.  Additionally, to test these out, you can simulate unplug/replug of the USB drive with:
udevadm trigger -v -c remove /dev/sda
udevadm trigger -v -c add /dev/sda

and you can see device/script state within systemd using:
systemctl status dev-offsitebackup.device
systemctl status offsite-backup.service

Two pages that helped to figure this all out are here and here.

cryptsetup cannot close mapped device


Recebimento de dados por meio da conexão entre o arduino e a internet(Ethernet shield)

Question: Construí um app para receber dados de um sensor conectado ao arduino através da internet utilizando um ethernet shield. Para isso peguei o resultado da página e separei apenas a medida do sensor no android.
Consegui obter o resultado da página mas somente o pressionamento de um botão. Como seria para ele ficar atualizando automaticamente?
Classe principal
        package com.example.appethernetsensor_;

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

        import java.io.IOException;

        import android.app.Activity;
        import android.content.Context;
        import android.graphics.Color;
        import android.net.ConnectivityManager;
        import android.net.NetworkInfo;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;

        public class MainActivity extends Activity {

            Button btnAtualizar;
            TextView medidaSensor;

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

                btnAtualizar = (Button)findViewById(R.id.button1);
                medidaSensor= (TextView)findViewById(R.id.textViewMedida);

                btnAtualizar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String stringUrl = "http://192.168.25.85/";

                        //Verifica se há alguma conectividade de rede
                        ConnectivityManager connMgr = (ConnectivityManager)
                            getSystemService(Context.CONNECTIVITY_SERVICE);

                        //Qual o tipo da rede, se é wifi, rede movel ...
                        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

                        //Se tiver conexão ...
                        if (networkInfo != null && networkInfo.isConnected()) {
                            new DownloadWebpageTask().execute(stringUrl);
                        } else {
                            Toast.makeText(getApplicationContext(), "Nenhma conexão disponível", Toast.LENGTH_LONG).show();
                        }

                    }
                });
            }

            private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
                @Override
                protected String doInBackground(String... urls) {

                    // params comes from the execute() call: params[0] is the url.
                    try {
                        Conexao conexao = new Conexao();
                        return conexao.downloadUrl(urls[0]);
                    } catch (IOException e) {
                        return "URL inválida";
                    }
                }

                protected void onPostExecute(String result) {

                    StringBuffer medida = new StringBuffer(result);
                    replaceAll(medida, "Sensor Ultrasonico : ", "");
                    replaceAll(medida, "", "");

                    medidaSensor.setText(medida);
               }
            }
            /*
             *      protected void onPostExecute(String result) {

                    StringBuffer medida = new StringBuffer(result);
                    replaceAll(medida, "Sensor Ultrasonico : ", "");
                    replaceAll(medida, " cm", "");
                    replaceAll(medida, "", "");

                    String s = medida.toString();//Converte a stringbuffer final para string

                    int i = Integer.parseInt(s);//Converte a string para inteiro

                    if(i>=0){
                    medidaSensor.setText(i + " cm");
                    }else{
                        medidaSensor.setText("Um momento...");
                    }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();
                if (id == R.id.action_settings) {
                    return true;
                }
                return super.onOptionsItemSelected(item);
            }
            */
        }

Classe para conexão
    package com.example.appethernetsensor_;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class Conexao {

        // Given a URL, establishes an HttpUrlConnection and retrieves
        // the web page content as a InputStream, which it returns as
        // a string.
        public String downloadUrl(String myurl) throws IOException {
            InputStream is = null;
            // Only display the first 500 characters of the retrieved
            // web page content.
            int len = 5000;

            try {
                URL url = new URL(myurl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
                is = conn.getInputStream();

                // Convert the InputStream into a string
                String contentAsString = readIt(is, len);
                return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }

        // Reads an InputStream and converts it to a String.
        public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
            Reader reader = null;
            reader = new InputStreamReader(stream, "UTF-8");
            char[] buffer = new char[len];
            reader.read(buffer);
            return new String(buffer);
        }

    }

Código arduino
  #include <Ultrasonic.h>
  #include <SPI.h>
  #include <Ethernet.h>

  //Define os parametros para o sensor ultrasonico HC-SR04
  #define PINO_TRIGGER  6 //Porta ligada ao pino Trigger do sensor
  #define PINO_ECHO     7 //Porta ligada ao pino Echo do sensor
  //Inicializa o sensor ultrasonico
  Ultrasonic ultrasonic(PINO_TRIGGER, PINO_ECHO);

  //Definicoes de IP, mascara de rede e gateway
  byte mac[] = {
    0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
  };
  IPAddress ip(192, 168, 25, 85);       //Define o endereco IP
  IPAddress gateway(192, 168, 25, 1);  //Define o gateway
  IPAddress subnet(255, 255, 255, 0); //Define a máscara de rede

  //Inicializa o servidor web na porta 80
  EthernetServer server(80);

  void setup()
  {
    //Inicializa a interface de rede
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();
  }

  void loop() {
    float cmMsec;
    long microsec = ultrasonic.timing();
    //Le e armazena as informacoes do sensor ultrasonico
    cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);

//Aguarda conexao do browser
EthernetClient client = server.available();
if (client) {
  Serial.println("new client");
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();
      Serial.write(c);
      // if you've gotten to the end of the line (received a newline
      // character) and the line is blank, the http request has ended,
      // so you can send a reply
      if (c == 'n' && currentLineIsBlank) {
        // send a standard http response header
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: close");
        client.println("Refresh: 2"); //Recarrega a pagina a cada 2seg
        client.println();
        client.print("");
        //Mostra as informacoes lidas pelo sensor ultrasonico
        client.print("Sensor Ultrasonico : ");
        client.print("");
        client.print(cmMsec);
        client.print("000");
        client.print(" cm");
        client.println("");
        break;
      }
      if (c == 'n') {
        // you're starting a new line
        currentLineIsBlank = true;
      }
      else if (c != 'r') {
        // you've gotten a character on the current line
        currentLineIsBlank = false;
      }
    }
  }
  // give the web browser time to receive the data
  delay(1);
  // close the connection:
  client.stop();
}

}
Answer: package com.example.appethernetsensor_;

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

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 Button btnAtualizar;
 TextView medidaSensor;

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

  medidaSensor = (TextView) findViewById(R.id.textViewMedida);

 }

 TimerTask timerTask = new TimerTask() {

  @override
  public void run() {
   String stringUrl = "http://192.168.25.85/";

   //Verifica se há alguma conectividade de rede
   ConnectivityManager connMgr = (ConnectivityManager)
   getSystemService(Context.CONNECTIVITY_SERVICE);

   //Qual o tipo da rede, se é wifi, rede movel ...
   NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

   //Se tiver conexão ...
   if (networkInfo != null && networkInfo.isConnected()) {
    new DownloadWebpageTask().execute(stringUrl);
   } else {
    Toast.makeText(getApplicationContext(), "Nenhma conexão disponível", Toast.LENGTH_LONG).show();
   }
  }

 };

 Timer timer = new Timer();
 timer.schedule(timerTask, 2000, 2000);

 private class DownloadWebpageTask extends AsyncTask < String, Void, String > {
   @Override
   protected String doInBackground(String...urls) {

    // params comes from the execute() call: params[0] is the url.
    try {
     Conexao conexao = new Conexao();
     return conexao.downloadUrl(urls[0]);
    } catch (IOException e) {
     return "URL inválida";
    }
   }

   protected void onPostExecute(String result) {

    StringBuffer medida = new StringBuffer(result);
    replaceAll(medida, "Sensor Ultrasonico : ", "");
    replaceAll(medida, "", "");

    medidaSensor.setText(medida);
   }
  }
  /*
             *      protected void onPostExecute(String result) {

                    StringBuffer medida = new StringBuffer(result);
                    replaceAll(medida, "Sensor Ultrasonico : ", "");
                    replaceAll(medida, " cm", "");
                    replaceAll(medida, "", "");

                    String s = medida.toString();//Converte a stringbuffer final para string

                    int i = Integer.parseInt(s);//Converte a string para inteiro

                    if(i>=0){
                    medidaSensor.setText(i + " cm");
                    }else{
                        medidaSensor.setText("Um momento...");
                    }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();
                if (id == R.id.action_settings) {
                    return true;
                }
                return super.onOptionsItemSelected(item);
            }
            */
}


Como ativar apenas a próxima div?

Question: Na minha página eu tenho vários elementos que preferi esconder para não deixar o site muito grande, mas ao clicar em mostrar um, ele expande todos da página. Como eu faço para ele selecionar apenas o próximo elemento?
$(document).ready(function(){
        $(".flip").click(function(){
            $(".panel").slideToggle("slow");
        });
    });

Assim ta o JQuery e no código está assim:

Expandir/Esconder

Answer: Cara use o método .next() do jQuery junto com o seleto this, o this vai pegar apenas o elemento que vc clicou, e o next() vai selecionar o próximo elemento com a classe que vc definir

$(document).ready(function() {
  $(".flip").click(function() {
    $(this).next(".panel").slideToggle("slow");
  });
});

Expandir/Esconder

  111

Expandir/Esconder

  222

Aqui tem a documentação oficial do .next() https://api.jquery.com/next/
Answer: Use $(this).next('.panel') no lugar de $(".panel"). Isso fará que seja acessado o próximo panel em relação ao elemento clicado, em vez de selecionar todos
Comment: Rapaz esse pontinhos das peguntas deram um UP ai hein!
Comment: Tá falando da reputação? Também achei estranho, lembrava de ter 6k, um belo dia olho e tem 2k a mais. Deve ter dado um bug na SE, tava até olhando minha aba de reputação ontem pra ver da onde tinha saído isso
Comment: As resposta até semana passada valiam 5pts, agora passou para 10pts, ai foi retroativo, deram +5 para as perguntas antigas tb :D, levei 3.5k nessa rss
Comment: @hugocsl tô totalmente desatualizado shusauhusahuhsa
Answer: Outra forma é pegando o índice da classe .flip clicada e aplicar ao mesmo índice da classe .panel.
A vantagem desta forma sobre o .next() é que o elemento .panel não precisa ser irmão do elemento .flip. O .next() só funciona com elementos irmãos e que estejam após o elemento selecionado.
Por exemplo, se tiver a estrutura abaixo, o .next() já não vai funcionar:

Expandir/Esconder

painel 1

Note acima que a div.panel não é irmã da div.flip.
Pegando o índice, como falei, funciona em qualquer caso, pois cada índice da classe .flip é "casada" com cada índice da classe .panel.
Basta fazer isso:

$(document).ready(function(){
   $(".flip").click(function(){
      var idx = $(".flip").index(this); // pega o índice
      $(".panel").eq(idx).slideToggle("slow");
   });
});

Expandir/Esconder

painel 1

Expandir/Esconder

painel 2

O .index() me retorna o índice do .flip clicado e uso .eq() para pegar o mesmo índice da classe .panel. Muito simples!

Como ativar apenas a próxima div?


Random Forest in R: how to get OOB error and interpret error.rate table

Question: I run random forest (using package randomForest) on the classic titanic data. Here are the code and results.
dt_rf <- randomForest(Survived ~ ., data = train, ntree = 200)
print(dt_rf)

Call:
 randomForest(formula = Survived ~ ., data = train, ntree = 200)
               Type of random forest: classification
                     Number of trees: 200
No. of variables tried at each split: 2

        OOB estimate of  error rate: 15.8%
Confusion matrix:
     No Yes class.error
No  401  38  0.08656036
Yes  74 196  0.27407407

Wondering is there a way to access the OOB error from the dt_rf object? I only see error rate table by dt_rf$err.rate. What does this table mean? How is this table different from the error rate in the printable results?
dt_rf$err.rate
            OOB         No       Yes
  [1,] 0.1785714 0.07407407 0.3666667
  [2,] 0.2070588 0.12781955 0.3396226
  [3,] 0.2169811 0.13719512 0.3465347
  [4,] 0.2233503 0.17403315 0.3013100
  [5,] 0.2154088 0.16153846 0.3008130
  [6,] 0.2080838 0.14146341 0.3139535
  [7,] 0.1973490 0.13397129 0.2988506
  [8,] 0.2023290 0.13207547 0.3155894
  [9,] 0.1873199 0.11943794 0.2958801
 [10,] 0.1919771 0.12064965 0.3071161

I tried using mean to calculate the OOB column, but it does not match 15.8% in the printable results.
Answer: You can calculate the OOB error from the random forest confusion matrix. What you need to do is just to divide the number of correctly classified observations in the confusion matrix by the number of total observations and substract it from 1. In your case: (401 + 196)/(401 + 38 + 74 + 196) = 0.842; 1 - 0.842 = 0.158, which is the same as 15.8%. You can get this number by using diag() and sum() functions:
    conf <- dt_rf$confusion[,-ncol(dt_rf$confusion)]
    oob <- 1 - (sum(diag(conf))/sum(conf))
    oob
    oob * 100


symfony 2 : can't execute data fixture doctrine:fixtures:load

Question: I have project developed with Symfony2.8. It works locally. I am trying to execute doctrine:fixtures:load but I get this error :
Comment: I really don't understand why a swiftmailer exception is thrown in a fixtures loading script.. Are you explicitely throwing it in your script ? can you post your Epx\Bundle\SubscriptionBundle\DataFixtures\ORM\LoadData.php file ?
Comment: It looks like the fixtures are fine, the problem is with you swift mailer setup.  Possible fix for you; http://stackoverflow.com/questions/23420937/uncaught-exception-swift-transportexception-with-message-connection-could-not (downvoted answer as it appears you are using wamp)
Answer: The problem is that your server (wampserver) is not working properly. Indeed the application (Symfony app) is not able to communicate to it via doctrine that is why it display:
connection could not be established with localhost... So you simple have to check what is wrong with your localhost server. I suggest:

Restart wamp
Restart your PC (if restarting wamp does not work)
Reinstall wamp (if restarting your PC does not work)
Search on web ...(if any of above does not work...)


How to search the debug console in vscode?

Question: This is currently a feature request, so I know the answer isn't straight forward, but I assume some clever people found clever workarounds for this.
One way is to copy/paste the output in some text editor, but ew.
Someone suggested redirecting the debug output to the terminal, which does have a search feature, sounds better.
So, the question is, how does one redirect the debug output to the terminal?
Unless, of course, you have an even better solution.
EDIT (from the GitHub thread)

You can use the property "console": "integratedTerminal" on the debug
  launch task to redirect the output to the terminal.
Comment: someone has already replied to your question on gihub ;)
Comment: @Jaya héhé, thanks!
I'll still leave the question open in case something better comes along though.
Comment: [Here](https://stackoverflow.com/a/44186259/3066295) is how to set the property mentioned in your edit.
Comment: Go to root folder of project and type "flutter logs"
Answer: Looks like this answer is now outdated, see this other answer instead.

A type-to-filter functionality has been added. To use it:

Give focus to the debug console (By clicking it, for instance.)
Press cmd + F / ctrl + F
Start typing

You will see what you type in the upper right corner of the debug console.

You can then "enable filter on type" (the 3 lines left of the 'x') and only matching lines will show in the debug console. Press Escape to clear the search.
So it's not exactly the search feature OP was looking for, plus you can't type spaces, but it's the best built in tool for now (July 2019).
Comment: This is an unfortunate state of affairs :/
Comment: It's unfortunate not just because it's hard to find, but also because of its limitations - see above.
Comment: No, it's bad all over because it's not even a proper search. It doesn't allow you to search for "list of something", as it doesn't allow spaces in the search, so it's essentially useless for searching custom logs in a human readable format.
Comment: @Antony Stubbs - unfortunate , especially since this was a solved problem in editors 30 years ago.
Comment: What I'm doing is copying all the lines to the clipboard and then opening a new window in the main text editor, pasting them in, and using the legit text search tools.
Comment: I'd disagree @AntonyStubbs, sure it's not obvious, but it does keep the UI simple but allows the functionality to exist?
Comment: I only seem to be getting this filter to work in the Terminal tab but not in the Debug Console.
Comment: the correct answer is: the app does not provide a search feature. that is the only one, that can be accepted. unbelievable, btw.
Answer: Since August 2020 and VSCode 1.49, the Debug Console does support filtering:

Debug Console filter

The Debug Console now supports filtering, making it easier for users to find the output they are looking for, or to hide irrelevant logging output.
The filter also supports exclude patterns (for example, patterns starting with an exclamation mark !).
The filter only applies to program output, but not to evaluations run by a user.
Like other input boxes in VS Code, you can use the up and down arrow keys to navigate between old filter inputs.
In the short video below, the output is filtered to entries that include the text 'http', do not include the text 'http' (using the filter !http), and then include the word 'Severity':

(Click on the picture to enlarge. Look for the filter at the top right section of the animation)

And with the upcoming Sept. 2020 VSCode 1.50, you know where you are in your search:

Since last milestone the Debug Console supports filtering, making it easier for users to find the output they are looking for, or to hide irrelevant logging output.
Now we have added a badge to make it clear how many items are filtered away.

Nov. 2023, Sattar Hummatli adds in the comments:

Go to root folder of project and type "flutter logs"

As noted by Troopers in the comments:

You can combine filters (AND) using a comma:
!native, !result

Comment: Filtering is cool and all, but what if what I need is a search? I want to find lines and see their context.
Comment: @GregorA.Lamche True, this is not the same as a search.
Comment: I just want to read through the output without having to use the very fiddly mouse scrollbar. Arrow keys don't work. I have to copy and paste to Notepad++. Every. Time.
Comment: @Resource I agree, that is frustrating.
Comment: Go to root folder of project and type "flutter logs"
Comment: @SattarHummatli Good point. I have included your comment in the answer for more visibility.
Comment: @VonC is there a way to combine filters like `!native && !result`
Comment: @Troopers Not sure (I cannot test it at the moment). Try ` !native !result `
Comment: @VonC a comma between filters is needed `!native, !result`
Comment: @Troopers Good catch, well done! I have included your comment in the answer for more visibility. Thank you for this feedback.
Answer: I recently stumbled upon the same issue and managed to find a workaround that did the trick for me. I thought I'd share it here in case it could help you or anyone else who's grappling with the same problem.

Navigate to the Keyboard Shortcuts section in VSCode Code > Settings > Keyboard Shortcuts.

Use the search bar to look for cmd+f.

After locating the command, check the When column, in my case it indicated that Find should always trigger if editor is open, even if not in focus editorFocus || editorIsOpen.

To make the command functional even when the terminal is in focus, modify the When value to editorFocus || editorIsOpen && !terminalFocus so that it checks if terminal is not in focus when cmd+F pressed.
Answer: To have search instead of filter you need to go to root folder of project and type flutter logs


Joint Distribution of Scaled multivariate Standard normals

Question: Let $X$ be $N(0,I_n)$, a $n$-dimensional multivariate standard normal. Let $Y = X/||X||$. I know $Y$ is distributed uniformly on the surface of a $n$ dimensional "circle" but how do I prove this?
The answer given Here is fine but I am looking for a finding joint density/ using Jacobian transform type answer if possible.
Answer: One way, painful but mechanical: Represent each point $x\in\mathbb R^n$ in "polar coordinates" $(r,\sigma)$ by $x=r\sigma$, where $r\ge0$ and $\sigma\in\mathbb R^n$ with $\|\sigma\|=1$, that is, $\sigma\in S^{n-1}$, and apply the usual Jacobian change-of-variables formula to obtain the joint density for $(r,\sigma)$ when $x$ is a standard Gaussian vector.  The key thing here is that the value of the Jacobian determinant depends only on $r$ and not on $\sigma$.
Another way is to argue from the formula for the characteristic function of the vector $X$:  $\phi(u)=E[\exp(i\langle u,X\rangle)] = \prod_{k=1}^n E[\exp(i u_k X_k)]=\prod_{k=1}^n\exp(-u_k^2/2)$, to obtain (in the end) $\phi(u)=\exp(-\|u\|^2/2)$, and to exploit the spherical symmetry of the formula for $\phi$.


Face detection using local binary pattern

Question: As you know, LBP is a strong feature for face detection. Usually, SVM or other similar classifier is used for classification purpose for this feature.
But in some paper, Adaptive Boosting methods like AdaBoost are used. Using AdaBoost with haar-like feature is clear, because each weak classifier is a haar-like feature with a [x,y,w,h] which we calculate a [threshold, polarity] for it.
But in case of LBP, i could not understand what structure should be used?
I read this paper, it applied LBP (in fact LGP) to each pixel of training images and calculated a histogram for each feature.
but how can we using AdaBoost and a bunch of histograms?
Answer: There is a Haarcascade with LBP features in Opencv. You can use it or see the code to understand how it is done for LBP features.


Align basis of vector space with that of subspace

Question: Suppose I have two real vector spaces $V,S\subset\mathbb{R}^n$ and $S\subset V$. Say the dimension of $V$ is $l$ and that of $S$ equals $m<l$. They are given in terms of their basis vectors $v_i, i=1,\ldots,l$ and $s_i,i=1,\ldots,m$ (as results of the computation of the nullspace of two related homogeneous systems). I want to find a new basis of $V$ such that it reads $\{s_i\mid i=1,\ldots,m\}\cup \{w_i\mid i=m+1,\ldots,l\}$. In other words: how can I systematically compute $w_i,i=m+1,\ldots,l$, which are linearly independent of the basis of $S$. Naively, I would simply solve the linear system $v_i=a_1 s_1 + \cdots + a_m s_m$ for each $v_i$ and discard it (as a basis vector of $V$) if this homogeneous system has a non-trivial solution (to see if it is linearly independent). The set of discarded vectors would then be replaced by the basis of $S$. But, since the algorithm is to be implemented in a computer code, I wonder if this is the most clever solution and if there are flaws. Note that numerical stability is not an issue here. The basis vectors shall all have integer elements.
Answer: You should not solve that linear system involving only the vectors $s_i$. Instead you should check that each candidate vector for $w_k$ is linearly independent of $s_1,\ldots,s_m$ and $w_1,\ldots,w_{k-1}$. Only then is it ensured that the vectors retained form a basis. Given this modification the method is sound.
From a practical point of view, you might want to replace the vectors $s_1,\ldots,s_m,w_1,\ldots,w_{k-1}$, maybe only for use in the test, by another sequence of vectors that span the same subspace, but are in echelon form: for each vector there is a coordinate position (its pivot position) where it is the last in the sequence to have a nonzero entry. Then for any candidate vector $v_i$, you first clear, from left to right for the vectors already in the sequence, the coordinate of $v_i$ that is in its pivot position (by adding a multiple of that vector). After all these coordinates have been cleared the new vector, as well as the original $v_i$, is linearly independent of the retained vectors if (and only if) the new vector is nonzero. If this is the case $v_i$ can be retained, and the new vector is ready to join the vectors in echelon form, with the position of any chosen non-zero entry (for instance the first one) as its pivot position.
Comment: You keep missing the point of my first paragraph: **it does not suffice** (except for the first one) that the $v_i$ you retain be linearly independent on the $s_i$, they should be linearly independent on the $s_i$ **together with the previously retained** vectors $v_i$.
Comment: Thanks for the fast reply. I think I was not clear enough. $w_i$ were supposed to be elements of the basis of $V$ (those $v_i$ which are not linearly dependent on $s_i$; i.e. $w_i$ are already linearly independent). Our approaches should therefore be equivalent, or not?
Comment: And the approach I sketched in the second paragraph already takes into account your wish to make a basis consisting of the $s_i$ together with some of the $v_i$. After considering $v_i$, clearing its coordinates at pivot postions, and testing it to be nonzero (therefore linearly independent), you can retain the _original_ value of $v_i$ in the basis. It is just that for efficiency reasons it is useful to hold, locally, a second (echelon) basis, with pivots, to quickly perform the linear independence test. If $v_i$ is retained in the basis, the modified $v_i$ can go into the echelon basis.
Comment: Now I see your point. Seemingly my linear algebra is a bit rusty.
Answer: Use the Gram-Schmidt algorithm, with the basis vectors of $S$ as your first $m$ inputs.  You will end up with $l-m$ zero vectors, but just discard them.
Comment: **No**. Gram-Schmidt is for making a basis orthogonal, and this question has nothing to do with that.
Comment: Yes, agreed, it does not meet my question, but in fact an orthogonal basis could have advantages for my application. But, would the the non-zero orthogonal vectors be indeed linearly independent of ${s_i}$, the basis of $S$. In principle I am flexible also to change the basis of S to one which is orthogonal.
Comment: I might have slightly misunderstood the question; you actually just want a subset of your initial set of vectors $\{s_i\}\cup\{v_i\}$?  You can still use Gram-Schmidt; just keep track of which indices give you non-zero answers, and at the end, go back and keep the corresponding vectors in your original set.  Marc's suggestion is probably more efficient though.
Comment: I need a basis of $V$ which contains the given basis of $S$ as subset. Alternatively the basis of $S$ may be transformed into a new basis of $S$ (possibly orthogonal). In this case I need a basis of $V$ which contains the transformed basis of $S$ as subset.


Discrete mathematics generating function grabbing balloons restricted.

Question: Say we have 3 different kind of balloons: blue, red and black. If we want to grab k balloons with the restriction that the number of red balloons is al least twice the number of blue balloons. How can i represent this in a generating function? The order does not matter
Answer: Temporarily introduce three variables, $x,y$, and $z$; we'll use the exponent on $x$ to represent the number of black balloons, the exponent on $y$ to represent the number of blue balloons plus the minimum number of red balloons required to accompany them, and the exponent on $z$ to represent the number of red balloons over and above that minimum. The exponent on $y$ is necessarily a multiple of $3$, since each blue balloon must be accompanied by a minimum of $2$ red balloons. A term $x^py^{3q}z^r$ then represents a selection of $p$ black balloons, $q$ blue balloons, and $2q+r$ red balloons; the total number of balloons represented is $p+3q+r$, the sum of the exponents.
Thus, the terms of the product
$$\left(\sum_{p\ge 0}x^p\right)\left(\sum_{q\ge 0}y^{3q}\right)\left(\sum_{r\ge 0}z^r\right)\tag{1}$$
represent the possible selections of balloons, and we're interested in the number of terms $x^py^{3q}z^r$ for which $p+3q+r=k$. If we replace $y$ and $z$ by $x$ in $(1)$, ghat's just the coefficient of $x^k$, so the desired generating function is
$$\left(\sum_{p\ge 0}x^p\right)\left(\sum_{q\ge 0}x^{3q}\right)\left(\sum_{r\ge 0}x^r\right)\;;\tag{2}$$
I'll leave to you the pretty straightforward task of finding a closed form for $(2)$.
Comment: @discreteballoons: You're welcome -- and thank you!
Comment: @iJup: There are always $3$ red balloons. If there are $p$ black balloons, there are certainly $p$ blue balloons as well; that accounts for $2p$ balloons. Finally, there are $q$ additional blue balloons for some $q\ge 1$. Thus, we want the coefficient of $x^n$ in $$x^3\left(\sum_{p\ge 0}x^p\right)\left(\sum_{q\ge 1}x^q\right)\;.$$
Comment: @iJup: Oops: that should have been $$x^3\left(\sum_{p\ge 0}x^{2p}\right)\left(\sum_{q\ge 1}x^q\right)\;.$$ The first summation is just a geometric series with ratio $x^2$, so it's equal to $\frac1{1-x^2}$. The second is a geometric series with ratio $x$ and first term $x$, so ...
Comment: @iJup: If the number of blue balloons is allowed to be equal to the number of black balloons, then the second summation must start at $q=0$: you're now allowing the excess to be $0$.
Comment: Thanks for all the help. Very clear explanation!
Comment: @BrianM. Scott Can you help us further on to give some help with the exp. gen. function when we grab exactly 3 red balloons and more blue than black balloons? Thanx in advance!
Comment: Thank you for the quick response! In response to the above expression and (2) (with the summations): what sort of closed form we are looking for to express the generating function?
Comment: And does it make a difference if order counts for grabbing three balloons, $p$ black, and $\geq p$ blue balloons?
Comment: Sorry for another comment. If order counts, we are interested in case summations in thus form $\sum\limits_{k=0}^n \frac{n!}{(n-k)!}x^k$?


Generate random hexadecimal colour in Twig

Question: I want to generate random hex colors in Twig, to use it for example as a background in something like this:
<code>{% for organization in organizations %}
    {
        value: {{ organization.value }},
        color: "#F56954",
        label: "{{ organization.name }}"
    },
{% endfor %}
</code>
Any way to do it?
Answer: I suggest you to randomise a know set of data (in order to exclude no sense values) as follow:
<code>{% for organization in organizations %}
    {
        value: {{ organization.value }},
        color: "{{ random(['#H54924', '#F36252', '#F56954']) }}"
        label: "{{ organization.name }}"
    },
{% endfor %}
</code>
EDIT:
For pure random values, you can try the following approach:
<code>{% set values = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']%}
{% for organization in organizations %}
    {
        value: {{ organization.value }},
        color: "#{{random(values)~ random(values)~ random(values)~ random(values)~ random(values)~ random(values)  }}",
        label: "{{ organization.name }}"
    },
{% endfor %}
{{ '#' ~ random(values) ~ random(values) ~ random(values) ~ random(values) ~ random(values) ~ random(values)  }}
</code>
Here a working example
Hope this help
Answer: <code>class SomeUtil
{
    /**
     * @return string hex color string (RGB): #XXXXXX
     */
    public static function randHexColor()
    {
        return sprintf("#%06s", dechex(rand(0, 256**3-1)));
    }

    /**
     * @param int $rangeFrom [0..255]
     * @param int $rangeTo [0..255]
     * @return string hex color string (RGB): #XXXXXX
     */
    public static function rangedRandHexColor($rangeFrom = null, $rangeTo = null)
    {
        $min = 0;
        $max = 255;
        if ($rangeFrom === null || !NumberUtil::inRange($rangeFrom, $min, $max)) {
            $rangeFrom = $min;
        }
        if ($rangeTo === null || !NumberUtil::inRange($rangeTo, $min, $max)) {
            $rangeTo = $max;
        }
        if ($rangeFrom === $min && $rangeTo === $max) {
            return self::randHexColor();
        } else {
            return sprintf("#%02s", dechex(rand($rangeFrom, $rangeTo)))
                .sprintf("%02s", dechex(rand($rangeFrom, $rangeTo)))
                .sprintf("%02s", dechex(rand($rangeFrom, $rangeTo)));
        }
    }

}
</code>
In controller
<code>$data['util'] = new SomeUtil();

return $this->renderView('AppBundle:Foo:bar.html.twig', $data);
</code>
In twig
<code>{{ util.randHexColor() }}
</code>
or
<code>{{ util.rangedRandHexColor(180, 220) }}
</code>
to exclude dark and LSD colors


if title available print $title if disabled print somthing else

Question: I use advanced forum but it uses default Drupal title method.
I know there is a module called Comment subjects for this purpose but I need to do it in this way.
I would be grateful if anyone could help me.
 if $title >avalible print $title
 if $title disabled print
<a href="#<?php echo $comment->cid; ?>"> Re: <?php print $node->title ?>

OR
 if > node print $node->title
 elseif comment $print
<a href="#<?php echo $comment->cid; ?>"> Re: <?php print $node->title ?>

Answer: Found the Solution.
Go to -> (advanced_forum/styles/naked/advanced-forum.naked.post.tpl.php)
  <?php if (!empty($title)): ?>

      <?php print $title ?>

  <?php endif; ?>

Then replace it with:
<?php if (!empty($title)): ?>

        <?php print $title; ?>

<?php else: ?>

<a href="#comment-<?php print $comment->cid; ?>"> Re : <?php print $node->title ?>

<? endif; ?>

Comment: I think you have a XSS vector in the title printing - it should be run through `check_plain()`. Personally I always try to avoid using a template if I can achieve the same effects by using a preprocess and modifying variables (which in this case is easily possible by modifying `$vars['title']`).
Answer: When you disable the title tag does the node have value? Because if it does, all you need to do is adding an control statement.
if ($node->title[array values] == the disabled value) {
  // What I need to print here.
}
else {
  // Print the rest.
}


runtime winform designer for users

Question: We are trying to build a budget program. It is going to be a big project. We want to let users build their own WinForms and controls into it. Then do some databindings but that is the next step.
Is there way to build a "runtime form designer" in c# ? I am reading this PAGE. It says it is possible but It doesnt give enough information to start and finish the designer.
Thanks,
Comment: This sounds terrifying.
Comment: You know you are creating a monster, don't you? You'll end up with some bastard cross between Sharepoint and Visual Studio's IDE.
Comment: do u have a year or so to do it? cus' if not, quit now
Comment: Of course there is, since you can add and remove controls programmatically. (It would take a lot of work however.) Could you specify what's causing you problems? Your question seems to be too broad to be answered reasonably.
Comment: my boss want to me create such a designer. I know it is huge but I have to do it somehow. My question is too broad, I know. But I dont how to start to build designer:) I am gooogling all day and I couldnt find a very good tutorail to start
Comment: I would recommend that you look into [DevExpress](http://www.devexpress.com/), or some other component library that has support for runtime customization. (Disclaimer: I don't work for DevExpress, but I'm a happy customer.)
Comment: Sounds like your boss thinks your customers are smart enough to build their own applications. As soon as you finish this project, you're out of work. Luckily you will never finish this, as it is mere impossible. Not in the first place because users aren't developers. - @Renan, don't forget DreamWeaver / FrontPage.
Comment: This can easily be done with WPF and MEF (to have these forms included in the application as compiled assemblies). winforms in general is very limited. Still, @CodeCaster is right, as soon as you finish this you're out of work. And users are not developers (unless they really are)
Answer: This is a short answer because I can't give you a full answer; that will require too much time...
Basically you need to create a form and a ToolBox, just like VS, and have the users Drag-and-Drop the controls. The Drag-and-Drop needs to be enabled and it's event handled. You also need in the drop event handler to get the mouse position on the Form and programmaticaly create a default control there.
Now, a lot of questions come to mind. Those will have to be addressed as they come, because I can't answer them all in less than a day.

runtime winform designer for users


Plist: what it is and how to use it

Question: What exactly is a .plist file and how would I use it? When I view this in xcode, it seems to generate some kind of template vs showing me some xml code. Is there a way that I can extract the data in a plist file by pushing the contents into an array? Also, where can I view the source of the .plist?
Answer: You can easily get the contents of a plist into an array by using the following code (we're opening here the file called 'file.plist' that's part of the Xcode project):
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"];
contentArray = [NSArray arrayWithContentsOfFile:filePath];

A plist is just a XML file which corresponds to some DTD (datatype dictionary) designed by Apple, the DTD can be seen here:

http://www.apple.com/DTDs/PropertyList-1.0.dtd

The DTD -among other things- describes the "objects" and datatypes that the XML file can contain.
Answer: Plist is short for property list. It is just a filetype used by Apple to store data.
You can get more info here:
http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man5/plist.5.html
If you want to read in plists check here:
// Get the location of the plist
// NSBundle represents the main application bundle (.app) so this is a shortcut
// to avoid hardcoding paths
// "Data" is the name of the plist
NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];

// NSData is just a buffer with the binary data
NSData *plistData = [NSData dataWithContentsOfFile:path];

// Error object that will be populated if there was a parsing error
NSString *error;

// Property list format (see below)
NSPropertyListFormat format;

id plist;

plist = [NSPropertyListSerialization propertyListFromData:plistData
                                mutabilityOption:NSPropertyListImmutable
                                format:&format
                                errorDescription:&error];

plist could be whatever the top level container in the plist was. For example, if the plist was a dictionary then plist would be an NSDictionary. If the plist was an array it would be an NSArray
Here the format enum:
enum {
   NSPropertyListOpenStepFormat = kCFPropertyListOpenStepFormat,
   NSPropertyListXMLFormat_v1_0 = kCFPropertyListXMLFormat_v1_0,
   NSPropertyListBinaryFormat_v1_0 = kCFPropertyListBinaryFormat_v1_0
}; NSPropertyListFormat;

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/SerializePlist/SerializePlist.html.html
Comment: thanks for the code. Would you be able to tell me line by line what you're doing here? Also I'm not sure what some of these datatypes are (NSBundle, NSData, NSPropertyListFormat, NSPropertyListSerialization).
Comment: @locoboy search [Apple Developer Documentation](https://developer.apple.com/documentation/) - [NSBundle](https://developer.apple.com/documentation/foundation/nsbundle?language=occ) [NSData](https://developer.apple.com/documentation/foundation/NSData?language=occ) [NSPropertyListFormat](https://developer.apple.com/documentation/foundation/NSPropertyListFormat?language=occ) [NSPropertyListSerialization](https://developer.apple.com/documentation/foundation/NSPropertyListSerialization?language=occ)
Answer: A little more on @AdamH's answer from Feb. 2021

propertyListFromData has been deprecated by dataWithPropertyList since iOS 8.0 macOS 10.10

Apple seems to be incorrect. It should be propertyListWithData instead of dataWithPropertyList

void dump_plist(const char *const path){@autoreleasepool{
  NSError *err=nil;
  puts([[NSString stringWithFormat:@"%@",[NSPropertyListSerialization
    propertyListWithData:[NSData dataWithContentsOfFile:[[NSString new]initWithUTF8String:path]]
    options:NSPropertyListMutableContainersAndLeaves
    format:nil
    error:&err
  ]]UTF8String]);
  assert(!err);
}}

E.g. to dump device's network configuration settings to stdout
dump_plist("/private/var/preferences/SystemConfiguration/preferences.plist");

Plist: what it is and how to use it


insert value without setting primary key

Question: i got minimal database like so
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(8) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `pass` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `reg_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=40 ;

then i try to insert new user, setting only username/email/pass

"INSERT INTO users SET name='user_name', email='users_email', `pass = 'users_top_secret_pass."';

or every time i ned insert new id like:
INSERT INTO `users` (`id`, `name`, `email`, `pass`, `reg_time`) VALUES
(1, 'user', 'email@example.com', 'pass', '2016-01-31 03:10:13');

name and email are UNIQUE, time is default current timestamp and i no need  to test them. This is good but how i can be insert id, and does i need it?
testing on local phpmyadmin gives me nothing new.
upd: removed outdated code with php functions, only sql.
Comment: You don't need to insert a value for `id`.  That is what `auto_increment` does.
Comment: Stop using the **deprecated and as of PHP7 removed** mysql_* functions. Migrate to PDO and start using Prepared Statements.
Comment: thx but on 99% where i work it php5. and about auto_increment, without setting it i got errors. mb problem on mysql side.
Answer: mysql_query("INSERT INTO `users` ( `name`, `email`, `pass` ) values('".$user."', '".$email."', '".$pass."') ");

Insert query syntax wrong you are using update query syntax in you code..
Comment: MySQL supports `set` for `insert`.  This is a MySQL extension.  You can read about it in the documentation:  http://dev.mysql.com/doc/refman/5.7/en/insert.html.
Answer: omg, just setting null, and it good works!!!!
INSERT INTO `users` (`id`, `name`, `email`, `pass`, `reg_time`) VALUES
(null, 'user', 'firstname.lastname@example.com', 'pass', null);

Comment: This is answer is for specific version of mysql.
Answer: Your insert query is having id, if your table is not having any record with id 1 which is your table's primary key then it will work correct. If table is having and record with id 1 then it will cause a Fatal error.
Note:- basically primary key of table should be auto incremented. For date time auto update in PHPMyadmin set column default value for CURRENT_DATETIME.
INSERT INTO `users` (`name`, `email`, `pass`, `reg_time`) VALUES
('user', 'firstname.lastname@example.com', 'pass', '2016-01-31 03:10:13');


Need help understanding a proof (Bipartite Graph)

Question: I was reading lecture notes of graphs(from MIT 6042) and am having trouble understanding this proof:

I can't understand Let d be value such that deg(l) >= x >= deg(r), what values do d and x represent here and why did we consider them?
And how did we arrive at |N(S)|x >= |S|x?
Note:
Comment: It might help if we knew the definition of a "bottleneck" and the statement of Theorem 5.2.5.
Answer: I suspect that $d$ should be replaced by $x$.  The consideration of $x$ must arise from the definition of "degree-constrained" - this is a term I am not familiar with.
Now for any subset $S$ of vertices in $L$, we have $d(v) \ge x$ for all $v \in S$.  Hence the number of edges leaving $S$ is $\sum_{v \in S} d(v) \ge x |S|$.
On the other hand, every such edge goes to $N(S)$ (by definition of what $N(S)$ is).  Every vertex in $v \in N(S)$ is in $R$, and hence receives $d(v) \le x$ edges.  Thus the number of edges from $S$ to $N(S)$ is at most $\sum_{v \in N(S)} d(v) \le x |N(S)|$ (note that vertices in $N(S)$ could also receive edges from vertices not in $S$, so even the sum of degrees is just an upper bound here).
Hence, by double-counting edges from $S$ to $N(S)$, we have
$$ |N(S)| x \ge e(S, N(S) ) \ge |S|x . $$
Comment: `x` has nothing to do with degree constrained. I edited the question and added its definition. I also can't understand the last line: `by double-counting edges from S to N(S)`, what does this mean? I am sorry if my questions are too basic.
Comment: Thanks for the definition.  $x$ does have to do with the graph being degree constrained: for example, take $x = \min_{v \in L} \text{deg}(v)$.  The degree constrained condition then guarantees $\text{deg}(l) \ge x \ge \text{deg}(r)$ for all $l \in L, r \in R$.
Comment: As for the "double-counting" line, we have a lower bound on the edges from $S$ to $N(S)$ by summing the degrees of the vertices in $S$.  We have an upper bound on the same quantity by summing the degrees of the vertices in $N(S)$.  Since these are bounding the same quantity, the upper bound must be bigger than the lower bound, which gives us the inequality we were looking for.


Migrating ExpressionEngine to Drupal 7 DONE but Password is not working

Question: I have migrate EE users in to Drupal using user_save() function but when users are trying to login with EE password they can not able to login and getting password is wrong. I have used below code to migrate data.
<code>foreach($result as $eeUser) {

    $drupalUser = user_load_by_name($eeUser['username']);

    if (!$drupalUser) {
        $user_array = array(
            "name" => $eeUser['username'],
            "pass" => $eeUser['password'],
            "mail" => $eeUser['email'],
            "status" => 1
        );
        user_save($account, $user_array);
   }
}
</code>
Answer: EE does not store passwords.  It stores hashes of passwords, actually I think it stores salted hashes of passwords.
So what you have migrated into Drupal is a hash not the password.
I believe Drupal also stores hashed passwords rather than the passwords themselves.
If your install of Drupal were to use the exact same hashing method as EE only then could your users login using their existing password.
I think you would be better off asking your existing users to reset their passwords.  I'm not a Drupal guy but maybe you can loop through your users and send them all an email with a reset password link.