Tempo, time signature and note lengths

Question: Is there any sound numerical correlation between tempo, time signature and note lengths(duration in time)?
For example:
With some certain time signature like 6/8 or 4/4 and with a 120 bpm tempo what is the length of whole note, half note, crotchet etc ?
Answer: Each of these can be thought of as a conversion factor. Typically, you're converting everything to or from beats (which are the basic unit of time in music). If you recall "dimensional analysis" from high-school physics, this is a great place to use it!

Time signature numerator = beats/bar
Time signature denominator = beats/whole-note (i.e. what division of whole note is a beat)
Tempo = beats/minute

However, there is the additional caveat that the "beats" in the tempo may not be the same as the "beats" in the time signature. In this case, you have to compare the note in the tempo marking with the time signature denominator. This typically happens in compound time, as explained by Dom and Bob Broadley.
So if you were looking for the actual time duration of a note, you'd use the time signature's denominator to determine how many beats (or what fraction of a beat) are allotted to that note. Then you'd use the tempo to determine the length of time in a beat (possibly accounting for different definitions of beat if needed).
Example
I was asked to give an example, presumably of finding the duration of a note. It should go without saying that this isn't something that any musician would ever need or want to think about while playing (especially since the actual tempo will often be somewhat variable during performance), but that doesn't mean there might not be a reason for someone to do it (such as when programming a computer).
For this example, let's say the time signature is 6/8, the tempo is a dotted quarter at 108 bpm, and you want to know how long a quarter note (or two tied eighth notes) lasts. From the tempo, we know there are (108 dotted-quarters / minute). We also know that our note's duration is 2/3rds the duration of the tempo unit (our quarter note lasts two eighths, while the tempo unit is three eighths). This gives us the formula below. Note that because each of the ratios below is exactly equal to one by definition, I can "flip" them as needed, in order to ensure that the units cancel out properly.

(60 seconds / 1 minute) * (1 minute / 108 dotted-quarters) * (2 dotted-quarter / 3 quarters)
= (60 * 2) seconds / (108 * 3) quarters
= (120/324) seconds / quarter note
= 0.370 seconds / quarter note

You'll also notice that (aside from affecting the unit the tempo is measured in) the time signature never enters into this equation. That's because the time signature is used for finding the length of a bar (or measure), which has no direct bearing on the duration of the note. So what if you wanted to find the length of a bar? The calculation is very similar, but note where the 6 (from the time signature) comes into play.

(60 seconds / 1 minute) * (1 minute / 108 dotted-quarters) * (1 dotted-quarter / 3 eighths) * (6 eighths / bar)
= (60 * 6) seconds / (108 * 3) bars
= (360/324) seconds / bar
= 1.111... seconds / bar

Addendum for MIDI Files
If you're working with MIDI files and sequencers, you may also come across a quantity called "ticks" or "Pulses Per Quarter Note" (PPQN) which defines the temporal granularity of the events in that file. This doesn't directly reference either beats or real-time units, so there's a bit of conversion necessary. For example, assuming the tempo unit matches the time signature denominator:
ticks per second = (ticks/quarter-note) * (quarter-note/beat) * (beats/minute) * (minute/second)
= PPQN * (4/denominator) * (tempo/60)
Comment: If no explicit tempo mark is given, you can map the 1/4 note to the tempo number in BPM. For example at 60 BPM the 1/4 will always take 1 s, no matter if you have 2/4, 4/4, 6/8 or whatever. If an explicit tempo mark is given, the above answer applies. For example with "<1/8> = 60 BPM" you will have 60 of the 1/8 notes per minute. (Please correct me if I got it wrong.)
Comment: So, if I have the measureTempo, measureNumerator, measureDenominator, noteDupleDuration, can I get the noteTicks ?
Answer: Another question and answer give answers for any beat type and tempo, but for the examples above, it depends upon which note length beat is 120 bpm.
For instance, a crotchet bpm of 120 (as would probably be used in 4/4), will always give a crotchet length of 0.5 seconds, whole-note length of 2 seconds, half-note length of 1 second, and so on.
If, on the other hand, the quaver beat is 120 bpm (which may be used in a slow 6/8, for instance), the quaver length is now 0.5 seconds, the crotchet is 1 second, the dotted-crotchet is 1.5 seconds, and so on.
Of course, in 6/8 you would be very likely to have the tempo marking given as how many dotted-crotchet beats there are per minute. If this were 120, the dotted crotchet is 0.5 seconds, the crotchet is two-thirds of this (approx. 0.33 seconds) and a quaver is a third of this (just 1/6 of a second).
Comment: Also keep in mind that if your tempo comes from a midi file, that note length will always be a quarter note regardless of what the sheet music notates it as.  Technically in microseconds per quarternote which translates to quarter notes per minute
Answer: It depends. The BPM is telling you the tempo based on a reference. If it is 4/4 then it is most likely this:

This pretty much means that there are 120 quarter notes a minute so each quater note would be a half second long. If you wanted to know how many half notes there are in a minute it is just simple math. Since there is two quarter notes in every half note then you just cut the BPM in half to get how many half notes there are a minute. In this case it would be 60 and each half note would be a second long.
Similarly, if you wanted to know how many whole notes there are in a minute it is just simple math. Since there is four quarter notes in every whole note then you just divide the BPM by 4 to get how many whole notes there are a minute. In this case it would be 30 and each whole note would be two seconds long.
In 6/8 you would most likely see this:

This is slightly different since a dotted quarter note (a quarter note and an eighth note) get the beat. In this case there would be 80 quarter notes a minute.

Tempo, time signature and note lengths


White screen of death when uploading a file attachment

Question: I am currently experiencing a problem when adding file attachments to nodes in Drupal 6. When attaching a file and clicking the upload button, the screen goes white. I checked the files directory and the file does not appear there so it would seem it never gets uploaded. This problem occurs on the production server but not the test server. I have tried displaying php errors by modifying the index.php file but that does not display anything. I have the php memory set to 154MB but still no dice. I have Googled and searched this site but can't find a solution. Has anyone else experienced this problem? Can anyone provide some insight as to what the cause of this might be (and hopefully how to fix it)?
System setup
Ubuntu 10.4,
Apache,
PHP 5.3,
MySQL 5.1
Drupal 6.22,
CKK 6.x-2.9,
jQuery UI 6.x-1.5,
jQuery Update 6.x-2.0-alpha1,
plus a whole boatload of other modules (that may or may not be relevant).
Thanks for any possible insight into this.
Comment: Doing some more digging in the error logs, I came across this message: mod_fcgid: HTTP request length 133640 (so far) exceeds MaxRequestLen. A possible solution to this problem is to update the Apache vhost configuration file and add the FcgidMaxRequestLen directive with a big enough value (in bytes), for example

FcgidMaxRequestLen 2000000

which equals roughly 2 MB. Then restart Apache. I will give this a go and see what happens
Answer: mod_fcgid have to do with FastCGI.
There are actually a few PHP settings you may need to investigate and modify.
Reference: Increase upload size in your php.ini
In short though, you will need to up your upload_max_filesize as well as your post_max_size
Also, I would recommend watching your /var/log/apache2/error.log (Default location in Ubuntu 10.4) while debugging.  Generally running sudo tail -f /var/log/apache2/error.log will show you 'white screen' errors in real time.


How to integrate $\int^a_0\int^a_0\int^a_0 \sin(\frac{n_x\pi}{a}x)\sin(\frac{n_y\pi}{a}y)\sin(\frac{n_z\pi}{a}z) dxdydz$?

Question: I am doing a physics question that requires me to integrate
$$\int^a_0\int^a_0\int^a_0\sin(\frac{n_x\pi}{a}x)\sin(\frac{n_y\pi}{a}y)\sin(\frac{n_z\pi}{a}z) \text dx\text dy\text dz,$$
where $n_x$, $n_y$, $n_z$ and $a$ are constants.
How do I go about doing this integral?
Comment: Right, but if it was for a physics problem, they are probably constant integers @Isham.
Comment: Integrate $\int^a_0sin(\frac{n_x\pi}{a}x)dx\int^a_0sin(\frac{n_y\pi}{a}y)dy\int^a_0sin(\frac{n_z\pi}{a}z) dz,$
Comment: This looks like a wavefunction in the 3D infinite potential well, are you sure the $n$s aren't integers?
Comment: Op said they are constants @DominicReiss
Comment: I see @DominicReiss.
Answer: By "Fubini's theorem" this is the same as
$ \left(\int_0^a sin(\frac{n_x\pi}{a}x)dx\right)\left(\int_0^a sin(\frac{n_y\pi}{a}y)dy\right)\left(\int_0^a sin(\frac{n_z\pi}{a}x)dz\right)$
The integral of $sin(\frac{n_x\pi}{a}x)dx$ is $\frac{a}{n_x}cos(\frac{n_x\pi}{a}x)$  evaluated between 0 and a and the other two are the same except with $n_y$ and $n_z$.


Consumo dinamico de API REST React

Question: Sou novo na área e saber como posso fazer para ter um consumo dinâmico de api rest em react. Atualmente a minha consulta está fixa e minha ideia seria pegar o valor que o usuario digitar para consulta, como posso passar essa informação via parametro?
import axios from 'axios';

const api = axios.create({
    baseURL: 'https://localhost:44340/api'
});

export default api;

Meu componente
import React, { Component } from 'react';
import api from '../../../SolicitacaoApi';
import './style.css'

class SolicitacaoTable extends Component {
  state = {
    solicitacao: [],
  }
  async componentDidMount() {
    const response = await api.get('solicitacao?protocolo='+1000250170);
    this.setState({ solicitacao: response.data });
  }
  render() {
    const { solicitacao } = this.state;
    return (

                    Protocolo
                    Titular
                    Email
                    Data de inclusão
                    Telefone
                    Tipo de produto
                    Tipo de emissão
                    Status

                    {solicitacao.protocolo}
                    {solicitacao.titularNome}
                    {solicitacao.email}
                    {solicitacao.dtInclusao}
                    {solicitacao.telefone}
                    {solicitacao.tipoProduto}
                    {solicitacao.tipoEmissao}

                            {solicitacao.statusSolicitacao}

    );
  };
};
export default SolicitacaoTable;

Comment: A pergunta não está clara, de onde vem o valor? Qual o problema exatamente? Você pode usar o `componentDidUpdate` para observar mudanças no estado ou nas props e realizar a requisição quando desejar, já que o `componentDidMount` só será executado uma vez
Answer: Você pode criar um useEffect para a variável que deseja. Ou seja, no momento em que determinada váriavel tiver seu valor alterado, ele dispara uma determinada action. Olha o seguinte exemplo.
const [value, setValue] = React.useState('');

const handleChange = (event) => {
    setValue(event.target.value);
  };

React.useEffect(() => {
    async function loadClients() {
      setLoading(true);
      const response = await api.get('agendamentos', {
      headers: {
        value
      }
    });

      const temp = response.data.map((client) => {
        return {
          label: client.descricao,
          options: client.lojas
        }
      })

      setContent(temp);
      setLoading(false);
    }

    if(value !== ''){
      loadClients();
    };
  }, [value])

<RadioGroup row aria-label="gender" name="gender1" value={value} onChange={handleChange}>
          <FormControlLabel value="trocas" control={<Radio color="default" />} label="Trocas" />
          <FormControlLabel value="estoques" control={<Radio color="default" />} label="Estoques" />
</RadioGroup>

Eu uso o useState para criar as variáveis mas utilizo o useEffect para monitora-lá e chamar a API para carregar as novas informações.
Comment: Levando em consideração que o componente dele é um componente Classe, ele não pode usar `useEffect`. Sua resposta teria mais valor apresentando uma abordagem possível para o caso de componentes Classe também.
Answer: Você pode adicionar um estado para armazenas seu campo de busca:
  state = {
    protocolo: '',
  }

Usando axios você pode passar os parâmetros desta forma:
const response = await api.get('solicitacao', {
  params: { protocolo: this.state.protocolo }
});
// Saída: http://suaurl.com/solicitacao?protocolo=valor

Agora você pode criar um input de texto que atualiza o state.protocolo e criar um botão que chama sua função que faz a busca

Consumo dinamico de API REST React


calculate riemann sum of sin to proof limit proposition

Question: $$\lim_{n \to \infty}\frac1n\sum_{k=1}^n\sin(\frac{k\pi}{n})$$
I'm having trouble expressing $\sin(x)$ differently here in order to calculate the riemann sum.
I want to show that this converges to $\frac{2}{\pi}$ so it equals to $\int_0^1 \sin(x\pi)$.
Is there any easy way to express $\sin(x)$ different here?
Added:
$$\frac{1}{2i}(\frac{\cos(\frac{(n+1)\pi}{n})+i\sin(\frac{(n+1)\pi}{n})-\cos(\frac{\pi}{n})+i\sin(\frac{\pi}{n})}{\cos(\frac{\pi}{n})+i\sin(\frac{\pi}{n})-1}-\\\frac{\cos(-\frac{(n+1)\pi}{n})+i\sin(-\frac{(n+1)\pi}{n})-\cos(-\frac{\pi}{n})+i\sin(-\frac{\pi}{n})}{\cos(-\frac{\pi}{n})+i\sin(-\frac{\pi}{n})-1})$$
Comment: What's your question exactly? You are already got the right integral.
Comment: Usually, one would calculate your sum by calculating the integral. (The integral is defined in terms of the  limit of Riemann sums.)
Comment: well I got the right integral/limit by trying it out in SAGE. I've not calculated the limit of the expression/the riemann sum by hand.
Comment: @zaiphox: Ok. see the answer. You can have a closed form for your sum and then take the limit.
Answer: Use that $$\sum_{k=1}^n \sin kx=\frac{\sin\dfrac{kx}2\sin (k+1)\dfrac x2}{\sin\dfrac{x}2}$$
ADD One can deduce the above in several ways. The first is to note it is the imaginary part of $$\sum_{k=0}^n e^{ikx}=\frac{e^{(n+1)ix}-1}{e^{ix}-1}$$
Another choice is to use $$\cos b-\cos a=2\sin\frac{b-a}2\sin\frac{b+a}2$$
Now let $$b=\left(n+\frac 1 2\right)x\\a=\left(n-\frac 1 2\right)x$$
Then you get
$$\cos \left(n+\frac 1 2\right)x-\cos \left(n-\frac 1 2\right)x=2\sin\frac{(n+1)x}2\sin\frac{x}2$$
Then sum and telescope.
Comment: Thanks. Where did you deduce this formula from?
Answer: The sum can have the closed form
$$\sum_{k=1}^n\sin\left(\frac{k\pi}{n}\right)= \frac{\sin \left( {\frac {\pi }{n}} \right)}{  \left( 1-\cos \left( {\frac {
\pi }{n}} \right)  \right)} .$$
Added: To prove the above identity, you need the two facts
1) $$ \sin(x)=\frac{e^{ix}-e^{-ix}}{2i}, $$
2) $$ \sum_{k=1}^{n}x^m={\frac {{x}^{n+1}-x}{-1+x}}. $$
Comment: Could you explain to me how to deduce the closed form or point me in the right direction via some kind of link?
Comment: @zaiphox: I'll add more hints.
Comment: Could you tell me wether my approach that I added in the OP is right? I'm having trouble getting to the closed formula.
Answer: The Riemann sum can be written in closed form by reference to the following trig identity. List of Trig Identities (https://en.wikipedia.org/wiki/List_of_mathematical_series)
$$
\sum_{k=0}^{n-1}\sin(k\pi/N)=\cot(\pi/2N)
$$
If you're curious about how that can be derived, you will need a bit of cleverness, using the difference of cosine identities.
The Riemann sum is
$$
(1/N)\sum_{k=0}^{n-1}\sin(k\pi/N)=(1/N)\cot(\pi/2N)
$$
to take the limit, as $N\rightarrow\infty$, of $\cot(\pi/2N)/N$, write as $\frac{\cos(\pi/2N)}{Nsin(\pi/2N)}=\frac{\cos(\pi/2N)}{sin(\pi/2N)/(1/N)}$  The numerator approaches 1 as $N\rightarrow\infty$ and the denominator approaches $\pi/2$ on account of the well known formula $\lim_{x\rightarrow 0}sin(\alpha*x)/x=\alpha$.  Thus the answer is $1/(\pi/2)=2/\pi$ $\square$
The Trig Identity
As for the trig identity, the strategy is to rewrite each sine as a difference, which can then be used to telescope the series.  If we multiply and divide each term in the series by $\sin(\theta/2)$, the numerator becomes $\sin(k\theta)\sin(\theta/2)$, which can then be written as a difference of cosines.  The series then telescopes so only the first and last term remain.  The conclusion is an exercise in trig identities, which I will omit for now.  I may come back and edit this solution if there are still questions.
Comment: OK, that makes more sense.  Nonetheless, the Wiki formula is asserted true for the special case $\theta=\pi/N$, and you seem Ok with this being true in the special case, so I will rewrite the solution accordingly, or did I still misunderstand you.
Comment: The real question, for me, is how to approach this sum if you cannot yet assume $\sin(x)=(\exp{ix}-\exp{-ix} )/ 2\pi$.  Typically, this problem is given in the curriculum before that formula is introduced.  If you know what you're after, the derivation makes sense, but it seems hard to come up with it if you haven't seen "the trick".
Comment: @chappers - thank you for the correction.   I have updated accordingly, but seem to have lost your original comments.
Answer: In general,
$\sum_{n=1}^p \sin n\theta=\Im (\sum_{n=1}^p e^{ i n\theta})=\Im (e^{i\theta}\frac{ 1-e^{i p\theta}}{1-e^{i \theta}}),$
which, for $1-e^{i n\theta}=e^{i0}-e^{i n\theta}=e^{i n\theta/2}(e^{-i n\theta/2}-e^{i n\theta/2})= e^{i n\theta/2}\cdot (-2i)\sin(n\theta/2)$, (we can use trigonometric formulas too, which one can notice is essentially the same) equals
$$\Im (e^{i\theta}\frac{ 1-e^{i p\theta}}{1-e^{i \theta}})
=\Im (e^{i\theta}\frac{e^{i p\theta/2}\cdot (-2i)\sin(p\theta/2)}{e^{i \theta/2}\cdot (-2i)\sin(\theta/2}))\\
=\Im (\frac{e^{i (p+1)\theta/2}\sin(p\theta/2)}{\sin(\theta/2)})
=\frac{\sin[(p+1)\theta/2]\sin(p\theta/2)}{\sin(\theta/2)}.$$
Therefore,
$$\lim_{n \to \infty}\frac1n\sum_{k=1}^n\sin(\frac{k\pi}{n})
=\lim_{n \to \infty}\frac1n\frac{\sin[(n+1)\pi/2n]\sin(n\pi/2n)}{\sin(\pi/2n)}
=\lim_{n \to \infty}\frac1n\frac{\cos (\pi/2n)}{\sin(\pi/2n)}=\frac{2}{\pi},$$
for $\lim_{x\to0}\frac{\sin x}{x}=1.$
This 'proves' $\int_{0}^1 \sin(\pi x) dx=\frac{2}{\pi}.$


Textfile Structure (tables)

Question: Alright, I know I have had a lot of help on here recently with writing queries in php and outputting them to a text file. I have finally grasped and learned how to actually do that much (thanks guys!). The code below show what I do have:
Now I know the table structure (th/tr/td) does not work in a text file. I was wondering if anyone knew how to get this into a traditional "column" view like:
id   ||   title   ||   keyword
================================
2    ||   bob     ||   jones
2    ||   bob     ||   jones
2    ||   bob     ||   jones
2    ||   bob     ||   jones

I dont necessarily need borders or anything just at least an easy to read format. This outputted file will be used by google products for the company I work for (and they need an easy to read format I believe, or just something that is set up in a table form. I could do a CSV, but I know less about that then I do php. Thanks again.
Comment: CSV is a stupendously simple format, especially since PHP has functions to deal with it. It'd be a lot easier than fake tables, especially if it's supposed to be parsed automatically.
Comment: By the way this was somewhat of a simplified example. If someone asked me to build a report from a SQL query, I would do it in phpMyadmin and export the results as an Excel file. Otherwise you have to continually modify the SQL, formatting, etc.
Answer: CSV is trivial with fputcsv:
$fh = fopen('output.csv', 'w') or die("can't open file");

// output header and first row
$row = mysql_fetch_assoc($result)
fputcsv($fh, array_keys($row));
fputcsv($fh, $row);

// output the remaining rows
while ($row = mysql_fetch_assoc($result)) {
    fputcsv($fh, $row);
}

fclose($fh);

Comment: Indeed, a better solution using php builtin functions. I was asking myself why you didn't provide an answer yourself. :) Well done!
Answer: Okay, let's see how we can do this. I'm just going to focus on the relevant header printing and displaying formatted results. So then, in this case we're going to use fprintf to print some fancy formatted text to our file in question here. So here's basically how will do this:
id   ||   title   ||   keyword

First off we need to make some widths for these fields so everything shows up in a nice fashion. We'll set a width of 10 for each:
fprintf($fh, "%-10s || %-10s || %-10s\n", "id", "title", "keyword");

What this %-10s does is tell us that we want a string formatted with a width of 10 characters, with spaces used for padding if the length is not enough. You can adjust the 10 to be whatever width you'd like in order to get the best result. The result comes out to something like this:
id         || title      || keyword

Next we print out our divider, which I just tweaked the length a bit until it came out the same:
fprintf($fh, "===================================\n");

Then we loop through and print out our values:
while ($row = mysql_fetch_assoc($result)) {
  fwrite($fh, "%-10s || %-10s || %-10s\n" $row['card_id'], $row['title'],  $row['description']);
}

Which will give us something like this:
id         || title      || keyword
===================================
2          || bob        || jones
2          || bob        || jones
2          || bob        || jones
2          || bob        || jones

And that's it! Here is the full code for reference:
<?php
// Make a MySQL Connection
 mysql_connect("mysql4.host.net", "user", "pass") or die(mysql_error());
 mysql_select_db("amyadele_test") or die(mysql_error());

// Query the database for data
$query = "SELECT card_id,title,description FROM cards";
$result = mysql_query($query);

// Open file for writing
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");

// Loop through returned data and write (append) directly to file
fprintf($fh, "%-10s || %-10s || %-10s\n", "id", "title", "keyword");
fprintf($fh, "===================================\n");
while ($row = mysql_fetch_assoc($result)) {
  fprintf($fh, "%-10s || %-10s || %-10s\n", $row['card_id'], $row['title'], $row['description']);
}

// Close out the file
fclose($fh);
?>

Comment: +1 The problem is, what do you do with titles/keywords longer than 10 characters...?
Comment: @deceze indeed that could become an issue, which is why I made the comment on being able to adjust the widths accordingly. The ID field could have been made shorter to be honest
Comment: @deceze There's probably a way to do it dynamically by first getting the length of the longest keyword, but I'd rather not complicate the example too much

Textfile Structure (tables)


How do I create a view with mixed languages, showing the node's original language by default?

Question: I have a site with mixed languages, Spanish and English. Some content was originally created in English, then translated into Spanish. Other content was originally created in Spanish, then translated into English. The remaining content is either in Spanish or English and is not translated.
How do I create a view that shows all of this content in the original content (non-translated) language, showing a view with a mix of English and Spanish? Then if the user chooses English or Spanish, it will show only those languages.
Comment: Site is Drupal 7.72
Answer: To show only the "original" nodes in any language don't include any language filters so all languages are shown. This will show all your content, translated or not in both languages.
It's not clear from your question what you mean by "that shows all of this content".
If you want to show only the nodes that were originals, and not a translation of another, add the Source translation Filter from the Content translation Category. Set it to Include untranslated content: Yes if you want only the nodes that haven't been translated yet.
Set it to No if you only want to show nodes that already have a translation node.
I'm guessing you'll want the No selected, or you won't need the Content translation Filter filter at all.
Then add the Content: Language Filter and Expose it to allow visitors to filter the language. Select only the two specific language options and the Limit list to selected items if you only want those to be the options your visitors see and are able to choose (so they don't see options like "Site default", "Current", etc).


Why don't we add multiple integration constants

Question: suppose we had
$\int x^2 + x \, dx$, I understand you can split it up into $\int x^2 \, dx$ + $\int x \, dx$, but then why is it that we don't add seperate constants of integration for each indefinite integral, and simply add a single constant on the end once we are done integrating?
Thanks
Comment: What is the purpose? Sum of two constants is a constant.
Comment: I think I get it now. It's like saying the antiderivative has constants scattered around, when they could all be added onto one term at the end.
Comment: Suppose the first integral gives you constant $C_1$ and the second integral gives you constant $C_2$. Then when you finish simplifying, we can just let $C = C_1+C_2$ be our integration constant. This generalizes, so it doesn't matter how many integrals you have, you can always just use one constant.
Answer: Writing $\int f(x) dx = F(x) + C$ is short-hand for saying that the family of antiderivatives of $f(x)$ is the set of functions $F(x) + C$, where $C$ is some arbitrary constant.
We could write $\int f(x) dx = F(x) + C_1 + C_2$, but then we'd note that (if there are no restrictions on the constants in question) the two sets are identical - for any function in the latter set defined by specific values of $C_1$ and $C_2$, we can always show that it maps to a value of $C$ and a corresponding function in the former.
In the end, we choose the representation that's most useful - having two constants doesn't add any information in this case, and so we would usually choose to absorb them into a single one. We might choose to leave them separated if having two constants gave additional insight into something - e.g. if we forced $C_1$ to be an integer and $C_2$ to be in the interval $[0, 1)$ and they had distinct impacts on the system we're looking at.
Similarly, the family of strictly positive functions that satisfies $f' = f$ could be written as $f(x) = e^{x+A}$ or $f(x) = Be^x$ (with $B > 0$), and while they represent the same functions the placement of the constant can have a different interpretation.
Answer: If indefinite integration is viewed loosely as the process of finding a function given its derivative, then the constant of integration is used to express the fact that there are many functions that have the same derivative (because the derivative of any constant is $0$).
In your example, notice that any function $f$ of the form
$$
f(x)=\frac{x^3}{3}+\frac{x^2}{2}+C
$$
for some constant $C$ will yield the derivative $f'(x)=x^2+x$. You can define $f$ to be
$$
f(x)=\frac{x^3}{3}+\frac{x^2}{2}+A+B+C,
$$
for some constants $A,B,C$ and the derivative of $f$ will stay the same.


Where do I find the settings for adding a vocabulary to a content type in Drupal 7?

Question: In Drupal 7, I can't find the Content types and Required setting under edit vocabulary.
How do I customise it?
Drupal6

Drupal7
Answer: Head over to the Manage fields tab of your content type. For example, for "article" that would be admin/structure/types/manage/article/fields. Then add a Term Reference field.
This question is about Drupal 7, but be aware that Term Reference appears to be deprecated and potentially be removed from Drupal 8 (in favor of the entity reference field). For more details on that, refer to the question about "Are there any benefits/caveats with using Entity Reference over Term Reference?", in which there is a comment also like "Term reference isn't going anywhere and there will be an upgrade path from 7 to 8".
Comment: The term reference field is not a good option. It has been deprecated and removed from Drupal 8 in favour of the entity reference field. Using term reference will lead to problems if and when the site will be migrated to Drupal 8. Entity reference is the way!
Comment: Is there no upgrade path for D7 term reference to D8 entity reference? I would imagine there is, since this is quite a common thing. And there is some useful logic in D7 that is only available for term reference, afaik. So it can still be preferable to use that.
Comment: See http://drupal.stackexchange.com/questions/54830/are-there-any-benefits-caveats-with-using-entity-reference-over-term-reference and https://www.drupal.org/node/1681908
Comment: @donquixote : interesting comment / question, I would hope such upgrade path is (or will be) available too ...


Catching multiple exception at once in oracle

Question: Please let me know whether it is possible to catch multiple exception at same time in oracle. Not like 1 user defined and 1 is oracle default .I need to catch multiple user defined exception at same time . Kindly let  me know how to do .
Thank you !
Comment: Could you provide us code please you are using to cause multiple exception at same time?
Comment: I don't see how it would be possible.  You perform an operation. It generates an exception.  You catch the exception.  The only possible additional exception would come from something you did in handling the first.  It's not like you can generate exceptions but ignore them and continue processing, then at the end go back and gather up all the exceptions you ignored.
Comment: Do you mean [bulk exception handling](https://livesql.oracle.com/apex/livesql/file/content_CMSE3VBYFCO9IX3PGE4S5C1Q8.html)? Or [DML Error Logging](https://oracle-base.com/articles/10g/dml-error-logging-10gr2)? If neither of those solves your problem you need to **edit your question** to provide a bit more detail about what you're trying to achieve.
Comment: Another alternative, do you mean that a single unit of code could potentially throw one of several exceptions and your exception block needs to catch and handle whichever is thrown?
Answer: Certainly, there is - if I understood the question correctly. It is called WHEN OTHERS. Though, people usually misuse it, especially when they use
exception
  when others then
    null;
end;

as it successfully hides any errors that might appear. WHEN OTHERS is OK during development process, but might be really bad in production, especially if it doesn't contain raise.
Answer: Yes, you can do what you want from "When Others" as indicated by @Littlefoot or bulk processing errors (not covered here). But additionally you can have an OR condition exception name clause on the WHEN . It's not very useful as generally requires more code the 2 separate WHEN condition, but it is valid syntax. The following demonstrates various error definition methods and exception processing.
create table except_demo ( id integer, col1 varchar2(20));
insert into except_demo (id, col1)
  select 5,'OK' from dual union all
  select 6,'Too Many' from dual union all
  select 6,'Still' from dual;

select id, count(*) from except_demo group by id;

create or replace procedure catcher(which_in integer, select_in boolean default False)
is
  e_user_1 exception;
  e_user_2 exception;
  invalid_which_range exception;
  appErr_inactive_acct exception;
  sample_ora_error exception;
  pragma exception_init (sample_ora_error, -00060);

  rae exception;
  rae_num constant integer := -20100;
  pragma exception_init  (rae, -20100);

  col1_value except_demo.col1%type;
begin
   dbms_output.put( 'Enter catcher(' || which_in || ') Result=>');
   if which_in > 8
      then raise invalid_which_range;
   end if ;
   if select_in
   then
       select col1
         into col1_value
         from except_demo
        where id = which_in;
        dbms_output.put_line('Select Successful 1 row selected.');
   else
       case which_in
            when 1 then raise e_user_1;
            when 2 then raise e_user_2;
            when 3 then raise appErr_inactive_acct;
            when 4 then raise sample_ora_error;
            else raise_application_error(rae_num, 'Which_In=' || which_in || ' invalid. Please specify number 1-7 only');
        end case;
    end if;
exception
   when e_user_1
   then dbms_output.put_line('Error e_user_1');    -- user error

   when e_user_2
   then dbms_output.put_line('Error e_user_2');

   when no_data_found or too_many_rows
   then dbms_output.put_line('Select except_demo where id=' || which_in ||'; Returned 0 or more than 1 row. Must return exactly 1.' );    -- oracle predefined error

   when sample_ora_error
   then dbms_output.put_line('Ora Error:: ' || sqlerrm );            -- oracle error NOT predefined

   when appErr_inactive_acct
   then dbms_output.put_line('Error Account id ' || which_in || ' is inactive.');  -- user error

   when rae
   then dbms_output.put_line(sqlerrm);

end catcher;

declare
  do_select boolean;
begin
    for i in 1..9
    loop
       do_select := (i between 5 and 7);
       catcher(i,do_select);
    end loop;
exception
    when others
    then
        dbms_output.put_line('Error returned from catcher=>' || sqlerrm);
        raise;
end ;

drop procedure catcher;
drop table except_demo;

In a live environment the dbms_output statement would be replaced writing the message and other information to a exception log table and NOT dbms_output.
I have a very minor disagreement with Littlefoot. I firmly believe that what ever is written in development, whether intended or not, will run in production. Too often it is the unintended that gets you into trouble. Therefore the example of a misused WHEN OTHERS is invalid even in development.


System of equations to represent a matrix

Question: Suppose that there is a $n \times n$ matrix. Then there will be entries $A_{ij}$ where i and j represent row and column.
Equations contain entries of a matrix, $A_{ij}$ and when the equations are solved, we will get each entry.
(Add: By equations I mean like ${A_{11}}^2 + {A_{12}}^3+..$ where $A_{ij}$ would be entries of a matrix.)
Is there any way to represent the matrix using a system of only $kn$ equations where $k$ is constant for all combinations of integer entries? (Obviously, linear equations will not do this.)
Any variation of the matrix is allowed if the variation respect the following: entries ($n \times n$ of them) in the same column and row must be in the same column and row.
Edit:
In linear algebra, for example, if there are $n \times n$ distinct equations, then you will be able to get entries of a matrix. This is a-bit different question.
Comment: What do you mean by "represent the matrix using a system of only $kn$ equations"? What is $k$?
Comment: What is an $n \times n \times n$ matrix?
Comment: @QiaochuYuan constant.
Comment: Okay. What do you mean by representing the matrix using a system of equations?
Comment: @QiaochuYuan Equations contain components of a matrix, $A_{ij}$ and when the equations are solved, we will get each component. And as the question says.
Comment: I don't understand what you mean by that.
Comment: @QiaochuYuan By equations I mean like ${A_{11}}^2 + {A_{12}}^3+..$ where $A_{ij}$ wpuld be components of a matrix.
Comment: @Liz: I still don't understand what you're asking. What is the relevance of the fact that you've put the $A_{ij}$ into a matrix? What do you want these equations to do?
Comment: Okay. Let me get this right. You would like to represent an $n\times n$ matrix $A,$ by $n^2$ variables, $A_{ij}$ denoting the $n^2$ **entries** (not components) of $A.$ Then, are you looking for equations involving the $A_{ij}$'s? What is given (or, known) here?
Comment: @J.D. My mistake. I was unsure of which tags I should use. The optimization tag would not be something that describes my problem..
Comment: @J.D. yes, I am refering to entries. And yes, I am looking for equations involving the entries. What I am asking is when given any matrix of $n \times n$ entries, can we define one system of $kn$ equations that will be able to represent the matrix (and works for any matrix)?
Answer: I am not sure that I know precisely what you are looking for. However, the following may give a partial answer.
Suppose that we are working over the reals. Then the system of $m$ simultaneous equations
$$P_1(x_1,\dots,x_n)=0, \quad P_2(x_1,\dots,x_n)=0,\dots\dots, \quad P_m(x_1,\dots,x_n)=0$$
 is equivalent to the single equation
$$\left(P_1^2(x_1,\dots,x_n)+ P_2^2(x_1,\dots,x_n)+\cdots+P_m^2(x_1,\dots,x_n)\right)=0.$$
Answer: This isn't really an answer, just a too long for a comment. I'll repeat myself here to make sure I understood you correctly..
Let the variables $A_{ij}, 1 \le i,j \le n$ denote the $(i,j)$th entry of the $n\times n$ matrix $A.$ Given such an $A,$ you would like to encode it as a system of polynomials: $$P_i(A_{11}, A_{12}, \ldots, A_{nn}) = 0, \quad 1 \le i \le B, \tag{1}$$ where $B$ is the total number of polynomial equations. The system $(1)$ is constructed from the entries of $A,$ and the solution to $(1)$ uniquely determines $A.$ Your question is then about how small $B$ could be? In particular, could $B = kn$ for some constant $k$?
Obviously, if $\text{deg}(P_i) = 1$ for all $i,$ i.e. a linear system, then we need $n^2$ such equations.
If $\text{deg}(P_i) = d_i > 1,$ for some (or all) $i,$ then the situation doesn't get better. Consider the situation with only 2 variables. Two lines can uniquely determine a point, because the number of intersection points is at most 1. Now consider a higher degree curve: circles ($x^2 + y^2 - c = 0$.) Two circles intersect in at most 2 points, which gives you 2 solutions, one of which is your original matrix $A,$ and the other is some other matrix similar (as far as conditions go) to your original matrix. In higher dimensions (i.e. more variables), polynomials become surfaces & intersections become curves.
In general, the number of common solutions will be proportional to the product of the degrees, by Bézout's theorem. Alas, I'm not well familiar with algebraic geometry, and other user will prove far more helpful.
Again, long comment really rather than answer.
Comment: Oh. That's why linear algebra is most commonly used, right?
Comment: What about limiting the case to integers (entries)?


Upload large file via URLSession

Question: So I have some code I've been using to upload files in my app, along the lines of this:
var mutableURLRequest = URLRequest(url: url)
var uploadData = try! Data(contentsOf: dataUrl)
session.uploadTask(with: mutableURLRequest, from: uploadData).resume()

There's a little more to it than that, but those are the relevant parts.  However I've noticed for some large video files Data(contentsOf: dataUrl) fails since the file is to big to load into memory.  I want to restructure this so that I'm able to stream piece by piece to the server without ever having to load the whole file into memory.
I already have this figured out from my server, the only piece I haven't figured out is how to get a chunkSize piece from the data in a URL, without putting it into a data object.  I essentially want this construct:
let chunkSize = 1024 * 1024
let offset = 0
let chunk = //get data from dataUrl of size chunkSize offset by offset

//Upload each chunk and increment offset

NSInputStream seemed promising in being able to do this, but I wasn't able to figure out the minimum set up in order to pull bytes from a file on disk in this fashion.  What code can I use above to fill in the let chunk = line to do such a task?
Comment: I did some testing of `uploadTask(with:fromFile:)` and can confirm that it **does not** load the whole file into memory! This ended up being the perfect solution for me.
Comment: Did you try `uploadTask(with:fromFile:)`? It might be smart enough to stream from the file as opposed to loading the whole thing into `Data`. Or maybe use `uploadTask(withStreamedRequest:)`.
Comment: I'm guessing that isn't going to work for me since I need to decorate each chunk with some other HTTP junk so my server knows what's going on.  However, whatever it's using under the covers to do that may be what I need.
Answer: I have a working solution, might need a little tweaking, but seems to work for big files I've tried:
public func getNextChunk() -> Data?{
    if _inputStream == nil {
        _inputStream = InputStream(url: _url)
        _inputStream?.open()
    }
    var buffer = [UInt8](repeating: 0, count: CHUNK_SIZE)
    var len = _inputStream?.read(&buffer, maxLength: CHUNK_SIZE)
    if len == 0 {
        return nil
    }
    return Data(buffer)
}

I also call _inputStream?.close() on deinit of my class that manages the chunking of a file on disk.
Comment: Cool! But how would you send these peaces to your server one by one? Would you create a separate request for each chunk or is there a smarter/efficient way?

Upload large file via URLSession


Making one term in a vocabulary priority and print it separately

Question: I have several terms in a vocabulary and my content type can be tagged with more than one of them.
When I print the term names tagged with the currently viewed node it seems that the term names are printed always in the same order (in the order of term id?)
However I somehow need to make one priority term per node and then print its term name first or separately from the rest.
Is there anyway to do this?
Answer: Easiest non coding way make a separate vocab and disable tags and multiple select for the new vocab then theme as required.
Comment: Thanks but all the terms need to be within the same vocabulary because I use them for also different things like argument and Views exposed filter.
Answer: You could add a content taxonomy field and use that to select the highlight term.
http://drupal.org/project/content_taxonomy
Then over ride or write your own theme function to loop through the terms array and remove the highlighted one before its output to the page
Comment: Thanks for your input but can you please specify me what "highlight term" means. I don't see anywhere to configure it for content taxonomy.


Electron window.webContents.send doesn't work

Question: main.js
mainWindow = new BrowserWindow({ show: false, minWidth: 400, minHeight: 400, webPreferences: {nodeIntegration: true} });
mainWindow.maximize();
mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, '/html/index.html'),
    protocol: 'file:',
    slashes: true
}));
mainWindow.on('closed', function(){
    app.quit();
});
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(mainMenu);

mainWindow.once('ready-to-show', () => {
    mainWindow.show();
    const data = {id: 'checking_for_updates', display: 'none'}
    console.log(data)
    mainWindow.webContents.send('change_display', data)
})

index.html

Checking for updates.

it only logs 'data' once so probably the ipcRenderer doesn't run the ipcRenderer.on change_display event. How would I fix this issue?
Answer: Your code here:
mainWindow.once('ready-to-show', () => {
    mainWindow.show();
    const data = {id: 'checking_for_updates', display: 'none'}
    console.log(data)
    mainWindow.webContents.send('change_display', data)
})

only sends the change_display once. And so you'll see data logged once as well.


Busca de palavra em planilha do excel e retorno da linha inteira que contem essa palavra em PYTHON

Question: Olá, tudo bom? Sou iniciante em Python e gostaria de rodar um script que dada uma planilha em excel, o usuário pudesse buscar uma palavra dentro dessa planilha (input) e caso a palavra fosse encontra retornar "Arquivo Encontrado e exibir todas as linhas.
Por exemplo, minha planilha:

Nome    Idade   altura
Danilo  27  1.62
João    35  1.75
Maria   23  1.85
Thalita 25  1.80
O usuário buscando Danilo, gostaria que o programa retornasse:
Arquivo Encontrado e
Nome    Idade   altura
Danilo  27  1.62

Segue meu código:
from xlrd import open_workbook
workbook = open_workbook("c:/Python34/test.xlsx")
sheet = workbook.sheet_by_index(0)
prompt = '>'
print ("Entre com o termo a ser buscado: ")
item = input(prompt)
found = False
for cell in sheet.col(0):
     if cell.value == item:
       found = True
if found == True:
    print('Arquivo Encontrado', item) # tentei colocar (cell) mas dá errado
else:
    print('Arquivo não Encontrado')

Muito Obrigado
Answer: Particularmente eu gosto mais de trabalhar com csv do que com xls. Basta converter seu xls para csv.
Você pode utilizar regex ou o próprio findall para isso:
import re

data = open('seu_arquivo.csv')

texto = "Bem vindo ao python!"

resultado = re.findall(texto, data.read())

Isso vai te retornar uma lista com as coisas que encontrou sem precisar ficar fazendo loop de repetição.
https://docs.python.org/2/library/re.html
Comment: Olá, muito obrigado pela ajuda. Vou tentar a sugestão, abç


How to determine if random variables are distributed according to a multivariate normal distribution?

Question: Suppose $(x_1, x_2, x_3)\sim N(\mu, \Sigma)$ where $\mu\in\mathbb{R}^3$ and $\Sigma$ is a $3\times 3$ covariance matrix, are the variables $A = x_1 + x_2$ and $B = x_2 + x_3$ necessarily distributed according to a multivariate normal distribution? That is, do there exist $\nu\in\mathbb{R}^2$ and a $2\times 2$ covariance matrix $M$ such that $(A, B) \sim N(\nu, M)$
Answer: Yes and here is how to see it. Write $A$ and $B$ as
$$\begin{bmatrix} A \\B \end{bmatrix}=\begin{bmatrix} 1 & 1 & 0 \\0 & 1 &1 \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \\ x_3 \end{bmatrix}$$
and exploit the fact that linear combinations of multivariate normal variables are themselves normal.
Comment: If you want to do it explicitly I suggest you take a look at how to transform densities and/or the concept of moment generating functions.


Setting transformations to greyscale with libpng

Question: I am using libpng to read an image. The image itself has 4 channels (rgba), with 8 bits for channel. I want to read it as a greyscale image, preferably black and white (1 bit per pixel), but even 8 bits per pixel would be an improvement.
To that end, i have written function, as follows:
<code>extern "C" void cuttingStream::set_image_transformations_in_grayscale( pngImageInfo* info,pngDataStructures* png)
{
    //alpha channel is removed
    if (info->color_type & PNG_COLOR_MASK_ALPHA != PNG_COLOR_TYPE_GRAY)
        png_set_strip_alpha(png->png_struct_field);
    //switch to rgb is completed
    if (info->color_type & PNG_COLOR_MASK_COLOR != PNG_COLOR_TYPE_GRAY)
        png_set_rgb_to_gray(png->png_struct_field,1,NULL,NULL);
    png_read_update_info(png->png_struct_field, png->png_info_field);

    info -> rowbytes = png_get_rowbytes(png->png_struct_field, png->png_info_field);
    //bits per CHANNEL! note: not per pixel!
    info->bitdepth   = png_get_bit_depth(png->png_struct_field, png->png_info_field);
    //Number of channels
    info->channels   = png_get_channels(png->png_struct_field, png->png_info_field);
    //Color type. (RGB, RGBA, Luminance, luminance alpha... palette... etc)
    info->color_type = png_get_color_type(png->png_struct_field, png->png_info_field);
}
</code>
pngDataStructures is my own struct that holds things such as png_structp, png_infop and pointers to custom read function. pngImageInfo holds some information about image that is interesting to me, as it can be seen in the code.
The problem is, after the code executes, number of channels does not change. How can this be solved?
Answer: operator precedence problem:
//alpha channel is removed
if ( ( info->color_type & PNG_COLOR_MASK_ALPHA )  != PNG_COLOR_TYPE_GRAY)
the precedence of operator & is less than operator !=


Exchange 2003 Recovery Items go back 3 years for 1 user

Question: I have an Exchange 2003 environment serving approx 150 users.
We are quickly approaching the 75 GB limit, and need to clear out what I can until we can get a new server in place. (Probably months out...)
In trying to clean things up a bit, I discovered a problem with 1 Mailbox and it's "Recover Deleted Items" feature.
He can recover emails that are a full 3 years old!
I have the Mailbox Store's "Keep Deleted Items for (days):" setting set to 2 days.
I have also tried changing his mailbox to not use the Mailbox Store settings and have manually set his mailbox to 2 (and even 0 days when that didn't work).
I have a feeling that is could be accounting for a very significant portion of our Mailbox Store as he's one of the heaviest users.
I've been able to check quite a few other mailboxes, and they all seem to be working perfectly.  No more than 2 or 3 days worth of deletions in the Recovery area...
It appears that this one user is the only problem mailbox, but I don't know of any way to truly tell.
Does anybody know how I might be able to flush this out?  Or does anybody know of another setting that might be set for this mailbox somehow?  I've checked everything I can find, and there is very little of anything "special" for this user.
My first thought was to delete his mailbox and re-build it, but I'd rather not as that would be a major undertaking for this user (4GB mailbox, tons of rules, tons of email addresses, included in tons of distribution groups, etc...).
I'd rather not do that unless I absolutely have to...
Thank you in advance for any help you can provide!
Comment: Thank you Evan and Mark,

I actually did find some errors, just not where I expected to.
Apparently Database Maintenance is set to run only on Sunday between 6:30 and 10am...  That's getting changed...

Just after the Cleanup begins there are 7 errors (though listed as just Information) stating: "Error -1601 while hard-deleting messages in folder 1-91876 on database "First Storage Group\Mailbox Store (EMAIL)"  The folder changes with each error.  Also the summary event shows this:
Start: 515990 items; 36661813 Kbytes
End: 483080 items; 33033988 Kbytes

Looks like 30 untouchable Gigabytes!
Comment: If it were me, given the -1601 error, I would:
1. "Make sure you have a backup handy"
2. Run Isinteg -s  -fix -test alltests

I haven't worked directly with Exchange disaster recovery in at least.. 7? or so years, but I would consider calling Microsoft support.
Answer: This feature, known as "Dumpster Cleanup", is handled by the online Information Store maintenance functionality. By default, this runs from 00:00 to 05:00 local time.
There isn't any mechanism that I'm aware of to prevent a mailbox from being processed by dumpster cleanup.
Are your online backups running properly? I'd assume so, given that other users aren't building up dumpster items, but it's worth asking.
Are you seeing anything in the Application Event Log to indicate that there are problems occurring during the maintenance activities? If there was anywhere I'd suspect to find a smoking gun it would be here.
You can manually purge the dumpster for the affected mailbox to mark more space free in the IS database if you're running low on space. That's only a band-aid fix, but it might help.
Edit:
I'd be wary of that Information Store database based on what you've said in your comment re: your Event Log message. If you can, put up a temporary Exchange Server computer, move the mailboxes over to it, and start fresh on your production machine.
You won't have to do anything with Outlook-- Exchange is smart enough to "redirect" users to another Exchange Server computer when their mailbox is moved. As such, as long as you can muster the spare hardware you should be able to swing the mailboxes over to a temporary box, clean up the production box, and swing the mailboxes back. I wouldn't reinstall Exchange on the production box, but I would get all the mailboxes moved out of its Information Store, at which time I'd start with a fresh mailbox database.
If you cant do that, perform copious backups on the production server and run an isinteg against the store. That might clean up the problems you're seeing.
Comment: Came here to say what Evan said - check the application event log.
Comment: Sorry about that-- I used the word "Purge" in an inexact manner. From Microsoft Outlook, go into the "Recovery Deleted Items" dialog and delete any items you'd like to "purge" from there. That will permanently delete those items.
Comment: I've been in that window countless times and never realized I could do that!  Thanks for the heads up!  I'll try that on the Mailbox in question and see if those items can be removed.  That may just solve the Database Maintenance problems as well... One can hope at least.
Thank You!
Comment: I dropped on an edit re: your event log message comment.


$Ax=0 \equiv x=0 \implies \exists A^{-1}$?

Question: Question:

Let $A\in \Bbb R^{n\times m}, \operatorname{Rank(A)}=m$ and consider $V=\{v_1,v_2,\dots,v_r\} \subset \Bbb R^m$. Prove that $$V \,\,\text{is}\,\, L.I. \iff  AV=\{Av_1,Av_2,\dots,Av_r\} \,\,\text{is}\,\,  L.I$$

Attempt:
I couldn't do the $\implies$ part so I was trying to do the $\impliedby$ part.
$\alpha_1 Av_1+\alpha_2 Av_2+\dots+\alpha_r Av_r =0 \iff \alpha_i=0 \forall i=1,\dots,r.$
$\alpha_1 Av_1+\alpha_2 Av_2+\dots+\alpha_r Av_r =0\iff A(\alpha_1 v_1+\alpha_2 v_2+\dots+\alpha_r v_r)=0$
So if I can multiply by the inverse of $A$ this part should be done, but I don't even know if I have a square matrix.
Comment: Since rank of $A$ is $m$, you know that $n\ge m$. You also get an injective linear transformation, which allows you to define an inverse from the domain to the image under the linear map. So it's a well defined inverse if you restrict the range to the image of the map. This is the same thing as saying it's injective. Then your result does follow.
Comment: Don't think about inverses. As the previous comment suggests, the rank condition should tell you that $Ax=0 \implies x=0$. Why?
Answer: Hint: Consider $A: \mathbb R^m \to \mathbb R^n$ the transformation associated with the matrix $A$. As the $\mathrm {rank} A = m$ then $\dim \mathcal Im (A) = m $ and $$\dim Ker (A) = m - m = 0 $$
Therefore $A$ is injective and it takes L.I. sets in L.I. sets.
Comment: Is there any way to prove this without the Rank-nullity theorem, or any interpretation of the matrix A as a linear transformation? I'm asking this because although I have studied those matters, my class haven't and so we can't use things like  that.
Comment: What can you use, because you just took all the linear algebra now.
Comment: Hmm can't I say that $\alpha_i=0 \implies \sum \alpha_i v_i=0$ and as $\alpha_i=0$ is equivalent to $\sum A(\alpha_i v_i)=0$,  $\sum A(\alpha_i v_i)=0 \implies \sum \alpha_i v_i=0$?


How php provide download from remote url (streaming)?

Question: I have to provide a download from a remote url where I dont know the file size.
The problems I had so far

I dont know the file size
Large file about 100 mb
When I provide download for user with CURL/readfile/... then PHP wait as long the ful file and then shows Download Window.

How can I provide a part, stream, chunky downloader?
I want to do something like on phpmyadmin - if you download a sql export - then it streams also.
Thanks in advance.
Answer: Streaming is normally done using a small buffer. Lets say you had allow_url_fopen set to true:
$file = fopen('http://example.com/large-file.bin', 'rb');
while (($content = fread($file, 2048)) !== false) { // Read in 2048-byte chunks
    echo $content; // or output it somehow else.
    flush(); // force output so far
}
fclose($file);

Comment: Hi arxanas Thanks you for your idea. This looks good, but if call the script then in load as long as the file has loaded the whole size. This is not what I want, it has to start after a few seconds and then download to user and streaming.
Comment: @user1509034 From my understanding, that's what this script does. However, one may want to manually `flush()` after each `echo`, so I've added that.
Comment: ok i added also the flush-method. But thats strange - I started the script again and its loading for more than two minutes and nothing outputs and no download windows is shown to start downloading. Did I forget something?


group by 2 columns python

Question: I have a dataframe of shape :
 id | V
 1    0
 2    1
 3    0
 4    0
 1    0
 2    0
 4    1

where V is only 1 or 0 and id can have duplicates. What i want is for each id to count 0s and 1s. Example above would be
    1 : ('0':2,'1':0)
    4 : ('0':1,'1':1)
    3 : ('0':1,'1':0)
    2 : ('0':1,'1':1)

i don't care about the format of the result this is just an example. It could be a dataframe with 0 and 1 as columnns or whatever.
Any ideas?
Comment: I've guessed the `pandas` tag. Please change if `pandas` is incorrect, but include a tag for the framework as `dataframe` is ambiguous.
Comment: `('0':2,'1':0)` is not a valid python object, do you mean `{'0':2,'1':0}`?
Answer: You can use the value_counts method.
Example:
df.groupby("id").V.value_counts()

Answer: To get the Json format. You can do this.
df.groupby(['id','V'])['V'].count().unstack().T.fillna(0).astype(int).to_json()

Output:
{
  "1":{"0":2,"1":0},
  "2":{"0":1,"1":1},
  "3":{"0":1,"1":0},
  "4":{"0":1,"1":1}
}

group by 2 columns python


For any i.i.d. $X_n$ it follows $\lim_{n\to\infty}X_n/n=0$ pointwise?

Question: Let $X_n$ denote a sequence of i.i.d. random variables and $Y_n=X_n/n$.
$Y_n$ converges pointwise towards Y if
$~~~{\displaystyle \lim _{n\to \infty }Y_{n}(\omega )=Y(\omega ),\,\,\forall \omega \in \Omega}$,
where $\Omega$ is the sample space of the underlying probability space over which the random variables are defined.
It seems trivial that $\lim_{n\to\infty}X_n(\omega)/n=0$, $\forall \omega \in \Omega$ and i.i.d. distributions of $X_n$.
Then, also all other kinds of convergence are true. What do I miss?
I'm confused by the comments of experienced guys in this post:
Proving almost sure convergence
Comment: Your definition of pointwise convergence is correct, we do need $\lim_{n \ra \infty} X_n(\omega)/n = 0$ for all $\omega$, it's just that in general $X_n(\omega) \ne X_m(\omega)$.  In fact, this is what allows there to be additional randomness between the $X_n$.
Comment: It is not trivial that $\lim_{n\to\infty} X_n(\omega)/n$. Can you tell use more about why you think it is trivial? What would be the $\epsilon-\delta$ proof? If you make your reasoning more clear, we can help better explain where it went wrong.
Comment: I seems true that for all $\omega$ and $\varepsilon>0$ there's a fixed $N$ so that $|X_n(\omega)/n - X_m(\omega)/m|<\varepsilon$. As $X_n(\omega)=X_m(\omega)$ and these are real finite numbers I can choose for any $\omega$ the constant $N$ large enough so that the condition for convergence is true. So, one of my assumptions must be wrong, but which one?
Comment: Why is $X_n(\omega) = X_m(\omega)$?  This seems to violate your assumption that $X_n$ and $X_m$ are independent.
Comment: I see, so the definition of pointwise convergence I state above applies only to sequences that are functions of the same $\omega$, and there's no additional randomness between the $X_n$ allowed. I think my misunderstanding was, that altough the $X_n$ are independent the equation is true for the same outcome $\omega$.
Comment: Not sure but $X_n = n$ ?
Comment: @BCLC Sorry, "... i.i.d. distributions of $X_n$" should be "... i.i.d. $X_n$", which rules out any dependence on $n$.
Answer: Here is an example for iid variables where $X_n(\omega)/n$ does not converge to zero.
Suppose that $X_n$ are iid copies of the St. Petersburg random variable. That is, you repeatedly flip a coin until the result is heads, and let $X=2^{\text{# flips}}$.
I claim that with probability one, $X_n(\omega)/n$ will not converge to zero. To show this, I will show that $X_n(\omega)/n\ge 1$ will occur infinitely often with a probability of one.
For any $n$ in the range $2^k$ to $2^{k+1}-1$, we have
$$
P(X_n/n\ge 1)=P(X_n\ge n)= P(X_n\ge 2^k)=P(\hbox{# flips}\ge k)=2^{-(k-1)}
$$
Therefore, the probability that all of the numbers $X_n/n$ in the range $2^k$ to $2^{k+1}-1$ are less than one is at most
$$
P\left(\bigcap_{n=2^k}^{2^{k+1}-1}\{X_n/n<1\}\right)\le (1-2^{-(k-1)})^{2^k}=\left(1-\frac{2}{2^k}\right)^{2^k}\approx e^{-2}.
$$
so the probability that at least one of the $X_n/n\ge 1$ occurs is $1-e^{-2}\approx 86\%$. Therefore, in each of then intervals $[2^k,2^{k+1})$, there is at least an $86\%$ chance that there will be a variable $X_n/n\ge 1$. This these events are all independent, in the long run, it will occur infinitely many times.

It turns out that the same thing will happen whenever $X$ has infinite expectation. The intuition is that having a large expectation increases the chance of $X$ being large, so it turns out infinite expectation implies $X_n$ will actually be larger than $n$ infinitely often.
Comment: Thanks, very clear. The only thing that still puzzles me is how can you type so fast to give the answer to quickly?
Comment: @Its_me Haha, I am fluent in conversational LaTeX now after much practice.


how to synchronize time on farm of windows 2003 servers?

Question: I would like to load balance a group of windows 2003 servers.
They are not on a domain, and I am not using active directory.
I would like the synchronize the time for these boxes.
What is the best way of doing this?
Thanks!!!
Answer: net time /setsntp:pool.ntp.org
Reference
Note: This does not work for domain-joined computers.


Pros and Cons of Combining CSS/JS files or loading contextually?

Question: I am building an application in Drupal 7.
There is one common CSS file A.css with 1000 lines of code. There are other 5 CSS files(B.css,C.css .... F.css) with 100 lines each. I want to load the other 5 files contextually(only on the pages they are needed).
Regarding pagespeed, what are the pros and cons of combining all those CSS files into one or loading them separately(contextually) ?
AFAIK, If I load them contextually, then the weight of those 5 files will be avoided in the pages they are not required. But I am not sure how Drupal's aggregation works. There are two possibilities I can think of.

When B.css is loaded contextually, the aggregated file will contain A.css + B.css into one file. Lets call it X.css. By this logic, when C.css is loaded, the aggregated file will contain A.css + C.css. Let's call it Y.css.  But since X.css and Y.css are two different files, this will not utilize browser's caching and will make http requests each time.
When B.css is loaded contextually, A.css and B.css will load separately. And similarly C.css will be loaded separately when needed. By this logic, A.css will be cached. Also B.css and C.css will be cached after being loaded once.

Which way it works(1 or 2)? How do I control it ?
Answer: As Drupal documentation says here: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme,
Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load every assets on every page, because it slows down front-end performance.
You don't need to worry about loading libraries (CSS/JS) contextually. Drupal can load individual libraries for a certain block, or when a certain node type is being displayed. That's the purpose of the [theme-name].libraries.yml file, you can mention the specific blocks and page in there and tell it load the required library for that part.
You can attach the library to all pages, to specific Twig templates, or to a render element in a preprocess function.
For instance for a maintenance page:
maintenance-page:
 js:
  js/mobile.install.js: {}
 css:
  theme:
   css/maintenance-page.css: {}
 dependencies:
  - system/maintenance
  - thunder_admin/global-styling

Or for certain blocks or part of your page:
vertical-tabs:
 css:
  component:
   css/components/vertical-tabs.css: {}
dropzonejs.widget:
 css:
  component:
   css/components/dropzonejs.widget.css: {}

You can also use hooks like THEME_preprocess_HOOK() function in the .theme file. For instance, if you want to attach JavaScript to the maintenance page, the "HOOK" part is "maintenance_page", and your function would look like this:
function fluffiness_preprocess_maintenance_page(&$variables) {
    $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
}

Answer: AdvAgg's bundler sub module does a good job of balancing the browser cacheabilty (no aggregation) vs faster payload (all aggregated). For CSS when using HTTP/1.1 a value of 2 will give the fastest page rendering times; HTTP/2 doesn't have a real penalty so using a value of 15 is better.
http://www.webpagetest.org/ with the Connection set to mobile edge as well as https://developers.google.com/speed/pagespeed/insights/ is how to measure frontend performance. See https://www.drupal.org/node/2493801 for how AdvAgg is currently used for drupal.org.


Border-Radius and Shadow on ImageView

Question: I want to apply a border-radius and a shadow in JavaFX.
In CSS3 it would be:
box-shadow: rgba(0,0,0,0.8) 0 0 10px;
border-radius: 3px;

Now I want this in JavaFX, but even the border-radius is not working in the JavaFX Scene Builder. Here is a screenshot of my problem:

(source: rapid-img.de)
On the screenshot you can see that I use:
-fx-border-radius: 10 10 10 10;
-fx-background-radius: 10 10 10 10;

Comment: For the box-shadow I found the following solution: -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,1) , 5, 0.0 , 0 , 1 );
Answer: Use the following css to get a drop shadow:
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.8), 10, 0, 0, 0);

See the JavaFX CSS Reference guide for details.
To get the border in addition to the drop shadow, place your ImageView containing your Image in a StackPane.  And apply the effect css above to the StackPane, in addition to a background and padding on the StackPane.
For example the css below applied to the StackPane containing your ImageView will provide a red border around your image:
-fx-padding: 10;
-fx-background-color: firebrick;

If you want the background defining your border curved at the edges, then use:
-fx-background-radius: 5;

That gets you an image like below where your image is enclosed in a shadowed border:

If you want to actually round the image itself, it's a bit trickier.  You need to apply some code to:

Clip the image to a rounded rectangle.
Snapshot the clipped image.
Store the snapshot image back in the ImageView.
Remove the clip from the ImageView.
Apply the drop shadow effect to the ImageView.

Then you can get something like below:

Some code for that "BatmanLost.java":
import javafx.application.Application;
import javafx.fxml.*;
import javafx.scene.*;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.*;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import java.io.IOException;

public class BatmanLost extends Application {

    class WingClipper {
        @FXML
        private ImageView imageView;

        @FXML
        public void initialize() {
            // set a clip to apply rounded border to the original image.
            Rectangle clip = new Rectangle(
                imageView.getFitWidth(), imageView.getFitHeight()
            );
            clip.setArcWidth(20);
            clip.setArcHeight(20);
            imageView.setClip(clip);

            // snapshot the rounded image.
            SnapshotParameters parameters = new SnapshotParameters();
            parameters.setFill(Color.TRANSPARENT);
            WritableImage image = imageView.snapshot(parameters, null);

            // remove the rounding clip so that our effect can show through.
            imageView.setClip(null);

            // apply a shadow effect.
            imageView.setEffect(new DropShadow(20, Color.BLACK));

            // store the rounded image in the imageView.
            imageView.setImage(image);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader loader = new FXMLLoader(
            getClass().getResource(
                "batmanlostinthemix.fxml"
            )
        );
        loader.setController(new WingClipper());

        Pane batman = loader.load();

        stage.setTitle("Where's Batman?");
        stage.setScene(new Scene(batman));
        stage.show();
    }
}

With some FXML "batmanlostinthemix.fxml":
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="313.0" prefWidth="477.0" style="-fx-background-color: azure;" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2">
  <children>
    <ImageView fx:id="imageView" layoutX="29.0" layoutY="44.0" fitHeight="224.0" fitWidth="400.0" pickOnBounds="true" preserveRatio="true">
      <image>
        <Image url="http://collider.com/wp-content/uploads/lego-batman-movie-dc-super-heroes-unite-1.jpg" />
      </image>
    </ImageView>
  </children>
</AnchorPane>

Comment: If you're reading this, make sure to scroll down to Sayka's answer using ImagePattern instead of conditional image clipping: https://stackoverflow.com/a/56303884/7676920
Comment: Wow great work thank you... I feel a bit sad that JavaFX don't support rounded corners for images nativly. Maybe in the next version =)
Answer: If you use the answer that jewelsea provided, then make sure to test first whether or not clipping is supported:
Platform.isSupported(ConditionalFeature.SHAPE_CLIP)

I try to avoid conditional features unless I have to use them. In my case, I wanted to make a picture round. So an alternative would be to use a Circle instead of an ImageView:
Circle circle = new Circle(14);
ImagePattern pattern = new ImagePattern(myImage);
circle.setFill(pattern);

The circle can be enhanced to use a shadow if supported:
if (Platform.isSupported(ConditionalFeature.EFFECT)) {
    circle.setEffect(new DropShadow(8, Color.rgb(0, 0, 0, 0.8)));
}

Answer: Thanks martin for pointing ImagePattern

Rectangle rectangle = new Rectangle(0, 0, 280, 180);
rectangle.setArcWidth(30.0);   // Corner radius
rectangle.setArcHeight(30.0);

ImagePattern pattern = new ImagePattern(
    new Image("file:images/mustang-gt.jpg", 280, 180, false, false) // Resizing
);

rectangle.setFill(pattern);
rectangle.setEffect(new DropShadow(20, Color.BLACK));  // Shadow

Note that here Iam resizing the image to match the size of the rectangle during its load to ensure smoothness.

Border-Radius and Shadow on ImageView


MYSQL & PHP calculate total hours in specific date and exclude overlaps hours

Question: I have a MYSQL table for tasks where each task has a date, start time,end time and user_id. I want to calculate total number of hours on specific date.
Table Structure
CREATE TABLE tasks
    (`id` int,`user_id` int, `title` varchar(30), `task_date` datetime, `start` time, `end` time)
;

INSERT INTO tasks
    (`id`,`user_id`, `title`,`task_date`, `start`, `end`)
VALUES
    (1,10, 'Task one','2013-04-02', '02:00:00', '04:00:00'),
    (2,10, 'Task two','2013-04-02', '03:00:00', '06:00:00'),
    (3,10, 'Task three.','2013-04-02','06:00:00', '07:00:00');

MYSQL Query
select  TIME_FORMAT(SEC_TO_TIME(sum(TIME_TO_SEC(TIMEDIFF( end, start)))), "%h:%i") AS diff
FROM tasks
where task_date="2013-04-02"

The result am getting is "06:00" Hours which is fine, but I want to exclude the overlap hours. In the example I gave result should be "05:00" Hours when the hour between 3-4 in the 2nd record is excluded because this hour is already exist in the 1st record  between 2-4.

1st record 2=>4 = 2 Hours
2nd record 3=>6 = 3 hours 3-1 hour=2 (The 1 hour is the overlap hour between 1st and 2nd record )
3rd 6=>7=1

Total is 5 Hours
I hope I made my question clear. Example http://sqlfiddle.com/#!2/05dd8/2
Comment: Is it possible for there to be a gap between tasks?
Comment: What would the desired result look like? Also, it's often better to store date and time as a single entity
Comment: @PatrickQ yes it is possible (i.e TaskA 04:00 - 06:00, TaskB 07:00 - 08:00) and in this case the total will be 3 Hours because from (04:00 - 06:00) is 2 Hours and (07:00 - 08:00) is 1 hour.
Comment: @Strawberry yes you are right to store in single entity, but it won't makes any difference. The desired result for the Example I gave is 5 Hours.
Comment: This might be something better done in code. So write a query that simply returns the start and end time for each task. Loop through the result array, and for each row, add the difference between `start` and `end` into a `$totalHours` variable. Then, if the difference between the current `end` and the next `start` is negative, subtract that value from `$totalHours`.  If it's possible that tasks don't always start right on an hour (for example, starting at `5:25`), then it may be better to convert to seconds before calculating the difference.
Answer: Here is an idea that uses variables (in other databases, CTEs and window functions would make this much easier).  The idea is to first list all the times -- starts and ends.  Then, keep track of the cumulative number of starts and stops.
When the cumulative number is greater than 0, then include the difference from the previous time.  If equal to 0, then it is the beginning of a new time period, so nothing is added.
Here is an example of the query, which is simplified a bit for your data by not keeping track of changes in user_id:
select user_id, TIME_FORMAT(SEC_TO_TIME(sum(secs)), '%h:%i')
from (select t.*,
             @time := if(@sum = 0, 0, TIME_TO_SEC(TIMEDIFF(start, @prevtime))) as secs,
             @prevtime := start,
             @sum := @sum + isstart
      from ((select user_id, start, 1 as isstart
             from tasks t
            ) union all
            (select user_id, end, -1
             from tasks t
            )
           ) t cross join
           (select @sum := 0, @time := 0, @prevtime := 0) vars
      order by 1, 2
     ) t
group by user_id;

Here is a SQL Fiddle showing it working.
Comment: you are genius bro, thanks it worked as expected (:, but my question is there another way to do it without using nested select query ?
Comment: @Hadi.M There is a way, but it's slower, and no less complicated!


How to implement and install Icomoon and Fontello icon packs in Drupal 7?

Question: I am trying to get Fontello and Icomoon icon packs installed properly.
I look in the backend and it says import for Fontello and Icomoon.
I have downloaded the packages, but importing creates an error.
I have manually downloaded and extracted them, put them in my libraries and:
Renamed folder: Fontello

And
Renammed folder:  Icomoon

But not found under status report, not even as missing. I have installed the Icon API module and enabled it.
Additionally, Fontawesome installed correctly and is showing ok in status report but it stil shows this error:
The Font Awesome library could not be found.Please make sure that     fontawesome was download & extracted at sites/all/libraries/fontawesome directory.Please check README.txt for more details.

Answer: Ok, got it figured out.

Go to Fontello website.

Drag and drop Icons you need in the box on top.

Save file as Zipped, don't do any renaming or extracting.

Go to admin/config/media/icon/import

Give it a title and import the zipped file you just downloaded.

The icons will then show up on the drop down when adding them to articles or wherever.
Additionally, the help files for Fontello are here.
Comment: Not sure if that is changed in the Drupal 7 version, but I am unable to use a zip file. Must be tar, bz, etc...
Answer: Are you using the Icon API modules for Fontello and Icomoon?  This should be easy to set up.
First you install Icon API module, then the provider modules (linked above). Then you go the respective websites (http://www.fontello.com/ and/or https://icomoon.io) and select the icons you need for your project. Basically you create an own "font" with this selection and download it as an archive. Which is the one you upload in the import dialog of the Icon API configuration page (admin/config/media/icon).
Comment: Just saw you figured it out already. Good!
Comment: yes I installed both modules, not clear from what URL to download and then import files from


Unable to upload large files (>50mb) to Amazon S3 from D7 on EC2

Question: I'm trying to configure Drupal to upload large videos (eventually goal is ~300mb, but currently testing with ~50mb files) to S3 through my Drupal site running on an EC2 instance.
I have configured and tried both the Amazon S3 and Storage API modules. When trying to upload a small file around 5mb, everything is fine and works perfectly. However, when I try with a large file, I receive the following error:

Warning: filesize(): stat failed for storage-field-storage-test://[FILE NAME].mp4 in file_save() (line 601 of /var/www/includes/file.inc).

This error is the same for both the Amazon S3 and Storage API modules.
It turns out that the large videos are not being uploaded to S3, which explains the error message.
I am able to upload files directly to S3 okay and I am able to upload large files to local storage just fine as well (the PHP upload limit is set well above what I'm trying). What I don't understand is what could be causing the failure with the large file sizes between Drupal and S3. Any suggestions?
Comment: You need to increase `post_max_size`, `upload_max_filesize` and `memory_limit` (or what these parameters are called in your hosting). Set them all to 100MB or so. When you do, it will become a Drupal question. unless you can't, and they have to stay below 50MB - then tell us what they are and that you are looking for workaround.
Comment: @Mołot Thanks, that led me in the right direction. The `upload_max_filesize` argument wasn't specified in my php.ini. It's curious that I was able to upload large files directly the EC2 instance, but transferring them to S3 failed.
Comment: Sometimes scripts may modify these from within scripts... certainly receiving end developed by Amazon was able to do that on Amazon ;)
Answer: As pointed out in the comments, this ended up being a PHP config issue.
While I had set the post_max_size and memory_limit arguments to 1GB, the upload_max_filesize was not set at all. Setting this to 1GB in the php.ini file as well resolved the problem.


Extract hidden comment content preceding a specific rule or token (Antlr, Java)

Question: I am new to antlr and java so this may be a trivial question (hopefully!). I am using antlr 3.4. I have a grammar for the lexer:
lexer grammar MyLexer;

options {
  language = Java;
}
COMMENT:
    ( '//' ~('\n'|'\r')* '\r'? '\n'
    | '/*' .* '*/'
    ) {$channel=HIDDEN;};

WS: (' '
     | '\t'
     | '\r'
     | '\n'
     ) {$channel=HIDDEN;};
COLLECTION:    'collection';
BRACE_OPEN:    '{';
BRACE_CLOSE:   '}';

and another for the parser:
parser grammar myParser;

options {
  language = Java;
  tokenVocab = myLexer;
}

collection_def
scope {
    MyCollection currentCollection;
}
@init {
    $collection_def::currentCollection = new MyCollection();
}
@after {

    // There should be a comment preceding this rule. How to get the content of that comment into the commentContent variable?
    $collection_def::currentCollection.setDescription(commentContent);

    ...
}
  : COLLECTION BRACE_OPEN
      ...

    BRACE_CLOSE;

The lexer sends comments to the hidden channel. But I want the parser to extract the text contained in the comment that precedes a specific rule (or a specific token, since the COLLECTION token only appears in the rule above).
For example, I want this input:
/* Text describing the collection */
collection {
  item 1;
  item 2;
}

to be parsed to a MyCollection object with its description member variable set to "Text describing the collection".
How can I do this?
Comment: @BartKiers - This is part of a larger codebase which uses antlr3 and porting it to antlr4 would be additional work. However if you have an answer that is antlr4 specific I'd also like to hear it.
Comment: Why ANTLR3 and not the new ANTLR4?
Answer: The token stream has all the tokens, included those on the hidden channel. Every token that you get from the parser result (e.g. through tree.getToken() if you're using output = AST) knows its position in the token stream (Token.getTokenIndex()). That's the information you need to be able to locate and read the hidden token(s) preceding your token.
All that's left for you to do is get all this info to the place where you need to use it. One possible way to do this is get the tokens list (via CommonTokenStream.getTokens() if you use a CommonTokenStream between lexer and parser) and pass it to whatever method is doing the processing of the comments, or do some post-processing of the result to add the info to it.


Pick Values from JSON Object Where Keys in Typescript Type

Question: I have a the following type:
interface User {
  email: string;
  name: string;
}

...and the following react component:
const MyComponent = <Values extends object>({ values }: { values: Values }) => {
  console.log(values);
  return

}

Let's say I use MyComponent with the User interface, and so I'm able to pass values to it. The question is: how do I modify the values JSON object being passed to pluck out any properties in it that are not present in the generic type Values? In other words, if I pass the object:
{
  email: 'firstname.lastname@example.com',
  name: 'Some name',
  foo: 'bar'
}

I need the console.log(values) in the component to log the object without foo: 'bar' in it.
Comment: You can't, types don't exist at runtime.
Answer: Types don't exist at runtime Typescript compiles to javascript.


I am a bit confuse about running a regression

Question: I am a bit confuse about running a regression. Independent Variables are as:
X1 = Profitability Index
X2 = Operational Index
X3 = Cost per employee
X4 = Leverage Ratio
I am confused that can I use indexes and as well as single variables as independent variables in the regression.
Clarification needed!
Thanks
Comment: Could you give us some more details about what you are trying to do and your data?
Answer: I am a bit unsure of what you mean by single variables - but I assume that you are referring to, on one hand, variables that consist of multiple variables, and, on the other hand, variables that have not been put together with other variables.
If the above is the case, then yes, you can both use index variables as well as single variables.
However, of cause you have to be aware that you cannot use any single variables that are part of any of the index variables, as this will bias your results and possibly overestimate the effect of some variables.


UNION ALL versus CONNECT BY LEVEL for generating rows

Question: I was wondering which is a better/faster/more efficient way of turning arbitrary strings into columns:
UNION ALL
SELECT my_field,
       CASE WHEN my_field = 'str1'
            THEN ...
            ...
       END,
       ...
FROM (
       SELECT 'str1' AS my_field FROM DUAL
       UNION ALL
       SELECT 'str2' AS my_field FROM DUAL
       UNION ALL
       SELECT 'str3' AS my_field FROM DUAL
     ),
     ...

CONNECT BY LEVEL
SELECT CASE WHEN rowno = 1
            THEN 'str1'
            ...
       END AS my_field,
       CASE WHEN rowno = 1
            THEN ...
            ...
       END,
       ...
FROM (
       SELECT ROWNUM rowno
       FROM DUAL
       CONNECT BY LEVEL <= 3
     ),
     ...

I'm inclined to go with the UNION ALL version if only because it makes the outermost SELECT simpler:  I don't have to do a second CASE statement to get the desired string values.  It also is more readable to see WHEN my_field = 'str1' rather than WHEN rowno = 1.  The only reason I ask about the CONNECT BY LEVEL version is because it was suggested in Example of Data Pivots in SQL (rows to columns and columns to rows) (see the "From Two rows to Six rows (a column to row pivot)" section).
I have only SELECT access to the Oracle database I'm using, so I cannot run EXPLAIN PLAN.  I have also tried to use WITH ... AS before, too, without luck.
Answer: I think you're confusing the purposed UNION ALL and CONNECT BY methods used in "Example of Data Pivots in SQL (rows to columns and columns to rows)"
The UNION ALL in your question is used to transform multiple rows with a single column into a single row with multiple columns:
label, 1, val1
label, 2, val2
label, 3, val3

into
label, val1, val2, val3

The CONNECT BY sub-query is used to transform a single row with multiple columns into mutiple rows with single column, so it uses as generator sub-query to multiply the existing data set:
label, val1, val2, val3
+
1
2
3

result into:
label, 1, val1, val2, val3
label, 2, val1, val2, val3
label, 3, val1, val2, val3

transformed into:
label, 1, val1
label, 2, val2
label, 3, val3

Answer: I would use connect by for any but the most trivial number of rows. Not having explain plan is a pain though ... you're really having your hands tied there. I'd be really keen on knowing what the optimiser's estimate of cardinality is.
Comment: Why would you choose `CONNECT BY`?  Is it generally faster than `UNION ALL`?
Comment: If I was generating 100 rows, or needed to vary the number of rows generated programatically, then connect by would be much easier. If I knew I always wanted six rows though I'd use UNION ALL. You might also consider having an index-organized table of integers you can use for this stuff.


Strategy for geometric die guessing game

Question: The first day of statistics class, we played a betting game to visualize the basics of probability distributions. It worked like this:

The teacher begins by rolling a die repeatedly until the number is not six.
The teacher calls out the number of the die.
At every iteration of this round, the teacher offers the option of stopping. At each iteration, every student gains 1 point unlesss he stops, after which he can gain no points for the iteration.
If the number is six, all remaining students receive a zero for the iteration.

We repeat for 30 rounds. Score distributions appeared approximately Normal. Needless to say, side-by-side histograms showed that girls consistently outperformed boys (the score difference was in the ballpark of 5).
Apparently boys tended to "hold on" to their scores too long, because then they'd have received a lot of zeroes. Some students committed the gambler's fallacy, assuming that a 6 was due after a while.
What would be the ideal strategy for playing this game?

Edit:
There was a small misunderstanding. Yes, points are banked, and each round can only add points. Every player chooses only for himself whether to stop and keep the points or to risk a 6 and a 0.
Comment: To clarify- do you "bank" points over the rounds? I.e. if you get 3 points in the first three rounds, then "stop" before round 4, you get no points for the fourth round but your end score raises by three and you can start gaining more points again in round 5?
Answer: This is one variant of a class of games sometimes referred to as 'Pig' games or jeopardy dice games, though individual games have other names. You may have seen the game Pass the Pigs, for example, which is a game in this genre. Optimal play for the main game (Pig itself) has been looked at, and many people have discussed optimal play for Pass the Pigs (but it's tricky since the probabilities are not determinable by symmetry arguments -- indeed it depends on the surface one plays on and the wear on the pigs as well as any manufacturing differences from pig to pig).
Optimal play depends on what it is you want to optimize (in Pass the Pigs the aim is to be the first to accumulate a target number of points -- in the early game that's going to be close to expectation-maximizing, but in the end-game the strategy may be quite different).
However, let's say we want to maximize the expected score. Further, let's think of just one of the students playing (what happens to everyone else doesn't matter, as in this calculation we're not specifically trying to score higher than another player, just maximize expected score). What's her best strategy?
Imagine in some round that the player has already got some bank of points at risk, $b$ and has to decide whether to stop or play that turn. (Points from previous rounds are not at risk in this game.)
If the student plays, then with a chance of 5/6 the student gains $1$, and with a chance of 1/6 the student gains $-b$ (i.e. loses those points).
The expected return for playing is $(5-b)/6$. This is positive if $b<5$ and negative if $b>5$ and zero when $b=5$.
If the student holds (stops), the expected return is $0$.
So to maximize expected points:
If you have 4 or fewer points at risk, don't stop.
At 5 points an expectation-maximizer is indifferent to stopping. (By contrast, a slightly risk-averse player would stop at 5, a slightly risk-seeking player would play one more round.)
At 6 points, it's against our expectation-maximizer's interest to keep playing.
If you had some other thing you wanted to optimize, you might choose a different strategy.
Answer: In this answer also the two-player nature of the game is adressed, which is given already when you assume that your opponent can track your actions -- as it is usually the case in a classroom.
Preliminary considerations and single-player game
Let us denote the probability for getting $k$ points when you target $n$ points by $p_n(k)$. It is given by [*]
$$p_n(k) =  \left(\frac56\right)^n \delta_{kn} + \left(1-\left(\frac56\right)\right)^n \delta_{k0} $$
The expectation value when you target $n$ points is
$$E_n = \sum_k k \, p_n(k) \\= n \left(\frac56\right)^n$$
for which I obtain from Wolfram Alpha:

In a single player game, I would therefore expect to perform best by choosing the targets $n=5$ or $n=6$.
Two-player game
This is just a short explanation what one would do ... I've not done it for this game.
For reasons of simplicity, let us consider the following hypothetic version of your game. Before each "inner round", the players write down the targeted number on a sheet and hand it to the professor, who communicates each of these to the class. (Otherwise, it would be possible for players to change their initial decision according to the actions of the other players, which would make the whole thing more complicated.)
For solving the two-player case, let us first define the state $s$ in which the game can be by
$$s=(s_1, s_2, r)$$
where $s_i$ denoted the current "banked" or permanent points of player $i$ and $r$ the current round number. For each of those possible states, player one and two can target $k=1,2,\ldots$ points. For practical reasons, let us limit $k$ by 20, say.
Now the minimax theorem, the fundamental theorem for two-player zero-sum games, states that there exist an optimal mixed strategy which is denoted by $(p_1,\ldots,p_{20})$. It requests you to randomly choose one of the pure target point strategies $j$ with probability $p_j$.
Those strategies are obtained by solving a linear programming problem for a given payoff matrix $M_s$ in state $s$. Its entry $M_{s,k_1k_2}$ contains the probability for player 1 to win in state $s$ when he targets $k_1$ points and his opponent $k_2$ points. By solving the linear program, one further obtains the value $V_s$ of such a game state, which can be interpreted as the probability of winning the game in this state when both players follow the optimal strategy.
With this, one iterates over each state starting from the end of the game (after round 30) to the beginning. In round $r$, by knowing the winning probabilites for each state in round $r+1$ and by using the probabilities derived for the single-player version of the game, one can set up all corresponding payoff matrices in round $r$, and for each of them solve the linear program. By this, one finally arrives at round 1, the value of which is $\frac 12$ due to reasons of symmetry.
In summary, you gain the optimal mixed strategy for each of the possible states the game the be.
I'll stop here as I have no idea on your knowledge in game theory. If you have none, the former might be rather cryptic but nevertheless might give you a slight idea how to proceed. If you have some experience in game theory I can also add some mathematics.

[*] That might look a bit overkill here as the distribution is rather trivial in this case. However, a slight change of the game where you add the shown die points instead of 1 makes this more complicated approach neccessary.

EDIT: as an aside: I formerly solved a different version of the game, which is played by two players in rounds. They throw a single die on their own as often as they want and sum up the die points. At any time they can banke these points, but if a six is thrown all current points are lost and the other player has the turn. The player to have 50 or more points at the end of player two's turn wins the game.
For this setup, the non-simultaneous actions allows for a solution in pure strategies and also for a different solution technique, namely dynamic programming. On this page, you can find some excerpts of the optimal strategies I found (--in german language).


interpretation of Markov transition field

Question: Markov transition fields come from this article:
https://www.researchgate.net/publication/282181246_Spatially_Encoding_Temporal_Correlations_to_Classify_Temporal_Data_Using_Convolutional_Neural_Networks
They are quite well explained here: https://lazyprogrammer.me/convert-a-time-series-into-an-image/
M_kl (one element of the transition field) is then just the probability that we saw a direct one-step (i.e. Markovian) transition from q_k to q_l in the time series.
But the article states:
By assigning the probability from the quantile at time step i to the quantile at time step j at each pixel M_ij , the MTF M actually encodes multi-step transition probabilities of the time series. M_i,j||i−j|=k denotes the transition probability between the points with time interval k.
and
By scattering the first-order transition probability into the temporally ordered matrix, MTFs encode the transition dynamics between different time lags k.

I don't understand what is meant by these sentences because the transition matrix really just contains probabilities of transitions between quantiles of neighboring elements in the time series, i.e. number of steps is always considered to be 1 by definition so I don't get how it can be true that it "encodes the transition dynamics between different time lags k" - k is a difference between two timestamps in the time series. The k (number of steps to reach another quantile) is not taken into account in the definition of Markov transition field.
And actually it would make sense to me if it was taken into account and we would put into the Markov transition field the probabilities that one quantile changes into another in k steps. Why it isn't like that?
Comment: Maybe "probabilities that one quantile changes into another in k steps" doesn't really make that much sense in the context of Markov chains but maybe rather "probabilities that one quantile changes into another while passing the same number number of intermediate states (quantiles)". I just want to say that I would expect some definition that takes into account distance of each two points in the time series to be able to interpret the statement from the original article. I know my explanation is probably lacking due to my inexperience in this area.
Answer: Imagine you have three states, A B C, and your transition probability matrix looks like this:
  A  | B  | C
A .5 | .5 |  0
B .3 | .4 | .3
C  0 | .5 |  5

(e.g. from state A there's a .5 chance of staying in A and a .5 chance of transitioning to B)
It's easy to see that this encodes the probabilities for the three possible lag-1 transitions starting at A:

A -> A (p = .5)
A -> B (p = .5)
A -> C (p = 0)

The trick is that it you can calculate the lag-2 transition probabilities by multiplying together the lag-1 probabilities:

A -> A -> A: p = .5 * .5 = .25
A -> A -> B: p = .5 * .5 = .25
A -> B -> A: p = .5 * .3 = .15
A -> B -> B: p = .5 * .4 = .20
A -> B -> C: p = .5 * .3 = .15

Finally, if you just want to know the probability of being in state B two steps after being in state A, you simply add up the probabilities of all the chains of transitions that would get you there:
P(A -> ? -> B) = P(A -> A -> B) + P(A -> B -> B) = .45
Comment: Whoops, missed "field", sorry!
Comment: Thank you. That's quite useful to know but it doesn't really address the question because Markov transition field is something else than Markov transition matrix which you are explaining. Thanks anyway, it's always good to refresh the basics.
Answer: I did try some other interpretations. E.g. consider that the points i, j have a distance |i - j| between them and therefore calculate the probability of transition between the respective quantiles for the points in that number of steps (i.e. on the main diagonal there will be just 1s as the distance is zero).
Needless to say, so far I have had more success with the original definition (where the probability is always that one quantile changes into another in a single step) when the resulting field is employed into a simple machine learning model.