How do I pass a variable from a custom module to its template file?

Question: I need to know the simplest method to pass variable from custom module to its template file.
I have created the custom.module and placed custom.tpl.php in the module folder.
function custom_menu(){
  $items = array();

  $items['custom'] = array(
    'title' => t('custom!'),
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_page() {

    $setVar = 'this is custom module';
    return theme('custom', $setVar);
}

i have added theme function but it is not working, can any one suggest me what is wrong with this code
function theme_custom($arg) {
  return $arg['output'];
}

function custom_theme() {
  return array(
    'Bluemarine' => array(
        'variables' => 'output',
        'template' => 'Bluemarine',
     ),
  );
}

Answer: Independently from the Drupal version for which you are writing the module, there are two errors in your code:

You define "Bluemarine" as theme function, but then you call theme('custom'), which would call the "custom" theme function
If you define "custom" as a theme function that uses a template file, then theme_custom() is never called

If you are writing code for Drupal 6, then the code should be similar to the following one. I take the assumption the name for the theme function is custom.
function custom_menu(){
  $items = array();

  $items['custom'] = array(
    'title' => t('custom!'),
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
      'template' => 'custom',
     ),
  );
}

function custom_page() {
    $output = 'This is a custom module';
    return theme('custom', $output);
}

function theme_custom($output) {
}

The template file will have access to $output, and to any variables set in template_preprocess_custom(), if your module implements it.
For example, you could implement code similar to the following one:
function template_preprocess_custom(&$variables) {
  if ($variables['output'] == 'This is a custom module') {
    $variables['append'] = ' and I wrote it myself.';
  }
}

With this code, the template file has access to $output and $append.
As example of theme function that uses a template file, you can look at theme_node(), which is defined in node_theme(), and that uses node.tpl.php as template file; the preprocess function implemented by the Node module for that theme function is template_preprocess_node().
Comment: Thanks Kiam, obviously missed OP's first comment about using D6. +1
Comment: Thanks Kiam, template_preprocess_custom(&$variables) did the trick
Comment: Now I want to move tpl to theme folder, how can i do that?
Comment: @KamranAkhter That is a different question. `:-)`
Answer: You are calling the wrong theme function. Instead of function theme_custom it should be function theme_Bluemarine. You also need to pass an array to the variables piece of hook_theme().  See a simple example here.
Using your example (after changing template and theme function to custom):
function custom_menu(){
  $items = array();

  $items['custom'] = array(
    'title' => t('custom!'),
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_page() {
  $setVar = 'this is custom module';
  return theme('custom', array('output' => $setVar));
}

function custom_theme() {
  $path = drupal_get_path('module', 'custom');
  return array(
    'custom' => array(
        'variables' => array('output' => null),
        'template' => 'custom',
     ),
  );
}

Now in custom.tpl.php just need <?php print $output; ?>
Comment: Thanks for reply the example u gave is node module and i have non node module.i just need a way to pass variable to tpl file, i m using drupal 6.plz help
Comment: Thanks for reply, it is giving me the error No such file or directory actually it is expecting the file custom.tpl.php in the module folder which i already have so in code bluemarine will be replcaed by custom. Bluemarine is the drupal theme which i m using.
Comment: changed the above code and giving me the white blank screen what should i do plz help
Comment: I changed the code, and I have it working on my site.
Comment: I just copy paste the above code but it does not work
Comment: Need more details than "it doesn't work". Is there an error? Do you have a custom.tpl.php file in the module's directory? Did you navigate to example.com/custom ?
Comment: No Error. custom.tpl.php and custom.module in sites\all\modules\custom folder. yes navigate through example.com/custom, it is showing me the title custom which is defined in custom_menu()
Comment: The code reported in this answer is for Drupal 7, while the OP is interested in an answer for Drupal 6. (See his first comment. The Drupal version should have been reported in a more prominent place, but this isn't an issue, since a question that doesn't make clear what version the OP is using can have answers for different Drupal versions.)


Validar inputs em formulário com expressões regulares

Question: Eu tenho campo de Contatos na page onde o usuário deve preencher, por exemplo, o nome, ele deveria apenas digitar letras, no campo telefone, apenas números e email obrigatório o uso do "@". A ideia é exibir uma mensagem para o usuário quando ele inserir número no campo "nome" e assim por diante.
Eu consegui capturar o input do usuário, mas a expressão regular não funciona.
Este é meu código:
var validaNome = $("#input-nome");
validaNome.on("input", function(){
    var digitado = validaNome.val();
    var comparavel = new RegExp("ab+c");

    if(digitado <= comparavel){
        $(".digite-nome").css("display", "none");
    }else {
        $(".digite-nome").css("display", "block");
    };
});

A variável comparável recebe a expressão regular e então usa-la na validação.
Alguém poderia me ajudar? Ou existe outra forma de validar isto?
Answer: Dei uma outra resposta parecida mas para cartões de crédito. A ideia interessante lá é a organização de código, que facilita a leitura e desenvolvimento.
Poderias fazer isso assim:

var inputs = {
  nome: /^[\w\s]+$/,
  telefone: /^[\d\s]+$/,
  email: /^[^@]+@[^@]+\.[^@]+/
};

$("form input").on("change", function() {
  var tipo = this.name;
  var regex = inputs[tipo];

  if (this.value.match(regex)) alert('O campo ' + tipo + ' está válido!');
  else alert('O campo ' + tipo + ' está inválido!')
});
Comment: INCRIVEL!
INCRIVEL!

Muito obrigado
Answer: Para validar o nome você pode utilizar este regex:
/^[\p{L}\s]+$

Para o telefone
/(\d{3}|\d{2}|\(\d{2}\))\s*(\d{9}|\d{8})

E para email
/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;

Comment: Não funciona, porque o navegador parece interpretar a variável como uma string...
Comment: Quando adicionar o console.log dentro do IF e do ELSE, consigo ver os inputs do usuário comparando com a variável.
Ele só da "Okay" se eu digitar /^[\p{L}\s]+$. não lê como uma expressão regular.


Filter nodes based on active context

Question: Is it possible to filter nodes based on whether a certain context (defined by context module) is active? I can't find a way to do this. I'm using Drupal 6 and context 6.x-3.0.
Let's say we have a certain menu path that activates a context. In this context I have a view and I need to filter nodes that belong to the context (that is they belong to the menu, that activates the context).
Comment: Please elaborate on the filtering. Do you want to filter the nodes from a view? On which pages are you seeing nodes that you need to be filtered out?
Answer: Making context aware Views is not something you can easily do with Context module. That is I'm sure it would be possible, but it would require a lot of work.
Panels is designed to accomplish such tasks, with it's tight integration to views, it can pass arguments to views that you can use to determine what to display.
Answer: Views default argument from Context is a project that might help you out. (I've not used it yet, just remembered seeing it a while back.)
It looks like you'll need to write a small module with a bit of glue code. See these configuration notes in the issue queue for the module:
http://drupal.org/node/774966

Filter nodes based on active context


Infinite sequence of rational numbers converging to x proof

Question: I really don't understand how to do proofs on convergence at ALL.
I know you're supposed to use $|x_i - x| < \epsilon$ but I have no idea how to apply this to this question:

Show that if $x$ is any real number then there is an infinite sequence of rational numbers converging to $x$.

Any hints or help will be greatly appreciated!
Comment: You might have a look at some similar questions already posted on this site. For example, http://math.stackexchange.com/questions/209001/how-can-i-prove-that-for-every-real-number-a-there-exists-a-sequence-r-n-of or http://math.stackexchange.com/questions/117146/sequence-of-rationals-converging-to-a-limit
Answer: Are you familiar with the density of the rationals? If so,
For every $n\in \mathbb{N}$, let $x_n$ be a rational in the open ball $B(x,\frac{1}{n})$. By the density of the rationals, there is always one such a $x_n\in\mathbb{Q}$. Then for any $\epsilon>0$, there exists $N$ such that $\frac{1}{N}<\epsilon$ by the Archimedean property. Then, for all $n>N$, $x_n \in B(x,\frac{1}{N})\subset B(x,\epsilon),$ meaning $|x_n -x|< \epsilon$.
Answer: Assume $x>0$ and irrational. If $x$ is rational, define $x_n:=x$ for all $n$.
Let $a_n:=\left\lfloor  x10^n\right\rfloor$ and define $b_n:= \left\lfloor 10^{n} x-10a_{n-1}\right\rfloor$. And finally $x_n:=\sum\limits_{k=0}^{n} \frac {b_k}{10^k}$. Basically I'm truncating $x$ to $n$ decimals at the $n$'th term in the sequence.
The breakdown:
We will write $x=b_0\cdot b_1 b_2 b_3 \ldots\;$, where $b_i \in\{0,1,2,\ldots,9\}$ for each $i \in \mathbb{N}$ and $b_0 \in \Bbb{N}_0$, with the convention that there does not exist an $N \in \Bbb{N}_0$ such that for all $i> N$ we have $b_i=9$. We do this to rule out ambiguities like $1=0.\dot{9}$
How you might write $x$ as a decimal is kinda the above method unless you know something special about the number. We want the $n$'th digit so we compute $a_{n-1}$ and $\lfloor 10^n x \rfloor$, and plug it into $b_n$ above. ($b_n$ also equal $\lfloor 10^n x\rfloor-10a_{n-1}$ because the second term is an integer less than or equal to the first term)
To show this works, suppose we have the decimal expansion as above.
$a_n=\left\lfloor  x10^n\right\rfloor=\left\lfloor b_0 b_1 b_2 b_3 \ldots b_n\cdot b_{n+1}b_{n+2}\ldots\; \right\rfloor=b_0 b_1 b_2 b_3 \ldots b_n$ as a decimal number, not multiplied.
Then we have that
$\left\lfloor 10^{n} x-10a_{n-1}\right\rfloor=\left\lfloor  b_0 b_1 b_2 b_3 \ldots b_n\cdot b_{n+1}b_{n+2}\ldots\;-b_0 b_1 b_2 b_3 \ldots b_{n-1} 0\right\rfloor=\left\lfloor  b_n\cdot b_{n+1}b_{n+2}\ldots\;\right\rfloor$
which is just $b_n$. So we now know the $n$'th digit, so we more or less say what we started with, that $$x=\sum\limits_{k=0}^{\infty} \frac {b_k}{10^k}=b_0\cdot b_1 b_2 b_3 \ldots\;$$
and we just take the partial sums, which are finite sums of rationals and so are rational:
$$x_n:=\sum\limits_{k=0}^{n} \frac {b_k}{10^k}=b_0\cdot b_1 b_2 b_3 \ldots b_n\dot0\;$$
Also then $|x-x_n|<\large\frac{1}{10^n}$.


Can you change some composition I wrote to whatever music you want just by changing the timbre of the instruments?

Question: Here is my problem: suppose I am a composer you have contracted to create any sheet music I dream of with the unique condition it is not pure silence and that I don't stipulate the instrument section (which means, don't specify the timbre). Suppose you are the one who is in charge of the execution of the music, and you have in your disposition any kind of instrument, room, high tech equipment you ask — and suppose also that you hate me. Could you just by changes on the non-fundamental harmonics and non-fundamental frequencies aspects of the sound wave change my original composition so that it sounds something like Baby Shark melody or whatever you want?
Well, I will try to put this question on better words.
What I learned about timbre is that it is defined by the wave format and the envelope of the sound. So the same fundamental frequency can have different wave formats, a perfect sine wave or some irregular pattern, like a saw, or other things. Others definitions seems to point that timbre is about the harmonics analysis of the sound. I think these two definition are connected, because the wave format determines the harmonics of a sound (is that right?).
But if we just think about the sound wave, it could be mathematically decomposed on a sum of sine waves (I remember people saying this is the Fourier sum). So, in thesis, you could reproduce an approximation of the timbre of an instrument on a computer by this process. I guess this is what people do when they try to imitate a violin on a computer. Equivalently, I think that in theory you could control also this wave parameters so that you could create a sound corresponding to any wave format you want. I think this is what people who synthesize sounds do.
I understand also that when you play two instruments at the same time the air molecules make some kind of sum of the waves and this is why you could have the destruction phenomena of waves that cancel each other and produce silence.
Now this is my thought process to arrive at this question:  I think you could, given a sound source, to change a second sound source so that the sum of the two waves produces another fundamental frequency different of the first instrument, because you can cancel the fundamental frequency by the above process and just let the harmonics of the two sounds sources audible. I think the question is if there is some way to make a destructive interference of the fundamental frequency, and resonance of the components of the sound wave, such that in the sum of the waves you could determine the fundamental frequency of each individual instrument, even if this fundamental frequencies of the instruments were determined before they were played.
But if you could do this, perhaps with a sufficient number of sound sources (you could even repeat the same note if necessary),you could change the fundamental frequency of the first instrument when you sum up all the waves of the sound sources to some other harmonics you determine.
But this is all just second hand information I received, and this is why I am here to ask you if this makes sense. The important thing to me is not to have an answer, I just to understand if what I am thinking makes sense, what are my errors, and how can I do to make a better question. Besides, I think interesting to think what kind of parameter you could relax in this experiment to have a better result. For example, if someone have all the power of the sheet music and the timbre of the music, how much could he play with this interference so that he make a music with harmonics.
Comment: OK so I hate you but I hire you to write a composition for me that I then try and make sound different and worse than what you wrote even though I paid for it? That plus mentioning Baby Shark song gets a +1 from me. The question itself is very deep and almost better suited to science than music, I look forward to the responses.
Comment: I'm pretty sure the answer to your question is yes, but I'm struggling to see what you hope to gain by going to the trouble of finding waves that would cancel the original composition out, when in most cases you could take the simpler approach of just not rendering the original composition at all. (I can guess that perhaps you might be thinking this will facilitate some interesting cross-fading out morphing? But I'm not sure that's what you mean at all...)
Comment: If I am constrained to non-fundamental frequencies, doesn't that imply that the resulting waveform must contain the fundamental frequency?  Can I add non-harmonic "overtones"?  Are you asking whether it's possible to invent (1) an instrument such that when you play one tune on the instrument the listener hears another tune, or (2) two instruments such that when you play tune A on one, the listener hears tune A, but when you add the other instrument, the listener hears tune B?
Comment: Does a sampler count as an instrument? i.e. a device which plays, say, "You Spin Me Round (Like A Record)", at different pitches, every time you press a key.
Comment: @John Belzaguy,  I think this 007-like villain plot came out of some kind of inner desire to humiliate the figure of the romantic composer who love his composition more than anything, haha. Yes, I first asked this question on mathematics stack exchange, then they transferred the question to physics community, then they close the question and said it were more adequate to here. https://physics.stackexchange.com/questions/560344/can-the-timbre-of-the-instrument-section-of-a-music-completely-change-the-music/560600?noredirect=1#comment1267152_560600
Comment: @Lostdefinition Well even though your question is legit and interesting I did get a major chuckle from your setup. Considering the number of answers and positive feedback everyone else seemed to enjoy discussing it!
Comment: But I think the question I made there was confuse, I didn't explain enough what I was defining by timbre, nor my thought experiment.
Answer: Destructive interference would effect what you hear, but that doesn't change the composition.
You could do other things to make a performance or playback inaudible, like move very far away or put a jackhammer next to the listener. Interfere however you like, that won't change the composition, because the composition is purely conceptual.
Comment: Yes, I think the way I made my question allows your answer if you say the noise resulting of the jackhammer is what you want to your music sound like, hehe. I guess in this conceptual view my question is even ambiguous, because timbre is part of a composition as well. I think your answer gives an afirmative answer to the question, but I want to exclude this cases to think not chaotic musics. Nice philosophical point.
Comment: @Lostdefinition, how does... "and suppose also that you hate me" ...have any bearing on the question? I just ignored that part, but if you really want an unambiguous case, I think the question needs to be re-written. It seems like your question is more like: can waveform interference make a listener hear another, arbitrary composition, example, Beethoven's Fifth is playing, but waveform interference causes the listener to hear Happy Birthday played by a flute.
Answer: You can do this. All you need to do is invert the signal, i.e. generate a waveform that is the exact negative of the input waveform and add it to the input so there is no signal left. This is how noise-cancelling headphones work. Then you add in your own signal.
Why anybody would go to the trouble of doing this, is a completely different question.
Comment: This answer makes it clear that this is essentially a math question.
Comment: "Why anybody would go to the trouble of doing this": it's an interesting engineering exercise.  But the question limits activity to "changes on the non-fundamental harmonics and non-fundamental frequencies."  Would it be possible to cancel out the fundamental under that constraint?
Comment: It seems that your answer, although not wrong, completely misses the point.  Noise (all sound) cancellation is easily accomplished by 180 deg phase shift copy of the signal added to the original.  This does NOT create new frequencies, or change the fundamental pitch of the song.
Comment: @ggcg Adding new frequencies is the second part of the operation, although the new signal could probably be mixed with the phase-shifted one
Comment: @ggcg  You could noise cancel low-frequencies only, which can be easily done with a low-pass filter. If the frequency difference between the fundamental and the overtones is great enough (that might be the hard part) you could noise cancel only the fundamental. The first overtone would then, for the ear, become the fundamental.
Comment: @Tom_C, NEVER!  You are missing the effect of fundamental tracking.  Unless you cancel EVERYTHING but one overtone.  Also, the OP started with a bland un-timbered sound (that was a constraint).  So there is only one note to cancel.  Leaving silence.
Comment: @PiedPiper, based on the criterion of the OP the entire exercise is "adding new frequencies".  At this point you may as well plug in a keyboard and rewrite the tune.
Comment: @ggcg That's true, let's say cancel the fundamental and all its harmonics, except one harmonic and all its own harmonics ;).
Comment: But, I think I have pointed this destructiion effect on my question. I think your answer is incorrect because when you add this new signal, this new signal would have to follow the fundamental frequency of the original composition. So you are just changing the problem of place, from a far away source to your ear channel. And for the reasons why, I think it could be interesting to think about the ear perception of the non fundamentals harmonics and timbre oriented music, and have a better understanding of these concepts.
Answer: As John Belzaguy said, this is much about science, I'll try my best to put that in a musical point of view.
In theory, what you are are saying is yes: two waves can cancel each in the process called destructive interferences. This is the process used for tuning a guitar using harmonics. However, there are a few problems…
Coherency of the waves
In order to interferes, your (let's say two) waves need to be coherent: they should have exactly the same frequency, and a phase ratio between them which is constant. This is hardly possible when using different sources, and is why, while light is also a wave, you do not a have black spots appearing when you light an additional light bulb: you first light bulb, and your second are not coherent one with each others.
The only this could be possible is with stereo digital instrument, which can have a very good control on the emitted wave. Here comes a second problem:
Spatial interference pattern
Let's say you have your instrument (I'm using the stereo digital synth for instance) producing two waves that should interfere with each other: exact same frequency, in anti-phase (when one is at maximum of pressure, the other one is at minimum). While, outputting this in mono would actually cancel the wave, in real life your waves need to fulfill the anti-phase condition at the precise spot you are listening. Unfortunately (or fortunately I do not know), as your two waves propagate, the time it will take them two reach your ears will not be the same in the general case. So even if the waves were in anti-phase when emitted, you ones you ear have no reason to be in anti-phase. With pure waves, here is the kind of patterns you can expect, I let you imagine that, in 3D it is a nightmare… The spots of destructive interference are also dependent on the frequency of the wave… So you'll need to move according to the music (isn't that dance?!) to follow the destructive pattern to keep the effect.
To solve this at any point, you two sounds emitters need to be very close. This is why tuning a guitar using interference works, however, if you succeed in producing no sound with two strings on a guitar, please send me the video!
I typed that fast, if any point is not clear, do not hesitate and I'll edit.
Comment: @Lostdefinition If you are in the close field of the sound emitters, those "black" spots (if they exist) will be located at different space location depending on the frequency. In that case, you need to move around to stay in a destructive interference node.
Comment: @Lostdefinition If you are far away, and have no echo like in an anechoic chamber, situation is much more easy. If you allow yourself an electronic device in the path between the instruments and you then you possibly could interfere with them before they enter your ears. For noise cancelling headphones, this part is made easy by the fact they are very close to your ears.
Comment: "if you succeed in producing no sound with two strings on a guitar": I don't suppose the vibration modes of a guitar's bridge are such that two strings could cancel each other out; even if they were 180 degrees out of phase, the bridge would probably be twisting somewhat. The wavelength of the high E string is about 104 cm (`(343 m/s) / 329.63 Hz`). If you put a couple of guitars a couple of meters apart, tune their E strings to the same frequency, and play both E strings, you should at least be able to find a spot somewhere between them where the amplitude of the pitch is much smaller.
Comment: @phoog that was exactly my point, there are a lot of additional effects which makes this possible. Also, tuning two different strings to the same frequency is likely to be impossible in real life. You may have a beating sound, just like with harmonics tuning.
Comment: Musicians regularly tune strings to avoid beats.  It's not impossible at all.
Comment: @phoog  To avoid beats they can hear... Very slow beats are impossible to perceive for a human.
Comment: If you could do that without physical connection between the two, I guess that quite a few metrologist would be interested ;).
Comment: Yes, "very slow beats are impossible to perceive for a human," and beats that are so slow that they can't be detected correspond to pitches that *are the same* given the precision and tolerance of our measurement device (namely, the human ear).  To the point of this example, it also means that the interference nodes for which the experimenter is listening will be moving imperceptibly slowly, and that the experimenter will therefore, as I said, be able to find a spot somewhere between the guitars where the amplitude of the pitch is much smaller.
Comment: @phoog That is too bad these spots are frequency dependent… That would be convenient at a bad music gig ;)…
Comment: For me, such an effect (very slow motion of the node spot) if actually of the same order of secondary effects affecting two adjacent strings on a guitar, bridge vibration, non-linearity of the strings and so on…
Comment: Yes, I I think your answer address the main challenge to do this kind of sound wave interference on a room and not a small space. Guess it would be really a nightmare, thinking about a 3D interference. But I didn't understand the dance part of your answer: "So you'll need to move according to the music ", you mean moving on the room?
Comment: But I think the premise of my question wouldn't be broken if you have a headphone noise-cancelling-like and a far away sound source playing. I think the complexity of the 3D interference could be managed then if you have some way of make a sound analysis of the sound before it "enters" the ear, very much like the noise-cancelling headphone. So, do you think that in this situation could you emit some kind of sound that control the harmonics and cancel the fundamental frequency?
Comment: I accepted your answer, but I think others answers are good as well, such as ggcd and John answers. I think there is a lot of problems to consider such as the fundamental tracking phenomena of the @ggcg answer. But I think the air complexity and 3D waves are the first imperative problem to solve the problem of how to manipulate the music by changing the timbre of the sound. And I think you were the first one to point this problem. So I guess the answer is no at the first approach. But I have still a lot of doubts. I will try to study to have a better understanding of it, thanks.
Comment: Obviously, even in that case, getting rid of the fundamental tracking pointed by ggcg would be a non trivial challenge ;)
Answer: You seem to be asking more than one question, or convoluting several ideas together to create this scenario in your mind.  Almost everyone has offered an answer that addresses "cancellation", which would turn off the sound.  But you have stated...
"I think you could, given a sound source, to change a second sound source so that the sum of the two waves produces another fundamental frequency different of the first instrument, because you can cancel the fundamental frequency by the above process and just let the harmonics of the two sounds sources audible."
No, by the process of linear superposition you cannot do this.  You will not change the fundamental.  There are several problems with this line of reasoning.  Perhaps too many to address in one post.  But the one that really sticks out is a process in the brain called Fundamental Tracking.  By this process our brain takes the harmonic spectrum and get the fundamental from the mathematical pattern.  The brain "perceives" the fundamental even when it's missing.  The next thing that gets in the way of faking out a changed fundamental is that the ear is non-linear and creates Aural Harmonics.  So, as long as you have enough data present the ear will feed the brain what it needs to get the "true" fundamental.
That does not mean that faking out a fundamental is completely impossible.  If the listener is fed two notes that are very close together, close enough to not be distinguished, then they will hear or perceive the average of the two called a sum tone.  But they will also hear a beating.  This would not be perceived as a music idea and, for example, you cannot turn Einen Kleinen Nachtmusik into Whole Lotta' Love using this, or likely any, technique.
You are creating a scenario in which you generate music with NO particular timbre, either as sheet music or a a wave file.  In the latter case this theoretically impossible, then asking can one alter the wave to the point where they have not theoretically altered the music but changed to tune to something unrecognizable.  On its face this is not a well posed question.  And it is not possible without completely rewriting the music.  At that point it's not worth editing the waveform.
Comment: Very interesting answer! Thanks, I will try to learn more about this fundamental tracking effect. Yes, I put my question on a abstract timbre point of view because I wanted to understand better the relation between the waveform and its sound sources interference. Yes, there seems to have a point of inflection when a wave cannot be perceived as organized and perceived as some unrecognizable sound. But I don't understand why this make the question not well posed. I want to understand the limits of this in view of sound interference.
Comment: And also understand if what I am saying makes sense..
Answer: Your question pertains to physics. First of all, you mentioned using destructive interference to produce silence and backed your argument by the example of noise cancellation process in headphones. True but not always. In a 3D space, the sound waves are generated in all directions and in the form of longitudinal waves(in air) so this makes perfect noise cancellation impossible. Moreover, to achieve silence by this process, one needs to replicate the original waveform with a phase difference of exactly pi radians, which is also nearly impossible while performing the music. Furthermore, in a 3D space, sound waves are generated in all directions so to experience the effect of destructive interference, one has to be at a very specific point in space given that the waveform doesn't change. If it changes with time, the person has to be at specific points in space at specific points of time. This would be a rather tedious feat.
You asked if it would be possible to produce different frequencies by playing different instruments and combining their waves. I don't actually fully understand what you mean to ask. I mean if you're gonna play different instruments and combine their sounds to generate different frequencies (which is very very very difficult), why not play a single instrument at a different frequency? Well, you mentioned that you need to change a composition in a way that the composer couldn't blame anyone but physics. It is actually difficult to do. What can be done is that one can use different instruments to change the feel of the song, intercalate beat notes in the spaces between the original beat to craft an illusion of complex odd time signatures. For example,  vardavar by Tigran Hamasayan. You should listen to this song. It uses a 4/4 time signature which sounds nowhere near like a 4/4 but it is in fact a 4/4. Check out YouTube for it. By changing the instruments to change the feel of the song, manipulating rhythm section and doing stuff like that, one can easily make a composition sound entirely different than what it was intended to sound like and keep it pleasing to ears.
Manipulating complex waveforms is a lot difficult than manipulating simple sine waves. Short answer to your question, no. Long answer to your question, I think a simple no would suffice!
All this is what I deduced and if anything I have written is wrong, I'd appreciate rectification. What you have asked is rather interesting and I'd like to see it in action if possible.
Comment: Thanks, I loved to know Tigran Hamasayan music. I asked this on physics but I think they didn't understand what I mean there. My original intention was to understand this concepts of timbre and wave interference better. I am an amateur musician, with very poor physics knowledge, and in reality I have a more philosophical intention to research this subject: to know how much of the material condition of instruments and physics influenced our concept of music today. The question about universality. And sometimes I get carried away by these questions.
Comment: But if some musician tries to make some kind of musical experiment based on this I think this would be very interesting too, though now I understand it seems to be a very complicated to solve this air complexity problem.
Comment: @Lost definition it's good that you have a philosophical approach to matters which should be actually dealt philosophically. I mean it's not fully helpful to know anything when you don't actually ask questions about its significance and influence it has. You know what I mean. The timbre has a huge huge impact on music as we know it. I mean, play für elise on a ukulele, Latin rhythm, bonga drums, shakers and see what you get. Tell a Norwegian death metal band to cover it and you get something entirely different. So yes, change the instruments, change the music(a major aspect of music).
Comment: I'm happy that you asked this question. These kind of questions need to be asked and people don't even think about them.
Answer:
Can you change some composition I wrote to whatever music you want just by changing the timbre of the instruments?

If the arbitrary timbre for the instruments must be fixed over the performance of the music, then no.
For instance if you make a composition that consists of nothing but a single voice playing the same note, no choice of alternative timbre will turn it into a melody.
For similar reasons, a tune that starts and ends on the same note won't be turned into one that starts and ends on a different note and such.
Answer: You can do this on an ordinary PC or Mac these days. There is even some free software out there. You can manipulate and overlay waveforms to your heart's content. You can choose from accurate-sounding musical instruments and write a full orchestral score, then play it back - all on the computer.
You could easily make some of Mozart's early pieces sound like Baby Shark. Just pick the best part of the main melody and repeat it endlessly. Choose a ridiculous combination of instruments that sound suitably childish and, Bingo!
I'm almost tempted to do this myself now!
Answer: The difference between rock-and-roll and country music, say, isn't just the instruments; they also tend to use different chord progressions. You can't change the chord progressions just by changing the timbre.


Site broken with multiple errors

Question: I am trying to install a Drupal site locally on a new laptop that was working fine on the old one. I get the following errors.

Notice: Undefined offset: 2 in Drupal\Core\Database\Database::parseConnectionInfo() (line 215 of /var/www/html/docroot/core/lib/Drupal/Core/Database/Database.php)

Notice: Undefined index: driver in Drupal\Core\Database\Database::openConnection() (line 367 of /var/www/html/docroot/core/lib/Drupal/Core/Database/Database.php).

Drupal\Core\Database\DriverNotSpecifiedException: Driver not specified for this database connection: default in Drupal\Core\Database\Database::openConnection() (line 368 of /var/www/html/docroot/core/lib/Drupal/Core/Database/Database.php).

It's running inside Docker, PHP version is 7.3.27 and Drupal version 8.9.
Comment: I haven't voted either, but I guess the down-vote comes from a user who doesn't see any effort in looking for a solution, or doesn't think the question gives enough details. I answered the question because I think the causes can just be two: The settings.php file contains the wrong information, or a module tries to add a connection information passing a wrong array.
Comment: Can somebody explain why this question is getting downvoted? I'm not a backend or Drupal dev, apologies if the question is stupid, but I've been wrestling with this install for 3 weeks now and need help.
Comment: Haven't voted so just guessing - there's no information on how to reproduce the issue, and the errors are pretty generic. Abstractly it might be suggesting the database connection array is missing or incomplete, but it's hard to say
Answer: The notices and the exception are caused from the connection array not setting the driver property. In fact, Database::parseConnectionInfo() tries to access a numeric index of the array it gets with the following code.
// If there is no "driver" property, then we assume it's an array of
// possible connections for this target. Pick one at random. That allows
// us to have, for example, multiple replica servers.
if (empty($info['driver'])) {
  $info = $info[mt_rand(0, count($info) - 1)];
}

That code assumes that the array defining available connections is similar to the following one, in the case there are more connections for that target.
$databases['default']['replica'][] = [
  'database' => 'databasename1',
  'username' => 'sqlusername1',
  'password' => 'sqlpassword1',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => '',
  'collation' => 'utf8mb4_general_ci',
];
$databases['default']['replica'][] = [
  'database' => 'databasename2',
  'username' => 'sqlusername2',
  'password' => 'sqlpassword2',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => '',
  'collation' => 'utf8mb4_general_ci',
];

It cannot be the following one because the code is expecting the indexes for $databases['default']['replica'] to be between 0 and 1.
$databases['default']['replica'][3] = [
  'database' => 'databasename1',
  'username' => 'sqlusername1',
  'password' => 'sqlpassword1',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => '',
  'collation' => 'utf8mb4_general_ci',
];
$databases['default']['replica'][4] = [
  'database' => 'databasename2',
  'username' => 'sqlusername2',
  'password' => 'sqlpassword2',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => '',
  'collation' => 'utf8mb4_general_ci',
];

Basing on the first notice message, this seems the case: The array containing the connection information, which is contained in the settings.php file, or which is passed to Database::addConnectionInfo() from a module, doesn't contain all the necessary information, starting from the driver property, and contains the wrong information.
In the case the notices and the exception are caused from Drupal when it reads the connection information from the settings.php file, that file could be corrupted, which would explain why it works in a case, but not in the other one.
As for why the connection settings work in one case but not in the other one, assuming that the part of the settings.php file defining the available connections is the same in both the case, or that the settings.php file isn't corrupted, that could happen because:

The settings.php file used is different
A module is adding information for a new connection in one case, and it's using a malformed array

Where Drupal looks for the settings.php file is explained in default.settings.php, which explains that, for a https://www.drupal.org:8080/mysite/test/ site, Drupal will look into the following directories.

sites/8080.www.drupal.org.mysite.test
sites/www.drupal.org.mysite.test
sites/drupal.org.mysite.test
sites/org.mysite.test
sites/8080.www.drupal.org.mysite
sites/www.drupal.org.mysite
sites/drupal.org.mysite
sites/org.mysite
sites/8080.www.drupal.org
sites/www.drupal.org
sites/drupal.org
sites/org
sites/default

The default directory, sites/default is the last directory where Drupal searches the settings.php file. It's sufficient that another directory matching the domain name / port number is found that Drupal will use a different settings.php.
In the case the connection is added by a module, it could be that module is installed in one case, but not in the other one. Drupal looks for third-party modules in different directories, as described in Directory Structure. ([domain] means the domain name used to access the site.)

/modules
sites/[domain]/modules
sites/default/modules
Comment: Thanks for such a detailed answer. I'll work through it today and see how I get on. Appreciate you taking the time
Comment: This got me in a new and hopefully correct direction. I can now see that Docker isn't reading the env variables, of which driver is one. Thanks again.

Site broken with multiple errors


How to iterate through methods of instances to get a representation string

Question: I'm trying to make a pension tax calculator and have created a class "Client" that will accept inputs from two separate users and calculate their taxes based on these inputs.
Is there a cleaner way for me iterate through each client than to repeat this code?
client1 = Client.from_input()
print(client1.name, 'Maximum pension contribution you can make this tax year: ', client1.get_maximum_contribution())
print(client1.name, 'Maximum pension contribution your employer can make this year: ', client1.get_carryforward() + client1.get_remaining_aa())
print(client1.name, 'Remaining annual allowance: ', client1.get_remaining_aa())
print(client1.name, 'Carryforward available: ', client1.get_carryforward())

client2 = Client.from_input()

print(client2.name, 'Maximum pension contribution you can make this tax year: ', client2.get_maximum_contribution())
print(client2.name, 'Maximum pension contribution your employer can make this year: ', client2.get_carryforward() + client1.get_remaining_aa())
print(client2.name, 'Remaining annual allowance: ', client2.get_remaining_aa())
print(client2.name, 'Carryforward available: ', client2.get_carryforward())

If anybody wants the full code or if it's relevant:
```# import datetime
# currentyear = datetime.date.today().year
# year3 = (datetime.date.today().year - 3)
# year2 = datetime.date.today().year - 2
# year1 = datetime.date.today().year - 1
aathreshold = 240000
aallowance = 40000
maxaareduction = 36000

class Client:
    def __init__(self, name, salary, bonus, intdiv, employeepercent, employerpercent, pensionlump, salaryexchange,
                 deathbenefits, year3contribution, year2contribution, year1contribution):
        self.name = name
        self.salary = salary
        self.bonus = bonus
        self.intdiv = intdiv
        self.employeecontribution = salary * (employeepercent / 100)
        self.employercontribution = salary * (employerpercent / 100)
        self.pensionlump = pensionlump
        self.salaryexchange = salaryexchange
        self.deathbenefits = deathbenefits
        self.totalgross = salary + bonus + intdiv
        self.totalannualpensioncontributions = self.employeecontribution + self.employercontribution + self.pensionlump
        self.year3contribution = year3contribution
        self.year2contribution = year2contribution
        self.year1contribution = year1contribution

    @classmethod
    def from_input(cls):
        return cls(input('Name: '),
                   int(input('Salary + Bonus: ')),
                   int(input('Bonus & Comission: ')),
                   int(input('Interest & Dividends: ')),
                   int(input('Employee gross workplace contribution % : ')),
                   int(input('Employer gross workplace contribution % :')),
                   int(input('Lump sum contributions: ')),
                   int(input('Employment income given through salary exchange')),
                   int(input('Taxed lump sum death benefits: ')),
                   int(input('Please enter your pension contributions for 2018: ')),
                   int(input('Please enter your pension contributions for 2019: ')),
                   int(input('Please enter your pension contributions for 2020: '))
                   )

    def get_carryforward(self):
        def cap_carryforward(contribution):
            if contribution > aallowance:
                contribution = aallowance
                remaining_allowance = aallowance - contribution
                return remaining_allowance
            else:
                remaining_allowance = aallowance - contribution
                return remaining_allowance

        year3remallowance = cap_carryforward(self.year3contribution)
        year2remallowance = cap_carryforward(self.year2contribution)
        year1remallowance = cap_carryforward(self.year1contribution)
        cf_allowance = year3remallowance + year2remallowance + year1remallowance
        return cf_allowance

    def get_threshold(self):
        threshinc = self.totalgross - self.pensionlump - self.employeecontribution\
                    + self.salaryexchange - self.deathbenefits
        return threshinc

    def get_adjustedincome(self):
        adjustedinc = self.totalgross + self.employercontribution - self.deathbenefits
        return adjustedinc

    def get_remaining_aa(self):
        taperexcess = 0
        if Client.get_adjustedincome(self) > aathreshold:
            taperexcess = (Client.get_adjustedincome(self) - aathreshold) / 2
            if taperexcess > maxaareduction:
                taperexcess = maxaareduction
        annualallowance = aallowance - taperexcess
        remaining_aa = annualallowance - self.totalannualpensioncontributions
        if remaining_aa <= 0:
            remaining_aa = 0
        return remaining_aa

    def get_maximum_contribution(self):
        combinedallowance = (Client.get_remaining_aa(self) + Client.get_carryforward(self))
        if (self.salary - combinedallowance) <= 0:
            maxcontribution = self.salary
            return maxcontribution
        elif (self.salary - combinedallowance) > 0:
            maxcontribution = combinedallowance
            return maxcontribution

client1 = Client.from_input()
print(client1.name, 'Maximum pension contribution you can make this tax year: ', client1.get_maximum_contribution())
print(client1.name, 'Maximum pension contribution your employer can make this year: ', client1.get_carryforward() + client1.get_remaining_aa())
print(client1.name, 'Remaining annual allowance: ', client1.get_remaining_aa())
print(client1.name, 'Carryforward available: ', client1.get_carryforward())

client2 = Client.from_input()

print(client2.name, 'Maximum pension contribution you can make this tax year: ', client2.get_maximum_contribution())
print(client2.name, 'Maximum pension contribution your employer can make this year: ', client2.get_carryforward() + client1.get_remaining_aa())
print(client2.name, 'Remaining annual allowance: ', client2.get_remaining_aa())
print(client2.name, 'Carryforward available: ', client2.get_carryforward())

Comment: Do you want to iterate over instances of clients, or over the methods of a single instance, or both?
Answer: Yes, you can add a __str__ method to your Client-class to define how the string-representation of your objects should look like. E.g.:
import os
...
class Client:
    ...
    def __str__(self):
       line1 = f"{self.name} Maximum pension contribution you can make this tax year: {self.get_maximum_contribution()}"
       line2 = f"{self.name} Maximum pension contribution your employer can make this year:  {self.get_carryforward() + self.get_remaining_aa()}"
       line3 = f"{self.name} Remaining annual allowance:   {self.get_remaining_aa()}"
       line4 = f"{self.name} Carryforward available:   {self.get_carryforward()}"
       return os.linesep.join([line1,line2,line3,line4])

If you do that you can just do print(client1) in your code.
Alternatively, you can just name this method getstring and do it like this print(client1.getstring()).
If you want to iterate though your clients you can do it like this:
client_list = [Client.from_input() for _ in range(num_clients)]
for client in client_list:
    print(client)

To create a list of num_clients with your from_input method and print them all out.
Comment: Under circumstances such `__str__` could be quite confusing. Imagine an error message line "expected was a xxx, but got yyy" with this multiline message substituted.
Comment: This was exactly what I was looking for, thank you!

If I wanted to add significantly more lines of text to the object would I need to continue listing each line with os.linesep.join( [ ] ) or isthere a more efficient way?
Comment: Yeah you're right, edited it, so that the strings are joined afterwards.
Comment: If by efficiency you mean speed, I don't think that there's be any observable differences. In the end you'll want to limit the mount of calls to print, as those are slow(syscall) so you'll have to construct the full string at some point. Whether with string concat or or string-join shouldn't make a difference. If you mean using less lines, maybe you should post a new question where you generically ask for ideas to fulfill your use-case. One more concise method would be writing all this down in a config file for example but I cannot say how suitable that is for you without more info.
Answer: def print_info_for_clients(clients):
    for client in clients:
        print(client.name, 'Maximum pension contribution you can make this tax year: ', client.get_maximum_contribution())
        print(client.name, 'Maximum pension contribution your employer can make this year: ', client.get_carryforward() + client.get_remaining_aa())
        print(client.name, 'Remaining annual allowance: ', client.get_remaining_aa())
        print(client.name, 'Carryforward available: ', client.get_carryforward())

client1 = Client.from_input()
client2 = Client.from_input()
print_info_for_clients([client1, client2])

If you wanted to you could move the Client.from_input() into the function, and pass in a number of clients to read instead, but I prefer doing it this way because I can also assign client1 or client2 in any number of different ways if I want.
Comment: They already have a `Client`-class, implementing `__str__` or a `getstring` method makes much more sense imho.
Answer: A simple for might work depending on how many clients do you want:
def input_clients(how_many):
    clients = []
    for _ in range(how_many):
        client = Client.from_input()
        print(client.name, 'Maximum pension contribution you can make this tax year: ', client.get_maximum_contribution())
        print(client.name, 'Maximum pension contribution your employer can make this year: ', client.get_carryforward() + client.get_remaining_aa())
        print(client.name, 'Remaining annual allowance: ', client.get_remaining_aa())
        print(client.name, 'Carryforward available: ', client.get_carryforward())
        clients.append(client)
    return clients

input_clients(2)


Interdisciplinary Questions Law and Economics

Question: https://law.meta.stackexchange.com/questions/865/legal-theory-and-deference-of-a-corporate-law-question-de-lege-ferenda-to-https/866#866
Should I ask https://law.stackexchange.com/questions/43507/limited-liability-and-moral-hazard here? I was defered to money but I think Economics deal with Moral Hazard. While I do not think the capacity to answer the question lies in Economics.
Law as a discipline is inherently interdisciplinary.
Economics, Sociology, Politics, Philosophy, Language; Law it is a mix of all of them.
My question is de lege ferenda. I want an answer on why should the law stay as it is as opposed to a suggestion I made. What would be the disadvantages.
Answer: Hard to say, I find that the question is long and kind of rambling. If you can make it clearer and succinct, link to the necessary legal phrases and explain on what you mean by "should", e.g. what is your exact goal you might get an answer here.
Comment: Since it is the economics stack exchange and the question is interdisciplinary I would rather ask about positive economics here as opposed to normative economics and let normative part to law. Are you happy seeing a draft of the question? I am not going to post the one I posted in law. Since that one is normative. I am going to happen what happens in such a case.
Comment: Having read the comment I don't know what your question will be. Go ahead and post it, worst case scenario it gets closed. Please try to be very clear in your question.
Comment: https://economics.stackexchange.com/questions/30504/moral-hazard-bubbles-and-economies-of-scale-in-limited-companies-and-organizat


Transformar HTML em PDF

Question: Observei que no site do Banco do Brasil é possível escolher o formato de saída de um comprovante de pgto em txt, pdf, csv sem a necessidade de submeter novamente a página.
Existe alguma biblioteca que converta o html exibido na página em PDF sem a necessidade de novo submit e processamento da página?
O back-end será considerado o php ou node.
Comment: Pode ser `JQuery`? Pois se for com PHP, sem sair da página, é impossível (a menos `Ajax`)
Comment: Pode sim. Pensei em usar angular ou jquery. O que você sugere?
Comment: Gosto de JQuery (particularmente), respondi...acho que é perfeito pra você
Comment: Muito simples, eu estou usando esta API:
https://htmlparapdf.com.br/como-usar-api.cshtml
Comment: Olá, Já deu uma olhada no dompdf (https://github.com/dompdf/dompdf) ? Você pode capturar o documento e submeter a um php que faça a conversão.
Comment: Eu recomendo usar iText7 e pdfHTML (o mais recente do add-on para o iText7 que lida exatamente o seu caso de uso). Você pode encontrar mais explicação no nosso site em http://itextpdf.com/blog/pdfhtml-introduction
Answer: Você pode fazer isso usando jsPDF.
HTML

Olá, esta é uma tag H3

Um parágrafo.

<button id="btGerarPDF">gerar PDF</button>

JavaScript (JQuery)
var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#btGerarPDF').click(function () {
    doc.fromHTML($('#conteudo').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('exemplo-pdf.pdf');
});

JSFiddle
Comment: Ainda não cheguei a testar esta nova função, mas vi por base aqui: http://stackoverflow.com/questions/25946275/exporting-pdf-with-jspdf-not-rendering-css
Comment: ele so redenriza o html ou se colocar algum css ele transforma tbm ?
Comment: Infelizmnte não interpreta o CSS. Mas uma solução simples seria converter o HTML pra Canvas ([exemplo](http://html2canvas.hertzen.com/)) e ao invés de `pdf.fromHTML()`, usar `pdf.addHTML()`, exemplo: `pdf.addHTML($('#ElementoCanvasQueVoceQuerConverterParaPDF')[0], function () { pdf.save('Teste.pdf'); });`
Comment: Entendi, este metodo `addHTML()` parece ser novo  pelo que vi na documentação, você ja testou ? modifiquei o seu jsfiddle para  ele pra funcionar e apareceu que `pdf.addHTML não e uma função.`
Answer: Eu já faço uso do Headless Browser PhantomJS para download de páginas WEB Completas renderizadas de forma FIEL a exibida no browser comum (ele interpreta o JS e CSS) mas com ele tambem é possivel realizar um print screen da página desejada da sequinte forma:

Crie um arquivo com extensão .js
Cole e salve o seguinte conteúdo:

Comando que acessa uma determinada página e salva o conteúdo da mesma em um .png (mas pode salvar como PDF):
var page = require('webpage').create();
page.open('http://stackoverflow.com/', function() {
  page.render('stackoverflow.png');
  phantom.exit();
});

chame-o da seguinte foma na linha de comandos: nome do programa (caso ele tenha sido inserido no path) mais npath do arquivo javascript criado no item acima ficando da seguinte forma:
phantomjs teste.js

Com ele tambem é possivel estabelecer as dimensões da janela onde o site é exibido (isto é util caso queira ver como está sendo renderizado um site responsivo) da seguinte forma (esta configuração deve ser feita antes do page.open()):
var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = {
  width: 480,
  height: 800
};

Você pode chama-lo usando o comando shell_exec desta forma:
    $pathToPhantomJS = 'C:\phantomjs-2.0.0-windows\bin\phantomjs';
    $pathToJSScript = 'GetPage.js';
    $comand = $pathToPhantomJS . ' ' . $pathToJSScript . ' ' . $site;
    shell_exec($comand);

Obs: passo uma terceira variavel que representa o site a ter sua pagina printada o site é pego pelo vetor de args que são passados para o shell.
É possivel criar um CRON JOB para executar o comando phantomjs teste.js em determinado horário.
O PhantomJS me foi muito util e é muito configuravel e não conseguiria descrever todas a possibilidades aqui então estou colando alguns links Oficial e não Oficias que poderão ser uteis:
Download
Link: http://phantomjs.org/download.html
Documentação
Screen Capture: Link
viewportSize: Link
shell_exec (PHP): Link
Answer: 1º Faça gerar o pdf por uma instancia de AJAX, no Jquery para ser mais rápido.
2º Execute uma url com o retorno do ajax, contendo o nome do arquivo, em outro
arquivo php o qual ira forçar o download. Desta forma vai ter seu pdf gerado
sem reflesh:

Para gerar o PDF mais rápido recomendo a biblioteca:
http://html2pdf.fr/en/example.
A mesma basta passar o HTML em uma variavel que ele gera o PDF.
O codigo do PHP do download abaixo:
<?php

$file_url = $_GET['file'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);

?>

Comment: **Colocar dentro da a sua função passando os paramentos o JavaScript/Jquery do meu código.**
Answer: Segue código em JS usando a API Html Para PDF:
// Code DEMO here
var settings = {
    "url": "//v1/Consultar?user=<string>&key=<string>&ArquivoID=<string>",
    "method": "GET",
    "timeout": 0,
};

$.ajax(settings).done(function (response) {
    console.log(response);
});

Transformar HTML em PDF


Alternative characterization of exterior algebra

Question: Throughout literature, the exterior algebra $\Lambda(V)$ over an $n$-dimensional $\mathbb{K}$-vector space $V$ is introduced as being the quotient $T(V)/I$ of the tensor algebra $T(V)$ by the ideal $I$ generated by elements of the form $x \otimes x$.
In this presentation, instead, a subset $\mathcal{D}$ is defined comprising linear combinations of elements $v_1 \otimes \cdots \otimes v_k$ such that $v_1, \ldots, v_k$ are linearly dependent. It is stated that $\mathcal{D}$ is clearly an ideal, $\Lambda(V)$ is defined as the quotient $T(V)/\mathcal{D}$.
Are these two formulations equivalent?
Answer: Yes, $I = D$. We clearly have $I \subseteq D$ and the usual proof that exterior products of linearly dependent vectors vanish in the exterior algebra proves that $D \subseteq I$. This construction is just being more explicit about what the ideal generated by elements of the form $x \otimes x$ actually looks like.
Comment: I'm still confused how elements of $D$ can be put into the form of linear combinations of $x \otimes x$.
Comment: @user: are you familiar with the proof that exterior products of linearly dependent vectors vanish in the exterior algebra? Write that proof down, but every time you use the fact that $v \wedge v = 0$ to conclude that two elements $a, b$ in the exterior algebra are equal, instead write out explicitly what the difference $a - b$ is, in terms of $v \otimes v$.
Comment: As a simple example, suppose $v_1, v_2, v_3$ are linearly dependent, and that (after possibly reindexing if necessary) $v_1, _2$ are linearly independent. This means $v_3 = av_1 + bv_2$ for some $a, b$, so $v_1 \otimes v_2 \otimes v_3 = v_1 \otimes v_2 \otimes (av_1) + v_1 \otimes v_2 \otimes (bv_2)$. The second term is $bv_1$ times $v_2 \otimes v_2$ so that's why it lies in $I$. The first term requires a bit more work; the way we'd prove that $v_1 \wedge v_2 \wedge (av_1) = 0$ in the exterior algebra involves commuting $v_1$ and $v_2$, so we need to write...
Comment: ...$v_1 \otimes v_2 = v_2 \otimes v_1 + [v_1, v_2]$ (where $[v_1, v_2]$ denotes the commutator) and so $v_1 \otimes v_2 \otimes (av_1) = av_2 \otimes (v_1 \otimes v_1) + [v_1 v_2] \otimes av_1$. The first term is $av_2$ times $(v_1 \otimes v_1)$ so that's why it lies in $I$. Now we need to know why $[v_1, v_2] \in I$. For this we reproduce the proof that alternating implies antisymmetric; explicitly, we have $(v_1 + v_2) \otimes (v_1 + v_2) \in I$ and $(v_1 - v_2) \otimes (v_1 - v_2) \in I$ and then we subtract them and divide by $2$.
Comment: Thank you so much!
Comment: Whoops, that last bit's not quite right, we instead use $(v_1 + v_2) \otimes (v_1 + v_2) \in I$ and then $v_1 \otimes v_1 \in I, v_2 \otimes v_2 \in I$, and we need $[v_1, v_2]$ to be the anticommutator instead, which changes a few signs.


how to play this part of right hand in the image shown? i have no idea how to go about this "two part with one hand"

Question:
Hello I have a question. I don't know how to play this part of right hand shown in the image. I would really appreciate some advice on the fingering.
This music is "a letter - by Yukie Nishimura". I am a beginner (late beginner maybe), and self-taught, though I have previously played the violin.
Answer: 1-2-4, 3, 4, 5, 2-3  perhaps?  A touch of pedal will smooth it out.
Comment: thank you! i tried it now and it is okay. i was going with 1-2-5, because i thought there's no way "4" could do it. but it seems i was not stretching enough since i had no idea how much to stretch (this is my first piece that requires stretching the fingers), and with 1-2-5 i felt it was weird since there was no finger left to play the high Eb so i had to use the 5th again. thank you again sir!
Comment: @vechivara "I had no idea how much to stretch " - a normal size adult hand should be able to play an octave easily with 1-4 as well as 1-5. Octaves fingered 1-4 are easier on the black keys, because there is less chance of accidentally pressing another key at the same time.
Comment: I have to admit I'd probably take the lazy way out, play the first chord 1-2-5 then, with the help of the pedal, hook 4 over for the Eb  :-)
Comment: You could also try 1-2-5 ,3 ,4, 5
Comment: Playing the F#&A with 2&3 is going to be very uncomfortable.


Background colour won't work. I'm trying to add a background for my page breadcrumbs

Question: I'm trying to add my website breadcrumbs to a list and change the list background to #0765de, i have tried as seen below, only the
 background will change colour.
I have to change the width of li so the text is in the page so the background cuts off. that's why I need it in ul.
Heres the HTML:

{ include'breadcrumb' }

Heres the CSS:
.breadcrumb_unli ul {
width: 100%;
overflow: hidden;
background-color: #0765de;
}

.breadcrumb_unli li {
width: 60%;
color: white;
margin: auto;
margin-top: -30px;
padding: 10px 10px 10px 0px;
}

Any help would be appreciated.
Comment: it should be `ul.breadcrumb_unli` not `.breadcrumb_unli ul` for your css selector. "breadcrumb_unli" is your ul
Comment: does your breadcrumb have an `` tag nested inside the ``? If so, try `ul li a { color: white; }`
Answer: to select a ul with a specific class you should do this:
ul.breadcrumb_unli {
      width: 100%;
      overflow: hidden;
      background-color: #0765de;
}

if it didn't work, try adding display: block or display: inline-block to the ul
Comment: Hi, I'm using liquid (Shopify) this is how you select in this I believe


MariaDB fails to start after reboot - can start it manually

Question: I have a VPS running Centos7 with MariaDB. I am having issues trying to get it to start MariaDB on boot, I am binding MariaDB to my VPS's private address as I only want it to listen to connections on that interface. It fails with this in the logs:
170204 15:34:03 mysqld_safe mysqld from pid file /var/run/mariadb/mariadb.pid ended
170204 15:34:12 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
170204 15:34:13 [Note] /usr/libexec/mysqld (mysqld 5.5.52-MariaDB) starting as process 784 ...
170204 15:34:13 InnoDB: The InnoDB memory heap is disabled
170204 15:34:13 InnoDB: Mutexes and rw_locks use GCC atomic builtins
170204 15:34:13 InnoDB: Compressed tables use zlib 1.2.7
170204 15:34:13 InnoDB: Using Linux native AIO
170204 15:34:13 InnoDB: Initializing buffer pool, size = 128.0M
170204 15:34:13 InnoDB: Completed initialization of buffer pool
170204 15:34:13 InnoDB: highest supported file format is Barracuda.
170204 15:34:13  InnoDB: Waiting for the background threads to start
170204 15:34:14 Percona XtraDB (http://www.percona.com) 5.5.49-MariaDB-38.0 started; log sequence number 1597945
170204 15:34:14 [Note] Plugin 'FEEDBACK' is disabled.
170204 15:34:14 [Note] Server socket created on IP: '10.99.0.14'.
170204 15:34:14 [ERROR] Can't start server: Bind on TCP/IP port. Got error: 99: Cannot assign requested address
170204 15:34:14 [ERROR] Do you already have another mysqld server running on port: 3306 ?
170204 15:34:14 [ERROR] Aborting

170204 15:34:14  InnoDB: Starting shutdown...
170204 15:34:15  InnoDB: Shutdown completed; log sequence number 1597945
170204 15:34:15 [Note] /usr/libexec/mysqld: Shutdown complete

However, I am able to start the service manually by running sudo systemctl start mariadb which produces:
170204 15:34:15 mysqld_safe mysqld from pid file /var/run/mariadb/mariadb.pid ended
170204 15:38:52 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
170204 15:38:52 [Note] /usr/libexec/mysqld (mysqld 5.5.52-MariaDB) starting as process 2609 ...
170204 15:38:52 InnoDB: The InnoDB memory heap is disabled
170204 15:38:52 InnoDB: Mutexes and rw_locks use GCC atomic builtins
170204 15:38:52 InnoDB: Compressed tables use zlib 1.2.7
170204 15:38:52 InnoDB: Using Linux native AIO
170204 15:38:52 InnoDB: Initializing buffer pool, size = 128.0M
170204 15:38:52 InnoDB: Completed initialization of buffer pool
170204 15:38:52 InnoDB: highest supported file format is Barracuda.
170204 15:38:52  InnoDB: Waiting for the background threads to start
170204 15:38:53 Percona XtraDB (http://www.percona.com) 5.5.49-MariaDB-38.0 started; log sequence number 1597945
170204 15:38:53 [Note] Plugin 'FEEDBACK' is disabled.
170204 15:38:53 [Note] Server socket created on IP: '10.99.0.14'.
170204 15:38:53 [Note] Event Scheduler: Loaded 0 events
170204 15:38:53 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.5.52-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server

My my.cnf:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd

bind-address    = 10.99.0.14

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

I temporarily disabled SELinux to see if this was the issue, however it didn't seem to fix the issue. It works fine when I bind to 0.0.0.0 but I don't particularly want to do that. Thanks in advance.
Answer: I ended up fixing this by adding network-online.target to the /usr/lib/systemd/system/mariadb.service file, under the unit directive:
[Unit]
Description=MariaDB database server
After=syslog.target
After=network-online.target

Originally, it was set to network.target.
Basically the eth1 interface wasn't getting an IP address fast enough, causing MariaDB to complain on boot.
Thanks @nickm
Answer: In my case what it took after an upgrade from 5.5.68-MariaDB to 10.5.8 was just this (note: drupal running with mariadb on RHEL7):
sudo systemctl enable mariadb

I hope this will help someone else
Answer: This happened because your MariaDB configuration sets a bind-address to an IP address which is not on any interface when MariaDB starts.
bind-address    = 10.99.0.14

You can resolve this by not binding to any specific address; MariaDB will then answer on any interface or IP address, even those not present when it started. Do so by removing all instances of bind-address = from your configuration.
(You can also resolve it by having systemd wait to start MariaDB until the IP address is available, as shown in another answer.)


How to repeat events with the calendar module?

Question: I have installed the calendar module. I create a content type call Events and I added a Date field using the Pop-up Calendar control type. So when I create a event node I'm able to give it a Date. So far so good.
Now I need to have something like "repeat every day", "repeat every month", "repeat every year".
Can I accomplish this with the calendar module? Do I need to install another module?
thanks
Answer: Check that Date repeat API is checked on your module listing page


Como resetar um menu de seleção (selectmenu) ao alterar outro campo usando uma função?

Question: Estou tentando fazer com que um "menu de seleção" (selectmenu) seja resetado quando insiro um valor a mão em um campo de texto, porém apesar de já ter tentado inúmeras solução que pesquisei aqui mesmo no Stack Overflow e em outros sites, nenhuma funcionou.
Segue abaixo o meu código HTML:

 Selecione Um Prazo Padrão:

  <select name="menuPrazo" id="menuPrazo" class="menuPrazo">
    <option value="*" selected="selected">Escolha um Tipo de Prazo</option>
    <option value="1">A Vista</option>
    <option value="30">Prazo Normal</option>
    <option value="15">Prazo Estendido</option>
</select>

Ou Informe Um Prazo Personalizado:

<input type="text" name="prazoManual" id="prazoManual" class="prazoManual" value=""></input>

Abaixo o código em JavaScript:
$(".menuPrazo").on("change", function () {
    $("#prazoManual").val("");
});

$(".prazoManual").on("change", function () {
  $('#menuPrazo').prop('selectedIndex',0);
});

Além da opção contida no código acima, já tentei as seguintes opções:
$("select#menuPrazo").selectmenu("index", 0);

ou
$("#menuPrazo").val("");

ou
$("#menuPrazo").refresh();

JSFiddle
Answer: Você esqueceu o ".change()" ao alterar
    $("#prazoManual").on("change", function () {
      $('#menuPrazo').val('*').change();
    });

Comment: Solução perfeita! A princípio não funcionou no meu código, apesar de ter funcionado corretamente no JSFiddle. Depois de muito quebrar a cabeça descobri que a razão de não funcionar era a ordem de carregamento das bibliotecas "Jquery", "Jquery UI" e "Jquery Mobile". Ao trocar a ordem de carregamento para essa ordem que citei, tudo funcionou corretamente.
Answer: Com o evento change em ambos fica assim:

 Selecione Um Prazo Padrão:

  <select name="menuPrazo" id="menuPrazo" class="menuPrazo">
    <option value="*" selected="selected">Escolha um Tipo de Prazo</option>
    <option value="1">A Vista</option>
    <option value="30">Prazo Normal</option>
    <option value="15">Prazo Estendido</option>
</select>

Ou Informe Um Prazo Personalizado:

<input type="text" name="prazoManual" id="prazoManual" class="prazoManual" value=""></input>

claro que o correto é criar um botao para "resetar" e neste botao você implementa o evento click em fez desses seus change ai.
Comment: Tentei implementar a sua sugestão, mas não está funcionando ( http://jsfiddle.net/qete9dp6/4/ ). Alguma outra ideia?
Comment: @DanielSilva não estou conseguindo abrir o site do jsfiddle, mas testei com html que tu me passou e funcionou, só precisei colocar uma tag a mais referente ao jQuery, vou editar minha resposta e postar tudo


How can I make sure ajax/jquery calls finish before an html page loads?

Question: $(function() {
    var $items = $('#items');
    $.ajax({
      type: "GET",
      url: 'some-url',
      data: {},
      success: function(items) {
        $.each(items, function(i, item){
          item_polys.push(item.polygon);
          $items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
        });
        localStorage.setItem('item_polys', JSON.stringify(item_polys));
      },
      // Error handling
      error: function (error) {
          console.log(`Error ${error}`);
      },
});

I need 'item_polys' to be saved into local storage before my corresponding html page loads. I would also settle for a way to reload the html page just one time each time after it loads, so that it will populate correctly. Thanks (and sorry if this has been answered already, I couldn't quite find what I was looking for when I searched)
Answer: Since you want the ajax request to occur when the user is on the exact same page that the populated elements will be in, I think the only good way of doing this would be to create or display the elements of the page dynamically. (This might be as simple as toggling a display: none on and off, but it depends on what the page is like and what you want.)
So, make a function like populatePage that shows the page, where the default state of the page is a loading screen (or blank, or whatever you want the user to see when the request is in progress). Maybe something like
const populatePage = () => {
  const items = JSON.parse(localStorage.items);
  for (const item of items) {
    $items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
  }
  $('main').show();
};

where main is the container you want to show when things are ready, and that has styling that hides it by default. Then:
On pageload, check if the item exists in storage. If so, use it, and call populatePage immediately. Otherwise, have the page keep showing the loading banner or blank screen, make the ajax request, and call populatePage when it's finished.
$.ajax({
  // ...
  success: function (items) {
    localStorage.items = JSON.stringify(items);
    populatePage();

Comment: Thank you very much, this helped me a lot was searching just like this.
Comment: Thanks, I will try this as soon as I can. Drop a couple upvotes if you can, I am only 2 away from enough rep to vote. I will upvote back when I make it


Não consigo redirecionar com PHP usando o header()

Question: Galera preciso de ajuda, sou iniciante e fiz o script abaixo onde recebo dados de um formulário, salvo em um arquivo csv, e depois libero o download de um pdf, no entanto, no final do script, eu queria dar um header() para a index para apagar os dados do formulário, porém não estou conseguindo de forma alguma redirecionar, o pdf já baixa automaticamente, mas não redireciona.
Comment: Olá jande, poderia postar seu código invés da imagem?
Comment: Seja bem-vindo ao SOpt, Jande. O que aparece na tela? Há alguma mensagem? É sempre ideal usar somente texto ao mandar algum código ao invés de imagem com código, pois, ao mandar imagem, dificulta nos testes aqui.
Comment: Não relacionado à pergunta, mas se vc tem `if(...) { faz_coisas; faz_A; } else { faz_A; }`, vc só precisa de `if(...) { faz_coisas; } faz_A;`
Comment: @tvdias ajustei a resposta, acho que esta boa agora, aonde você acha que ela esta ruim exatamente para justificar o seu downvote
Answer: O problema todo é que você não entende HTTP ainda, eu vou falar algo, a maioria diz entender HTTP, acha que estudando um dia ou dois domina isso, mas é pura ilusão, é necessário entender o que é TCP e, depois, entender o que é HTTP.
Você está esperando um comportamento do servidor como se estivesse correndo no computador do usuário, mas não está, porque o script está no servidor, isso não é um comando:
header('Location: index.php');

E nem nenhum outro header é um comando no PHP, são todos instruções, que serão baixadas e processadas pelo programa do lado cliente ou pelo SAPI (Server Application Programming Interface, neste caso são algumas instruções especiais como o X-Send citado pelo colega @Bacco que só correm do lado servidor comunicando um script com um módulo do servidor, mas isto é outra história), sejam eles:

navegadores
programas como curl, de comando de linha
Web Crawlers (Spider ou Bot)

Entendendo um pouco do HTTP
Eu já vou adiantar, não adianta sair daqui achando que aprendeu, ou que vai dominar isso de verdade, a maioria não domina, só se ilude e leva tempo para entender sim, ainda mais se não entende o básico e TCP, mas sim dá pra explicar o HTTP sem me aprofundar muito no TCP, a explicação mais simples, mas que não vai tornar ninguém em especialista é, quando você faz qualquer requisição HTTP o programa cliente, como navegadores irá enviar uma instrução para o servidor, algo como:
GET /pasta/arquivo.php HTTP/1.1
Host: www.site.com
Accept: image/gif, image/jpeg, */*
Accept-Language: en-us
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
(linha em branco)

O (linha em branco) é uma linha vazia, deve ir depois dos headers, em GET é "indiferente", geralmente os servidores tratam isso, mas em POST, PUT e PATCH quando contêm payload (informação de um formulário por exmeplo).
Então o navegador envia isto tudo puramente COMO TEXTO, subindo completamente o SERVIDOR vai processar e entender a instrução e irá agora enviar um download, sim um download, tudo em HTTP é download, então isto vai sendo baixado e só é processado pelo front-end quando algumas partes vão estar sendo reajustados, exemplo (só coloquei um pedaço, porque um PDF seria grande)
HTTP/1.1 200 OK
Date: Sun, 06 Feb 2020 23:15:53 GMT
Last-Modified: Thu, 06 Feb 2020 15:24:18 GMT
Content-Length: 1048576
Connection: close
Content-Type: application/octet-stream
Content-Disposition: attachment; filename='arquivo.pdf'
Location: index.php

%PDF-1.7

4 0 obj
...

Então o navegador irá interpretar os headers, como existe o header:
Content-Type: application/octet-stream

ou o:
Content-Disposition: attachment

Faz com que o navegador CANCELE a requisição (em navegadores), sim ele cancela e direciona para o gerenciador de downloads, claro que isso depende do motor e de como ele funciona gerencia o download, então a resposta HTTP deixa de ser controlada pela aba/janela que solicitou e passa a ser controlado pelo gerenciador de downloads, o gerenciador não faz parte do motor de renderização
O gerenciador de download pode vir embutido no navegador e não quer dizer que faça parte dele "completamente", mas claro que ele processa a mesma sessão que estava na aba/janela e você pode observar que no momento que o download inicia o "gerenciador" a requisição HTTP está marcada como cancelada no "navegador", você pode observar isto no console (DevTools por exemplo) na aba rede.
Para resumir como as headers são tratadas depende de onde é executado, em XmlHttpRequest o comportamento/tratamento dos headers recebidos é outro e dependendo do cliente como curl (comando de linha) isto também pode variar, ou seja cada tipo de local pode tratar os headers de forma diferente, podendo ser por ordem ou até por prioridade definida pelo programa cliente.
Não é possível redirecionar após um download
Resumindo, não é o PHP que faz o redirecionamento, quem faz é quem vai interpretar os headers e também não é possível direcionar após um download começar porque geralmente gerenciadores de download necessitam cancelar em uma instância (navegador) para que eles possam controlar a requisição
O unico meio de contornar isto seria fazendo talvez via JavaScript e no front-end, fazendo o download e o redirecionamento serem janelas diferentes, um exemplo superficial (afinal não tenho como saber exatamente como esta o seu sistema, basta ajustar a sua necessidade):
//Arquivo hipotético
$arquivo = '../foo/bar.csv';
?>

<?php
} else {
    header('Location: index.php');
}

Comment: Parabéns pela resposta @GuilhermeNascimento bem elaborada e esclarecedora!
Comment: Sim, sempre depende. TB sou recente no SOpt e "aprendendo" como ele funciona. Por sinal, já cometi inúmeras gafes... rs Estou tentando participar bastante, trocar idéias, etc. Quero ver até quando vou conseguir manter o ritmo!
Comment: Porque o negativo? Quem negativou discorda que HTTP funcione assim? Ou acredita que HTTP e TCP é fácil de entender?
Comment: @tvdias tem muitas formas de resolver no front-end, mas depende do conhecimento do usuário que pergunta, no geral eu nem devia ter dado sugestão, porque isso é especifico pode ser que em um ambiente especifico não dê para implementar assim, se as pessoas se preocupassem em aprender o minimo do que é web, e web é HTTP, então saberiam como contornar para cada situação problemas assim, mas como as pessoas aprendem errado é necessário explicar o que é HTTP e esperar que a pessoa modifique/adapte o que fez a sua própria necessidade, o que foi q tentei ensinar.
Comment: Só adicionei o exemplo pra tentar ajudar, mas é como disse não servirá para todos casos, a parte importante é entender como HTTP funciona e então ajustar e até ver uma estratégia melhor, que pode ser a que apresentei ou a que você apresentou, ou até uma série de outras que só vendo o sistema completo dele poderiamos saber.
Comment: @tvdias sim, mas ai esta o problema, o download é forçado via PHP, ele poderia forçar com .htaccess+mod_headers (recursos do Apache) e resolver o resto todo no front-end de forma simples, ele pode ter escolhido o FORM, mas foi decisão dele, nem significa que é a melhor estratégia, é mais provável q ele escolheu pq não sabe bem os princípios básicos, esse é o tipo de pergunta problematica que se enquadra em um dos fechamento off-topic, mas respondi pq fiquei com dó dele não entender HTTP... PS: Que outra pergunta (isto: apesar de ter sido questionado em outra pergunta por fazer isso)?
Comment: @tvdias acho que depende, tem que analisar caso a caso, aqui o problema justamente era o entendimento falho do autor que precisava ser orientado e talvez no que você respondeu pode ser outra coisa totalmente diferente, mas só eu vendo o link pra ter certeza.
Comment: @tvdias Excelente! Isso mesmo, sempre procure a pró-atividade e sempre buscar dicas. Boa sorte e se quiser trocar alguma ideia é bem vindo no chat do site https://chat.stackexchange.com/rooms/11910/estouro-de-pilha
Answer: Pela imagem, notei que você faz o uso do readfile, esse método lê um arquivo e escreve o seu conteúdo para o buffer de saída (output buffer).
Via regra, você não pode enviar um cabeçalho depois que iniciou a transmissão do conteúdo (que é o que o readfile está fazendo).
Imagino que você esteja tentando fazer o download de um arquivo, provavelmente com um target='_blank' no seu php, e por isso está tentando fazer o redirect com o header.
Quando você retornar um header application/octet-stream o próprio browser irá iniciar o download, então acredito que você pode chamar o seu download diretamente da página home, remover esse header("Location: home.php"); e o comportamento será o esperado.
Caso não seja esse seu cenário, atualize sua pergunta com mais detalhes, que complemento a resposta.
Comment: Faltou responder como limpar o formulário ao fazer o download...


Can't access class methods from JavaScript when trying scripting

Question: I'm trying to test out JavaScript through Java using simple Nashorn examples, and I'm just not understanding why I can't access a method of my own class from a JS call.
First, the class I want to work with:
package myPackage;

public class myClass
{
    Object internalObj;

    static boolean test()
    {
        return true;
    }

    boolean storeObject(Object obj)
    {
        internalObj = obj;
        return true;
    }

    String whatObjectType()
    {
        return internalObj.getClass().toString();
    }

}

Then, the code that is to provide scripting calls:
package myPackage;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class myTester
{
    public static void main( String[] args )
    {
        System.out.println(">> Script Testing");

        //test out my class
        System.out.println(myClass.test());

        myClass myObj = new myClass();

        myObj.storeObject("test");

        System.out.println(myObj.whatObjectType());

        //now try the same from javascript
        ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");

        String myScript ="var myJSClass = Java.type('myPackage.myClass');"
                + "var myJSObj = new myJSClass();"
                + "print(myJSObj.test());";

        try
        {
            js.eval(myScript);
        } catch (ScriptException e)
        {
            e.printStackTrace();
        }
    }
}

Everything is well and good until the evaluation of myJSObj.test(), which craps out. Here's the output:
>> Script Testing
true
class java.lang.String
javax.script.ScriptException: TypeError: myJSObj.test is not a function in <eval> at line number 1

Most of the Nashorn intro material shows similar examples, except they all work. What am I doing wrong?
Comment: I should note that replacing the call to method test() with a non-static method call results in the same error.
Answer: There are two problems:

You're trying to call a non-public method from outside the package (your JavaScript code isn't in myPackage). test will need to be public in order for you to call it.
You're making the call on an instance of your class, not on the class itself, but test is static. Java allows calling static methods through instance references (it's one of the quirkier things about Java), but JavaScript doesn't have that concept. You'll need to make test an instance method, or call it on myJSClass instead.

Fix those, and it works. :-)
Comment: 1) Worked perfectly, thank you. I just assumed something being called from within a package would have some sort of operational context for the package itself. Curious, is there a way to include a particular script within the package? Might be useful. 2) I did not know this, thanks again.
Comment: @Diego: No worries. I doubt it's possible to put the JavaScript code in a package, not least because JavaScript isn't class-based (even when using ES2015's `class` syntax), and you can happily copy a "method" from one JavaScript "class" to another. But I don't know that for sure, they may have come up with some clever way of supporting it.


Display suite fields visibility restriction

Question: Is there a way in DS fields visibility restriction with url pattern?
Answer: Yes. You can create a custom view mode with DS, add or remove fields as you wish, configure that view mode to use a DS layout, then access the view mode through a URL.
The structure looks like this for the "full" view mode: node/x?v=full.
You need to enable a DS Extra setting called "View mode per node" at admin/structure/ds/list/extras


Drupal Commerce Title length

Question: I'm facing a problem with commerce product title length. I want to increase the lenght over 255. What I've tried so far is:

Change DB field from varchar to text
Change the maxlength of the form field
Change the formfield to a textarea

Any of the form changes lead to an error. Any idea how to increase the length?
Answer: I wouldn't increase the length of the field, but instead ask yourself why you are storing so much information in the title. There is a very good chance you simply need to split the information out into different fields or use a textarea to store ancillary information. You don't know how many assumptions commerce makes about the title field with regards to logic and formatting and the general Commerce wisdom is to not mess with the internals.
Comment: My problem is, that I can't decide that. A customer said he needs more than 255 characters in the title and so I have to give him what he wants. I know that messing with the core isn't a good idea, but I really have to. Maybe I could hide the title field, create a new textfield, and copy 255 characters from that to the title.
Comment: It sounds like the issue lies more with your client. What are some examples of titles the client is creating? Can any of that information be stored in a more semantic field? What is the reasoning behind using the title? Titles to me are meant to be a very concise summary of what is being purchased and when you step outside of that concept, you are probably breaking commerce in other areas.
Comment: They do store to much information in the title which could easily be split up, but as they had a system with one gigantic title field before the new one, they just want it the same way. I tried my best to convince them to split up, but there seems to be no chance that they'll do that.
Comment: I would explain the benefits of storing things correctly, that is: searchability, filtering, reporting, future-proofing, design, semantic HTML, rich snippets and validation to name a few. Beyond that, you need to question why a client wouldn't take your recommendation on something which is probably easier than what they are used to and consider not working with the client.

If ease of use is the issue, perhaps tools could be developed to take their long string input and transform it into various fields with semantic meaning.
Answer: Sam's answer and comments should be taken as the best advice for this, but as a technical exercise it shouldn't be too difficult:
<code>// Alter the schema
function MYMODULE_schema_alter(&$schema) {
  $schema['commerce_product']['fields']['title']['length'] = 512;
  $schema['commerce_product_revision']['fields']['title']['length'] = 512;
}

// Change the DB in an update hook
function MYMODULE_update_7100() {
  $schema = drupal_get_schema_unprocessed('commerce_product');

  $new_field = array('length' => 512) + $schema['commerce_product']['fields']['title'];
  db_change_field('commerce_product', 'title', 'title', $new_field);

  $new_field = array('length' => 512) + $schema['commerce_product_revision']['fields']['title'];
  db_change_field('commerce_product_revision', 'title', 'title', $new_field);
}

// Change the form
function MYMODULE_form_commerce_product_product_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#maxlength'] = 512;
}
</code>
Completely untested, use with caution.

Drupal Commerce Title length


If $U$ is uniformly distributed on $S^{2}$, then its first component is uniformly distributed on $(-1,1)$.

Question: Assume $\mathbf{U} = (U_{1}, U_{2}, U_{3})' \sim unif(S^{2})$. How would I show that $U_{1} \sim unif(-1,1)$?
I don't know if I'm confusing myself, because I can't see this as being true for higher dimensions.
Comment: There is a well known and classical theorem that says that projection from a sphere to a cylinder is area preserving.  This fact plus the rotational symmetry of the situation implies what you want.
Comment: I don't see how the claim could be true:  the surface area of the subset of $\boldsymbol U$ such that $0 \le U_1 < 1/2$ is clearly larger than the subset corresponding to $1/2 \le U_1 < 1$.
Comment: @LearningMath Nope, it is special for dimension 2.  For a 1 dimensional sphere, projecting the uniform measure onto one of the axes concentrates a bit toward the poles.  As the dimension increases, a larger and larger percentage of the mass becomes concentrated on the equator and in fact for large enough dimension, 99% of the surface of a unit sphere is within .001 of the equator.
Comment: @Nate The theorem is true for spheres of all dimensions, not just $2,$ right?
Comment: @Nate Sorry, I think I made a mistake in my asking my question to you. Yes, I'm aware of the concentration of measure near the equator, but my question was: is the orthogonal projection of the uniform distribution on any dimensional sphere is uniform on $(-1,1),$ right?  If not, what is it?
Comment: @LearningMath I am confused as to the difference between what you are asking now and what I was addressing in my previous comment.  The answer is no,  the projection of the uniform distribution on $S^n$ to $(-1,1)$ is not uniform unless $n=2$.
Answer: Relating to the comment of Nate, there's also the "well known" formula for the area of a surface of revolution, namely if $f:[a,b]\rightarrow \mathbb R$ is smooth and positive, we can rotate its graph $\Gamma_f = \{(x,y)\ |\ x \in [a,b],\ y = f(x)\}$ around the $x$-axis and obtain a surface $\Sigma$. The area of that surface is
$$
\mathrm{Area}(\Sigma) = 2\pi \int_a^bf(x)\sqrt{1+f'(x)^2}dx.
$$
It's likely that your familiar with that from calculus or classical differential geometry. Alternatively, you can consult Wikipedia http://en.wikipedia.org/wiki/Surface_of_revolution

In particular, the function $g:[-1,1]\rightarrow\mathbb R,\ x \mapsto \sqrt{1-x^2}$ produces the sphere $S^2$ as a surface of revolution. We have to be careful about the end points $-1$ and $1$ of the interval $[-1,1]$, but since we're in a probabilistic setting and consider uniform distribution on $S^2$, we can ignore these points by invoking a measure zero argument.

Now, let's denote uniform probability measure on $S^2$ by $P$, i.e. for
$A \subseteq S^2$ Lebesgue measurable, we have
$$
P(A) = \mathrm{Area}(A) / \mathrm{Area}(S^2) = \mathrm{Area}(A)/4\pi
$$ (you can get $\mathrm{Area}(S^2)$ from the formula above :-). Moreover, let's denote Lebesgue measure on $\mathbb R$ by $\lambda$ and uniform probability measure on $[-1,1]$ by $Q$, i.e. for $B \subseteq [-1,1]$ Lebesgue measurable, we have
$$
Q(B) = \lambda(B) / \lambda([-1,1]) = \lambda(B) / 2.
$$ Finally, let
$$
T:S^2\rightarrow [-1,1],\ (x,y,z) \mapsto x
$$ be the projection onto the first coordinate. We want to show that the image of $P$ under $T$ is $Q$, i.e.
$\forall B \subseteq [-1,1]$ Lebesgue measurable: $P(T^{-1}(B)) = Q(B)$. By construction of Lebesgue measure, this is equvalent to
$$
\forall [a,b] \subseteq [-1,1]:\ P(T^{-1}([a,b])) = Q([a,b]).$$
Now, $T^{-1}([a,b])$ is the slice of $S^2$ "around" the interval $[a,b]$ on the $x$-axis. We can calculate its area with the formula from above, namely
$$
\mathrm{Area}(T^{-1}([a,b])) = 2\pi\int_a^bg(x)\sqrt{1+g'(x)}dx.
$$
Here, the integrand is
$$g(x)\sqrt{1+g'(x)^2} = \sqrt{1-x^2}\sqrt{1+\frac{x^2}{1-x^2}} = \sqrt{1-x^2}\sqrt{\frac1{1-x^2}} = 1.
$$
From this we get
$$
P(T^{-1}([a,b])) = \frac{\mathrm{Area}(T^{-1}([a,b]))}{4\pi} = \frac{2\pi(b-a)}{4\pi} = \frac{b-a}2 = Q([a,b]),
$$
which is exactly what we want.