Does a function exists to make this set dense?

Question: Let $f \in L^2(\mathbb{R})$, then we can show that $\overline{\text{span}}\{f(t-a)\}_{a \in \mathbb{R}} = L^2(\mathbb{R})$ if and only if $\hat{f}(\xi) \neq 0$ almost surely, by using the uniqueness of the Fourier transform. I am wondering if we can relax this assumption? That is, does there exists $f \in L^2(\mathbb{R})$ such that $\overline{\text{span}}\{f(t-a)\}_{a \in \mathbb{Q}} = L^2(\mathbb{R})$ (now running over only rational numbers)?
Initially my (wrong) idea was to choose $f$ so that $\hat{f} = \mathbb{1}_{[0,1]}$. This would then say that if $g \in L^2(\mathbb{R})$ with $0 = \langle g, f(t-a)\rangle_{\mathbb{R}} = \langle \hat{g}, e^{-2 \pi i a \xi} \hat{f}\rangle_{\mathbb{R}} = \langle \hat{g}, e^{-2 \pi i a \xi}\rangle_{[0,1]}$. Since this holds for every $a \in \mathbb{Q}$ it in particular holds for all integers. Thus $\hat{g} = 0$ and hence $g = 0$. But this only guarantees being $0$ on $[0,1]$!
The second thing that comes to mind is since we know that if we had $0 = \langle g, f(t-a)\rangle$ for all $a \in \mathbb{R}$, then this would imply that $g = 0$ and hence we have $\overline{\text{span}}\{f(t-a)\}_{a \in \mathbb{R}} = L^2(\mathbb{R})$. If we only have the assumption that $0 = \langle g, f(t-a)\rangle$ for all $a \in \mathbb{Q}$ could we use the density of $\mathbb{Q}$ to extend conclude that $0 = \langle g, f(t-a)\rangle$ for all $a \in \mathbb{R}$?
Perhaps there is a simple function $f$ where this clearly holds, but nothing comes to mind. Thanks.
Comment: Doesn't the argument in the second paragraph work for any interval of length $1$?
Answer: The conclusion is valid for any dense subset $A$ of the real line.
Equivalently it remains to show that the functions
$$e^{-2\pi i a\xi}\widehat{f}(\xi),\qquad a\in A,$$ span a dense subset of $L^2(\mathbb{R}).$  Call the closure of this span by $V.$
Let $a\in \mathbb{R}.$ There exists a sequence $a_n\in A$ such that $a_n\to a.$ Then
\begin{equation}\|e^{-2\pi i a_n\xi} \widehat{f}(\xi)-e^{-2\pi i a\xi} \widehat{f}(\xi)\|_2\to 0 \ \ \ \  \ \ \ \ \ \ (*)
\end{equation}
Therefore the functions $e^{-2\pi ia\xi}\widehat{f}(\xi)$ belong to $V$ for any $a\in \mathbb{R}.$ Now we can use the fact that the conclusion is true for $A=\mathbb{R}.$
Proof of $(*)$:
$$\|e^{-2\pi i a_n\xi} \widehat{f}(\xi)-e^{-2\pi i a\xi} \widehat{f}(\xi)\|_2^2=\int\limits_{-\infty}^\infty |e^{-2\pi i(a_n-a)\xi}-1|^2\,|\widehat{f}(\xi)|^2\,d\xi \\ =
\int\limits_{-N}^N |e^{-2\pi i(a_n-a)\xi}-1|^2\,|\widehat{f}(\xi)|^2\,d\xi
+\int\limits_{|\xi|>N} |e^{-2\pi i(a_n-a)\xi}-1|^2\,|\widehat{f}(\xi)|^2\,d\xi \\ \le \int\limits_{-N}^N |e^{-2\pi i(a_n-a)\xi}-1|^2\,|\widehat{f}(\xi)|^2\,d\xi
+4\int\limits_{|\xi|>N} |\widehat{f}(\xi)|^2\,d\xi $$
For given $\varepsilon>0,$ choose $N$ such that the last integral is less than $\varepsilon/2.$ Once $N$ is fixed, the first integral tends to $0$ when $n\to \infty,$ as the functions $e^{-2\pi i(a_n-a)\xi}$ tend to $1$ uniformly in the interval $[-N,N].$


First Movement of Mozart's Horn Concerto no. 2, is it Sonata Form or Rondo Form?

Question: So, I have come across an atypically structured first movement in Mozart's Horn Concerto no. 2 in Eb and I'm wondering if it is Sonata Form or Rondo Form, because it seems to have some characteristics of both, it's like Mozart is blurring the line here. Characteristics typical of Sonata Form I see include:

A clear First and Second Theme(the Bb octaves are what divide those 2 themes)
Orchestral exposition before the Solo Horn(this is more specific to the Double Exposition Sonata Form of Concertos)
Second Theme is in the Dominant when the Solo Horn is playing and is in the Tonic in the Orchestral exposition(again more specific to the Double Exposition Sonata Form of Concertos
Minor key in what I would assume to be the start of the Development

But on the other hand, one big typical characteristic of Sonata Form I just don't see here is the presence of repeats, at least in the exposition. And in Mozart, it's even more typical to have a repeat of the Recapitulation and Development as well. This is making me think maybe it is a Rondo? After all, Rondos sometimes completely lack repeat signs and a Rondo with characteristics of Sonata Form is not uncommon, even in Mozart, just look at K 333, his Piano Sonata in Bb and you'll see what I mean. But then again, Rondo doesn't seem to be quite right here. So maybe it is a Continuous Sonata Form? No, that usually refers to Sonata Form without a clear division between the First and Second themes like in the Presto of Divertimento in D, and that's not what's happening here.
Here's the score(which I just happen to be arranging for Piano Solo):
https://ks.imslp.net/files/imglnks/usimg/2/27/IMSLP01492-Mozart_-_Horn_Concerto_No.2.pdf
And a video of a performance of the first movement:

So is this a Rondo with characteristics of Sonata Form or is it Sonata form without the repeats?
Answer: I would say this is a relatively standard sonata–concerto form. You're correct that Mozart normally repeats his expositions (and the developments/recapitulations) in sonata forms, but that's pretty rare in the sonata–concerto hybrid. Since the sonata–concerto begins with both an orchestral (tutti) exposition and then a solo exposition, there's really no need to repeat anything, because the exposition (or something like it) has already been stated twice.
Otherwise, I agree with your formal markers: clear first and second themes (both in tonic in the orchestral exposition, as was common for Mozart), a move to minor to begin the development, and then a brief orchestral statement to begin the recapitulation.


php inserir com formato datetime

Question: É o seguinte eu tenho 2 variáveis:
Variável data formato (aaaa/mm/dd):
$inserir_data = nl2br( addslashes($_POST['inserir_data']));

E um turno do tipo VARCHAR que contem 2 horas esta no formato (hh:mm-hh:mm):
$inserir_turno = nl2br( addslashes($_POST['inserir_turno']));

Utilizei isto para separar o turno em 2 variáveis e depois juntei a data normal com o turno para formar um date time e inserir na base de dados numa variavl do tipo date time:
$turno_separado = explode('-', $inserir_turno);

$hora_inicio = "$alterar_data $turno_separado[0]";
$hora_final  = "$alterar_data $turno_separado[1]";

O problema é que pelo que vejo está tudo correto mas ele não insere na base de dados na base de dados fica sempre (00-00-00 00:00:00)
Ajudem-me que eu não faço a mínima ideia do que se passa aqui será da forma como estou a inserir? devido ao facto de na base de dados estar datetime e ele nao reconhecer a variável?
Obrigado pela paciência!! Espero que me possam ajudar!
Comment: Talvez seria melhor trabalhar sempre com DATETIME no mysql ao invés de VARCHAR, e com a classe DateTime no PHP para extrair com o formato desejado. Fora que os turnos ficariam melhores em colunas diferentes, assim provavelmente parte da logica seria resolvido na query.
Comment: Mas foi vc quem desenvolveu a base de dados? Acho que esta a ir pelo caminho das pedras, sendo que mysql e php tem funcionalidades para data e hora que resolvem muita coisa sem precisar ficar se matando assim,  fora os problemas que vc vai evitar com erros de calculos. Mas faça como desejar, apenas estou dando uma sugestão ;)
Comment: Shider, não leve a mal, mas é mais fácil do jeito que fez porque já esta feito e porque é a unica forma que vc conhece, se conhecer a fundo o funcionamento de funções que trabalham com tempo real e não com CHAR ou STRING, vai perceber que na verdade você esta apenas tentando recriar a roda sem necessidade. Não é porque vc só conhece um caminho que isso o torna o melhor, trabalhar com das assim pode ser um grande problema. Desejo sorte com isso ai e se quiser depois dar uma olhada nas classes de "Date" do PHP e ver os exemplos talvez no futuro vc consiga refatorar seus códigos. Feliz 2018
Comment: php: http://php.net/manual/en/book.datetime.php - mysql: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html - Unix Time: https://en.wikipedia.org/wiki/Unix_time e por ultimo perguntas sobra comparar tempo: https://pt.stackoverflow.com/search?q=comparar+datas+%5Bphp%5D e https://pt.stackoverflow.com/search?tab=votes&q=comparar%20datas%20%5bmysql%5d
Comment: Não é do input, o tipo DATE só vai existir no mysql, a classe de nome DateTime do PHP vc vai usar pra comparar strings (o seu input) com o formato que veio do mysql dos campos tipo DATE.
Comment: Eu queria fornecer um exemplo, mas não sei bem o que fez até agora fica meio dificil imaginar por onde começar, pois inicialmente o seu problema é outro, mesmo que causado por trabalhar strings como se fossem datas. Não tem solução mágica, algumas coisas vai ter que refazer ou simplesmente arriscar no que já fez até agora e no futuro quando entender melhor o conceito de TEMPO refatorar/refazer seus códigos.
Answer: Tabela de exemplo
Primeiro vamos tomar como base a seguinte tabela criada no mysql:
+-------------------------+
|datetime_inicio datetime |
+-------------------------+
|datetime_fim    datetime |
+-------------------------+

Consertando o codigo atual
E agora fazer seu codigo funcionar (antes de sugerir qualquer melhoria!). O seu codigo apresentou apenas um pequeno erro na hora de executar. Aparentemente a variavel $alterar_hora estava indefinido (imagino que você queria usar $inserir_data). Fazendo essa alterar, o codigo ficou assim:
<?php

//formato ano/mes/dia ou YYYY/mm/dd
$_POST['inserir_data'] = '2018/1/1';
$inserir_data = nl2br( addslashes($_POST['inserir_data']));

//formato ano/mes/dia ou YYYY/mm/dd
$_POST['inserir_turno'] = '10:30-11:40';
$inserir_turno = nl2br( addslashes($_POST['inserir_turno']));

$turno_separado = explode('-', $inserir_turno);

$hora_inicio = "$inserir_data $turno_separado[0]";
$hora_final  = "$inserir_data $turno_separado[1]";

var_dump($hora_inicio);
var_dump($hora_final);

$conexao = mysqli_connect('host', 'usuario', 'senha', 'nome_banco');
mysqli_query($conexao, 'insert into teste (datatime_inicio, datetime_fim) values (\''
. $hora_inicio . '\',\'' . $hora_final .'\')');

//exibir erros na execução da instrução anterior (remover em produção).
echo mysqli_error($conexao);

O que tem de diferente em relação ao seu codigo são os escapes "\'" para permitir uma aspa simples fique dentro de outra aspa simples, ja que strings precisam estar entre aspas. Após algumas execuções do codigo acima, a tabela no banco ficará similar a:
+----------------------+--------------------+
|datetime_inicio       |datetime_fim        |
+----------------------+--------------------+
|2018-01-01 10:30:00   |2018-01-01 11:40:00 |
|2018-01-01 10:30:00   |2018-01-01 11:40:00 |
|2018-01-01 10:30:00   |2018-01-01 11:40:00 |
+----------------------+--------------------+

Melhorias
É claro que você poderia usar algo similar a essa tag <input type="datetime-local" name="bdaytime"> para pegar o datetime completo, e so validar no servidor.Embora isso não funciona em todos os navegadores (mas da para usar plugins que permitem isso).
Comment: Muito obrigado você salvou-me a vida muito obrigado pela paciência e desculpe o tempo perdido!! Obrigado mesmo Feliz Ano Novo!

php inserir com formato datetime


Variation on Views exposed filter

Question: I am working on a Drupal 7 site. One View on the site that lists hundreds of publications around a scientific theme has this great set of exposed filters in a bar at the top that allows researchers to search the publications. Unfortunately, the site owner and graphic artist went a little wild with another section, and designed this great set of filters that should bring up results in a View, but the filters aren't on a View page. Can the "exposed filters" for a View Page be placed on a different page altogether?
Thanks for your help!
Comment: Can you expand?  What do you mean the filters aren't on a view page?
Answer: Yes, make it a block. Assign it to a region on a particular page. When the user clicks the Apply button the view will be displayed.

Variation on Views exposed filter


map does not work on vector which i am trying to use

Question: I have the data as below
adsl <- structure(list(SUBGRPVAR1 = structure(c("F", "M", "M", "M", "F",
"F"), label = "Sex"), SUBGRPVAR2 = structure(c("Y", "N", "Y",
"N", "Y", "N"), label = "Completers of Week 8 Population Flag")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

# A tibble: 6 × 2
  SUBGRPVAR1 SUBGRPVAR2
  <chr>      <chr>
1 F          Y
2 M          N
3 M          Y
4 M          N
5 F          Y
6 F          N

which i would like to change to as below
# A tibble: 6 × 2
  SUBGRPVAR1 SUBGRPVAR2
  <chr>      <chr>
1 Total      Total
2 Total      Total
3 Total      Total
4 Total      Total
5 Total      Total
6 Total      Total

I would like to use the below map with the vector subgrpvarc, however when i do I get the error as object .x not found, i am not sure why it is not work. Please advice
subgrpvarc <- c("SUBGRPVAR1", "SUBGRPVAR2")

map(subgrpvarc, ~ adsl[[names(adsl)[match(.x, names(adsl))]]] <- 'Total')

Answer: I'm not sure if that was a good example for requesting the use of map. Here is a much simpler way to accomplish the same thing:
adsl[subgrpvarc] <- 'Total'

So I suppose you could say that "[<-" is implicitly "mapping" when given multiple column names. The "[[" function cannot take multiple arguments. If you try to give "[[" a vector of length greater than 1 it errors out:
adsl[[subgrpvarc]]
#----------------
Error in `vectbl_as_col_location2()`:
! Can't extract column with `subgrpvarc`.


Open link as modal form or normal form based on user role

Question: I wish to have a link 'Post Ad':
For anonymous user: a modal login form will be displayed to request log in.
For logged in user: a normal ad posting form.
I managed to use the ctools for modal login form, but i have no idea how to get the normal form to display. (Exception happens when open the normal form, an ajax http error occurred.)
How to achieve this without create two links?
Thanks!
Comment: Where does this "Post Ad" link show? In a menu, regular node, a view, a panel etc?
Comment: The Post Ad link can be in a menu or a regular link. It will show a Login Form for anonymous user, or a ad node form for logged in user.
Answer: You can look at Menu per Role module, ie link to login form for anonymous users, and link to normal form for authenticated users. another alternative would be to add a hook into the menu in your custom module and change your link based on user's status that way. You can look at this post for info and examples.


Have two players ever played twice on the same tournament in tennis?

Question: It sounds impossible, but I just noticed a very weird fact that caught my eye and interest.
Tomorrow (13th February) starts the main draw of ATP 500 Abn Amro World Tennis Tournament in Rotterdam.
However, the qualification of the tournament has already finished, where number 6 seeded player Aljaz Bedene beat Uzbek Denis Istomin in two sets 7-6(8) / 6-3
Now, after withdrawal from main draw of Roberto Bautista Agut Denis istomin took his place as an alternative/Lucky Loser. And surprisingly enough he plays against Aljaz Bedene in the first round of the tournament. Meaning, two players are playing twice the same tournament. Which is quite extraordinary in my opinion. Has it ever happened before?
Comment: As I already commented below, this happens more or less frequently. see this article: http://www.tennisabstract.com/blog/2015/10/19/lucky-losers-and-familiar-faces/
Answer: Yes. In the 2015 ATP World Tour Finals, Roger Federer and Novak Djokovic played each other both in the round-robin stage (where Federer won 7-5, 6-2) and in the final (where Djokovic won 6-3, 6-4). I'm guessing some more examples could be found in other instances of the Finals.
Answer: I wouldn't say this is something that happens frequently, but it does happen on occasion when someone that loses in qualifying rounds ends up getting into the main draw as a lucky loser - like the scenario you described in your question. That's generally the only way it can happen - I can't think of another scenario that would allow it to occur, actually. Only the round-robin format can typically produce that and only the World Tour Finals use that format - everything else is single elimination.
The problem with finding out when this happened and which players it involved is that there is no publicly accessible database that has all of this information in it - your best bet would probably be the Tennis Abstract website.
Comment: actually, the guy from tennisabstract wrote an article about this "phenomenon": http://www.tennisabstract.com/blog/2015/10/19/lucky-losers-and-familiar-faces/


IE8 weird issue with jQuery

Question: On this domain http://demo.acylo.com when you go to IE8 ... It loads up fine, but I'm using a jQuery script to show some buttons on hover... The problem is, right after you hover on that block of div, everything is going insane... It works fine on all the other browsers.
I tried adding float: left to that div and width: 100%, but it still doesn't work. Also in IE6/IE7 the arrows are not showing up, even if I added display: block on hover in jQuery
Comment: You have about a dozen different jQuery plugins running on that page; it wouldn't surprise me if some of them are interfering with each other. Try stripping your page down to the minimum functionality to help isolate the problem.
Comment: Seems to be a CSS issue more than anything else. Create a jsfiddle width the minimal code to reproduce the issue.
Comment: Could you post the code that is causing the problem?
Comment: @b01 you can check the source code
Answer: All IE browsers have this issue with jQuery. Especially cloning of element does not work in IE. There is a heavy use of cloning in jQuery and it works perfectly fine in all other browsers.
Custom code should be written, checking for the browser being used. Special code need to be written for IE only.

IE8 weird issue with jQuery


Strange characters after URL -> /#.UAfaBbTY-iE

Question: I'm not sure how it's happened, but on each page there are some characters appended to the URL, similarly to the following one:

http://example.com/rndsite/#.UAfaBbTY-iE

They seem to be the same for each page. Anybody know what is causing this?
Comment: Sounds like a browser plugin adding something to URLs for tracking purposes. Try disabling any installed browser plugins to see if you can isolate the problem
Comment: Are you redirected there even if you directly visit: http://example.com/rndsite page?
Comment: Yes I'm re-directed there no matter what I type in, and it happens cross-browser.
Answer: Do you have an AddThis widget on any of the pages?  This is a known issue with that widget.  to resolve change this portion of the snippet:
var addthis_config = {"data_track_addressbar":true};

WITH
var addthis_config = {"data_track_addressbar":false};

Comment: No problem.  I ran into this same issue before.  Nearly drove me insane.  Glad I could help.
Comment: I was having the same problem.It's not really an issue but it's very annoying! Thank you man!


Why does singing while standing sound different from singing while sitting?

Question: To my ears there is a difference in my voice's timbre if I sing sitting down compared to when I sing standing up (I realize this might sound a bit weird). In fact, I like the sound better when sitting down, and therefore I'd like to figure out what's making the difference (besides the obvious) in order to be able to control and recreate that sound regardless of how I sit or stand.
The only thing I can think of is that the body posture sitting down might create a different type of airflow pressure, but I'm really at loss for a good explanation.
Any hints/ideas, or do I simply have to accept that the only difference is that I'm sitting down?
Answer: It would be to do with the way your diaphragm and thorax changes shape in a sitting position. I think you're right about the pressure. When sitting, the pressure of your thorax (chest cavity area) moves lower down perhaps producing this timbre you like the sound of.
Answer: Your "sound" is affected by your posture through a) support and therefore airflow, and b) direct shaping of your mouth cavity and therefore resonance, and c) indirectly caused tension in other muscles/body parts involved in singing, such as tension in your jaw and/or tongue.
Singers, whether soloists or choristers, generally preferentially sing in standing position since that provides the least obstacles to singing well. Voice teachers almost invariably work with their students standing up, at least when learning the fundamentals of singing. However, opera singers will learn how to retain crucial elements of good vocal production in a variety of positions, including sitting, moving, even lying down.
It's also important to note that what one hears, while singing, of one's own voice, is tremendously affected by vibrations passing inside your body (e.g. jaw). In your situation, I would start by asking others and/or recording your voice and playing it back to first verify whether your sitting-down voice is indeed better than your standing-up one, since your perception of this may be an artefact.
If indeed your "sitting voice" is objectively better, I would suspect that there is something in your standing-up posture which is not right, i.e. where though standing up should be more conducive to singing well, you're doing something wrong which is getting in the way, a bad habit you don't fall into when sitting. Addressing this bad habit should then help you in any position.
As a singer myself, I've had to work on not standing too rigidly "upright" (I was actually bent backwards), on neither compressing my thorax nor having facial tension from lifting my jaw too low or too high. From tension in my tongue and jaw induced by keeping one hand rigid while standing. I've addressed these issues in part by various constructed exercises to move while singing, sing bent over and/or seated and/or leaning against a wall -- not good posture in and of themselves, but helpful to build awareness of and break bad habits.
So I'd go back to basics and follow (with a teacher or on your own) various guidance on how to sing upright with good posture and try to find what element you're missing. Part of this might involve standing up and sitting down and self-monitoring changes in individual elements of your posture and presence/absence of tension in different body parts while singing in both positions. What you're describing is unlikely to be a necessary or direct consequence of sitting vs standing, and much more likely to be an indirect consequence of how your body and brain have learned to interpret the instruction "sit well and sing" versus "stand well and sing".


What is the name of this inequality?

Question: Let $X_1, \ldots, X_n$ be a collection of nonnegative random variables. Then
$$
\max_i X_i \le \epsilon/2 + \sum_i X_i \mathbb{1}_{\{X_i > \epsilon/2\}}.
$$
Does this inequality have a name? What is it?
Comment: Note that this has nothing to do with probability theory. It is true when  $X_n$'s are real numbers, hence also for random variables. It has no name because it doesn't deserve one!.
Comment: @KaviRamaMurthy just because it's true in two different situations doesn't mean it doesn't have anything to do with one of those situations. Moreover, easily-verified does not mean undeserving of a name--I'm sure you can think of a few examples yourself. Finally, it has already been suggested that this inequality doesn't have a name.
Answer: I don't think this has a name. But it is a combination of some simple [but also unnamed] results.
Under the event $\max_i X_i \le \epsilon / 2$, then the inequality holds automatically.
So we may assume we are in the event $\max_i X_i > \epsilon / 2$.
We then have
$\max_i X_i \le \sum_i X_i \mathbb{1}_{X_i > \epsilon / 2}$ because the right-hand side equals $\max_i X_i$ plus some other nonegative addends.
Comment: No I get the proof, I'm just wondering if it has a name. I'll wait a little bit and just in case nobody else steps forward with one, I'll accept the previous part as an answer. Thanks.

What is the name of this inequality?


Is there a closed form for...

Question: I was working on an analysis question, and was wondering if there's a closed form for $\sum_{i=0}^{log(n)}(1/2^i)log(i)$? Unless I have made a mistake, I am trying to show that $n\sum_{i=0}^{log(n)}(1/2^i)log(i) \in \Theta(n)$.
Thanks!
Answer: You are interested in the sum
$$S(n) = \sum_{i=1}^n \dfrac{\log(i)}{2^i}$$
Note that we have $\log(i) < i$ and hence we have
$$S(n) < \sum_{i=2}^n \dfrac{i}{2^i} = \dfrac32 - \dfrac{n+2}{2^n} < \dfrac32$$
Comment: Ah, thanks! Exactly the identity I was looking for.

Is there a closed form for...


Saving the current data before updating the form in Django

Question: I would like to create a history of changes in one of my models. That every time I will update it, the current data will be saved to a different table and at the same time, the new data enters to another table. How will I be able to do that? I saw examples and they are based from the admin. But I still don't get the idea of it. This maybe a noob question but I'm still learning Django.
models.py
class tblTicket(models.Model): #new data will be entered here
    remarks = models.TextField("Action Taken", max_length=500,default='')
class LogChanges(models.Model): #table to save the changes
    prevRemarks = models.CharField(max_length=500,default='')

forms.py
class troubleTicket(ModelForm):
    class Meta:
        model = tblTicket
        fields = '__all__'

class history(ModelForm):
    class Meta:
        model = LogChanges
        fields = '__all__'

views.py
def updateTicket(request, ticket_id):
    ticketDetails=tblTicket.objects.get(id=ticket_id)
    updateTicketForm = troubleTicket(request.POST or None,instance=ticketDetails)
    if updateTicketForm.is_valid():
        updateTicketForm.save()
        return HttpResponseRedirect('/ticket/')
    return render(request,'updateTicket.html', {'updateTicketForm':updateTicketForm,'ticketDetails':ticketDetails,'ticket_id':ticket_id})

I am using django 1.8.3

UPDATE:
I found a link related to my question. But it gives me an error NameError: name 'tblTicket' is not defined
def make_copy(sender, **kwargs):
    obj = kwargs['instance']
    try:
        orig_obj = tblTicket.objects.get(pk=obj.pk)
    except: #If it is a new object
        orig_obj = None

pre_save.connect(make_copy, sender=tblTicket) <- this is where the error leads me

To my understanding, in this link, the Country there is the model. So I switched it to my model which is tblTicket. I don't understand why it isn't defined.
Comment: for what it's worth, there's several django packages that basically do this: https://www.djangopackages.com/grids/g/versioning/
Comment: Hi there @NightShadeQueen! I have researched those and I wouldn't want another package in my library just for this.. So I am seeking for options that does not require to use another packages
Answer: cIt sounds like you want to override the save method of your tblTicket model so that it creates a new LogChanges object. Like this..
class tblTicket(models.Model):
    ...

    def save(self):
        super(tblTicket, self).save()
        LogChanges.objects.create(prevRemarks=self.remarks)

Comment: Hi thank you for taking the time answering. I will give this a try. Question though, how about in my views, do I have to change something or I'll just add this in my `models.py`? And the current data will be save to the `LogChanges` table and new data to the `tblTicket`?
Comment: I tried it there was an error. `'Manager' object has no attribute 'Create'` it was on this line. `LogChanges.objects.Create(prevRemarks=self.remarks)` am I missing some import?
Comment: I fixed the error above. It worked with `create` not `Create`


Solve the problem using linearity of expectation.

Question: A building has $n$ floors numbered $1, 2, \cdots , n,$ plus a ground floor $G$. At the
ground floor, $m$ people get on the elevator together, and each gets off at a uniformly
random one of the $n$ floors (independently of everybody else). What is the expected
number of floors the elevator stops at (not counting the ground floor)?
Answer: For $i=1$ to $n$, let $X_i=1$ if the elevator stops at the $i$-th floor, and let $X_i=0$ otherwise. Then $N$, the number of floors stopped at, is given by
$$N=X_1+X_2+\cdots+X_n.$$
Thus by the linearity of expectation, we have
$$E(N)=E(X_1)+E(X_2)+\cdots +E(X_n).$$
The probability that no one stops at floor $i$ is $\left(\frac{n-1}{n}\right)^m$.
Thus the probability that $X_i=1$ is $1-\left(\frac{n-1}{n}\right)^m$.  This is also the expectation of $X_i$.
For $E(N)$, add up over all $i$, that is, multiply by $n$.


Why access_token becomes invalid

Question: what are the reasons that the access_token instagram becomes invalid. I've noticed that there is no time expiration of the token?
Does someone know how to avoid it?
thanks a lot for your replies
Answer: Your all answers are given here in this document:
https://www.instagram.com/developer/authentication/

Important
  Even though our access tokens do not specify an expiration
  time, your app should handle the case that either the user revokes
  access, or Instagram expires the token after some period of time. If
  the token is no longer valid, API responses will contain an
  "error_type=OAuthAccessTokenException". In this case you will need to
  re-authenticate the user to obtain a new valid token. In other words:
  do not assume your access_token is valid forever.

So Token expire in two case

User revoke access
After some time (No specific time interval)

Does someone know how to avoid it?
No. Ther is no way to avoid it because that is for security reason. Avoiding it is compromising the security of the user and Instagram definitely don't want that.
So the only solution (And proper way) is to handle OAuthAccessTokenException

Why access_token becomes invalid


Domino Trains Questions

Question: A train is an end-to-end arrangement of dominoes such that the adjoining halves of neighboring dominoes have the same number of dots.
A "double-$n$'' domino set has one of each possible domino using integers from $0$ to $n$, where order is not a distinguishing feature (so there aren't separate $0$-$2$ and $2$-$0$ dominoes, for example).
Let $f(n)$ be the smallest number of trains that can be formed from the dominoes in a double-$n$ set, such that each domino is used in exactly one train. What are the values of $f(12)$ and $f(15)$?

How can I approach this problem with graph theory?
Comment: I don't think you need graph theory for this
Comment: What does a double-$n$ set mean ?
Answer: This question really asks which complete graphs have an Eulerian cycle. For the complete graphs with an Eulerian cycle the answer is 1. For the complete graphs without an Eulerian cycle you need to find a decomposition in a minimal number of paths.
The dominoes of the form $i,i$ can be squeezed in at any moment you visit vertex $i$.
Can you take it from there??
One more hint: in the complete graphs without an Eulerian cycle, every vertex of odd degree must be endpoint of a path.
Answer: We need to look at Eulerian paths, and use the well-known result about them using odd and even vertices. This makes $f(12)=1$ and $f(15)=8$.
The trains are fairly basic in the odd case (an even number of vertices) - we 'disconnect' $\dfrac{k+1}{2}$ single edge disjoint graphs, the remaining graph is Eulerian and can have a path joined to it to make a train, the rest form individual trains.
A perhaps more interesting answer can be arrived at by defining a train as a rotationally symmetric path for the complete graph, for example for $n=8$ we have:

If we rotate the image four times we arrive at:

which gives us the four minimum trains as required.

Domino Trains Questions


Como compilar o banco de dados para instalar junto com uma aplicação C#?

Question: Estou desenvolvendo uma aplicação em c#, e preciso saber se consigo compilar o banco para instalar junto com a aplicação, já vi algo por aqui falando sobre o SQLite, porém não conheço a ferramenta e não sei se ela armazena imagens, e no meu caso terei um fluxo de uma imagem por cadastro, pensei em LocalDB, porém ele armazena apenas 10GB, o que penso que vai encher logo, bom, pensei no MySQL que já utilizei para aplicações web e conheço a ferramenta, bom vão as perguntas.

Posso integrar o MySQL com facilidade a um projeto no Visual Studio?
Compensa usar o MySQL em uma aplicação desktop para cadastro?
Tem como instalar o banco junto com a aplicação?
Se não, qual um banco que tenha integração com c#, que seja grande o suficiente para um bom fluxo de cadastros e possa ser facilmente adicionado ao projeto?
Comment: Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Comment: Tenho visto por aí usarem instaladores de softwares(INNO SETUP e etc) e juntos, com esses instaladores os banco de dados e etc. Agora, bancos relacionais deve se ter alguns cuidados. Se na máquina do cliente não houver um instalado, o instalador vai instalar, mas é necessário de quem está adquirindo seu sistema tenha um entendimento para acompanhar a instalação. Não sei se seria uma boa. Quanto ao Sql Lite, não conheço.
Answer: Que fique claro que nesta resposta estou falando de aplicações puramente desktop. Não estou falando de cliente servidor onde o cliente é um executável para rodar no desktop e o banco de dados ficará no servidor para acesso por vários clientes.
No cenário cliente/servidor o aplicativo desktop será instalado separado do servidor, então a pergunta não caberia.
O cenário descrito na pergunta é para aplicações standalone, onde o banco de dados está intimamente ligado ao executável e só será acessado por ele.
MySQL
Sem muitos detalhes não é fácil dar uma resposta precisa, mas de uma maneira geral não compensa usar o MySQL para uma aplicação desktop assim. Aí as demais perguntas não fariam sentido. Claro que tem como instalar junto, mas não deveria.

O MySQL precisa ser instalado, muita coisa pode acontecer errada nesse processo. Sem falar no tamanho que deve ir junto a aplicação.
E tem que ficar rodando. Ocupa muita memória. E usuários incautos podem facilmente comprometer seu funcionamento quando detectam coisas esquisitas no seu computador (tem como rodar sob demanda, mas não ajuda muito e pode trazer outros problemas).
É comum precisar de manutenção, e ela não é tão simples.
É um canhão pra matar passarinho. Muito do que ele oferece não é necessário neste cenário.
Pode haver outros problemas em cenários específicos. Por exemplo, pode já haver um MySQL na máquina pra outra coisa. Você teria conflito ou precisaria estar preparado para lidar com isto, o que é demais para algo que deveria ser simples.

SQLite

O SQLite é o banco de dados padrão para aplicações desktop (não servidores).
Ele pode fazer essencialmente tudo o que o MySQL pode. A diferença é que ele não é um servidor (ótimo neste caso), e que não pode fazer uma quantidade de escritas realmente simultâneas tão grande quanto o MySQL, mas a diferença não é brutal e no desktop isto não deve ocorrer, pelo contrário, provavelmente só será necessário fazer uma escrita por vez.

As informações sobre o componente adicional que precisa anexar ao projeto para seu uso podem ser obtidas na página oficial dele. Não precisa instalá-lo, ele passa fazer parte da aplicação.
Os pacotes Nuget encontrados na página de download são mais fáceis de manipular.
Ao contrário do que algumas pessoas pensam, o SQLite também pode ser usado, e eu uso com sucesso, em cenário cliente/servidor (tem resposta minha lá em baixo mostrando como), mas aí pode não ser a solução mais adequada. Veja mais sobre seu uso.
Se tiver dúvidas específicas, faça-as em perguntas individuais.
Coloquei no GitHub para referência futura.
Comment: Estou fazendo uma aplicação desktop com o MySQL e baseado na sua resposta é mais correto, eficiente ou eficaz usar o SQLite do que o MySQL? Quais são as vantagens e desvantagens de usar o SQLite do que MySql?
Comment: Depende de cada caso. Acho que as vantagens estão aí, se for detalhar mais precisaria ser em nova pergunta. Eu atualizei para esclarecer um ponto importante, antes que haja confusão sobre o termo "aplicação desktop". Não sei qual é o seu caso.
Comment: Então vou uma pergunta sobre isso detalhando o meu caso.


What am I doing wrong in calculating the Laplace Inverse Transform of $\mathcal L^{-1} \left(\frac{3}{s}-\frac{3s}{s^2+1}\right)e^{-(s+1)x}$?

Question:
Question:
  $$W=\left(\frac{3}{s}-\frac{3s}{s^2+1}\right)e^{-(s+1)x}$$
By taking the inverse laplace transform of $W(x,s)$ find $w(x,t)$?

My Attempt:
$$W=\left(\frac{3}{s}-\frac{3s}{s^2+1}\right)e^{-(s+1)x}$$
$$=\left(\color{orange}{\frac{3}{s}}-\color{red}{\frac{3s}{s^2+1}}\right)\cdot \color{purple}{e^{-sx}}\cdot \color{#06f}{e^{-x}}$$
Finding the Inverse Laplace Transform:
Since:
The Inverse Laplace Transform of:
$$\color{orange}{\frac{3}{s}=3\cdot 1}$$
and
$$\color{red}{\frac{3 \cdot s}{s^2+1}=3\cdot \cos t}$$
and
$$\frac{\color{purple}{e^{-sx}}}{s}=u(t-s) \implies \color{purple}{e^{-sx}=u(t-s) \cdot s}$$
and
$$\color{#06f}{e^{-x}=\frac{1}{s+1}}$$
We can use the 2nd Shifting Theorem, to get that the final answer is:
$$\bbox[10pt, border: blue solid 1pt]{\mathcal L^{-1}\left(\frac{3}{s}-\frac{3s}{s^2+1}\right)e^{-(s+1)x}=\frac{(\color{orange}{3}-\color{red}{3\cos(t)})\color{purple}{u(t-s)\cdot s}}{\color{#06f}{s+1}}}$$
But my Answer is wrong, what am I missing here?
Comment: $e^{-xs}/s \to u(t-x)$
Answer: Hint: $$\mathcal L^{-1}(1)=u(t)$$
Thus $$\mathcal L^{-1}(e^{-sx})=u(t-x)$$ And according to the 2nd Shift Theorem:
$$\mathcal L^{-1}(F(s)*e^{-sx})=f(t-x)u(t-x)$$
Also $e^{-x}$is a constant. So rewriting the equation:
$$\mathcal L^{-1}\left(\frac{3}{s}-\frac{3s}{s^2+1}\right)e^{-(s+1)x}={-3\times(\color{red}{\cos(t-x)-1})\color{purple}{u(t-x)}}{}e^{-x}$$


Convert group json for Highcharts Donut chart

Question: This question for creating the Highcharts Donut chart with multiple series.
I have dynamic key properties xData, yData of JSON input data model:
  xData= ["Phase", "Step", "Task"];
  yData = ["VPhase", "VStep", "VTask"]

  inputArray = [
    { Phase: "Phase 1", VPhase: 100, Step: "Step 1", VStep:50, Task: "Task 1", VTask: 20 },
    { Phase: "Phase 1", VPhase: 100, Step: "Step 1", VStep:50, Task: "Task 2", VTask: 30 },
    { Phase: "Phase 1", VPhase: 100, Step: "Step 2", VStep:50, Task: "Task 1", VTask: 25 },
    { Phase: "Phase 1", VPhase: 100, Step: "Step 2", VStep:50, Task: "Task 2", VTask: 25 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 1", VStep:100,Task: "Task 1", VTask: 60 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 1", VStep:100,Task: "Task 2", VTask: 40 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 2", VStep:50, Task: "Task 1", VTask: 15 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 2", VStep:50, Task: "Task 2", VTask: 35 }
  ];

I need group and distinct consecutive index xData, yData for creating output result similar:
outputArray = [
    {
      Phase: ["Phase 1", "Phase 2"],
      VPhase: [100, 150]
    },
    {
      Step: ["Step 1", "Step 2", "Step 1", "Step 2"],
      VStep: [50, 50, 100 ,50]
    },
    {
      Task: ["Task 1", "Task 2", "Task 1", "Task 2", "Task 1", "Task 2", "Task 1", "Task 2"],
      VTask: [20, 30, 25, 25, 60, 40, 15, 35]
    }
  ];

Comment: Hi @Moslem Shahsavan, You have used `highcharts` tag, but the problem doesn't seem to be about a chart - rather about data. If you'll have problems with Highcharts then please provide a demo with hard-coded, exemplary data.
Answer: With some effort I end up with this solution:

const inputArray = [
    { Phase: "Phase 1", VPhase: 100, Step: "Step 1", VStep:50, Task: "Task 1", VTask: 20 },
    { Phase: "Phase 1", VPhase: 100, Step: "Step 1", VStep:50, Task: "Task 2", VTask: 30 },
    { Phase: "Phase 1", VPhase: 100, Step: "Step 2", VStep:50, Task: "Task 1", VTask: 25 },
    { Phase: "Phase 1", VPhase: 100, Step: "Step 2", VStep:50, Task: "Task 2", VTask: 25 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 1", VStep:100,Task: "Task 1", VTask: 60 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 1", VStep:100,Task: "Task 2", VTask: 40 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 2", VStep:50, Task: "Task 1", VTask: 15 },
    { Phase: "Phase 2", VPhase: 150, Step: "Step 2", VStep:50, Task: "Task 2", VTask: 35 }
  ];

function getGroupedData(data, firsts, seconds) {
    const reduced = data.reduce(function(m, d) {
      if(!m) m = {};
      firsts.forEach(function(key) {
        if(!m[key]) m[key] = [];
        m[key].push(d[key]);
      });

      seconds.forEach(function(key) {
        if(!m[key]) m[key] = [];
        m[key].push(d[key]);
      });

      return m;
    }, {});

    const obj = [];
    for(var i in firsts){
      const o = {};
      o[firsts[i]] = reduced[firsts[i]]
      o[seconds[i]] = reduced[seconds[i]]
      obj.push(o);
    }

    const final = [];
    obj.forEach(c=>{
      var keys = Object.keys(c);
      for(var i in c[keys[0]]){
        const o = {};
        o[keys[0]] = c[keys[0]][i];
        o[keys[1]] = c[keys[1]][i];
        if(!final.some(p => p[keys[0]] == c[keys[0]][i] && p[keys[1]] == c[keys[1]][i]))
          final.push(o);
      }
    })

    const output = [];
    for(var i in firsts){
      const o = {};
      o[firsts[i]] = [];
      o[seconds[i]] = [];
      final.forEach(c=>{
        if(c[firsts[i]]){
          o[firsts[i]].push(c[firsts[i]]);
          o[seconds[i]].push(c[seconds[i]]);
        }
      })
      output.push(o);
    }

    console.log(output);
}

getGroupedData(inputArray, ["Phase", "Step", "Task"], ["VPhase", "VStep", "VTask"]);

https://stackblitz.com/edit/typescript-vryxjl
Comment: برو یره. لطفا تصویر نمونه که فرستاده شده توجه فرمایید


Ajax Request Failing

Question: I've got a perplexing issue which has left me quite confused. I've got a form which has a link on it and when the user clicks the link it is supposed to open up an AJAX popup form and display some data in the form.
It is working just perfectly about 90% of the time.  But of late, a few users are complaining that when they click the link, the popup appears but the data is not being displayed.  Instead, they just get the loading sign and it just goes on forever.
I decided to test this myself and after a few tries I was able to replicate this myself. In my JS Console, I've got no response back and just have the request headers.  As for my code, what happens is, when the popup is displayed initially, I just have the loading throbber going and I send a .get request to my Drupal function to retrieve the data.  Once the data is retrieved, we replace the throbber with the data display.  You can see this being done in the code below:
$('a.myModule_test_request', context).live("click", function(event) {
        //Store the matched div jquery object in a variable
        var $this = $(this);

        event.preventDefault();

        //Get the complete url for the Test Request drupal function
        var testurl = Drupal.settings.basePath + 'myModule/TestRequest/';
        //Get the nodeid from the link
        var linkurl = $this.attr("href");
        //We use a regex to extract the nid, which is at the end of the url
        var match = /\d+$/.exec(linkurl);
        var nid = match[0];
        //The complete url for the Test Request drupal function
        testurl = testurl + nid;

        //Create a temporary div and turn it into a modal dialog
        var $myModule_Item_TestRequest_modal_dialog = $('

');

        //Make the height and width of the dialog 95% of the screen size
        var dialogWidth = ($(window).width() * 0.95);
        var dialogHeight = ($(window).height() * 0.95);

        $myModule_Item_TestRequest_modal_dialog
          .addClass("myModule_test_request_dialog")
          .addClass("myModule_dialog")
          .dialog({
            modal: true,
            title: $this.text(),
            resizable: true,
            draggable: true,
            height:dialogHeight,
            width:dialogWidth,
            bgiframe: true,
            open: function () {
              //Add an id attribute to the close button, when the dialog opens, which will be used later to close the dialog and detach behaviors
              $(this).parent().children().children('.ui-dialog-titlebar-close').attr( 'id', 'myModule_Item_TestRequest_Dialog_Close');
              //Add an id to main div of dialog box.

              $(this).parent('.ui-dialog').attr( 'id', 'myModule_Item_TestRequest_Dialog');
              //Add the myModule_test_request_dialog and myModule_dialog classes to main div of dialog box as well
              $(this).parent('.ui-dialog').addClass("myModule_test_request_dialog_wrap myModule_dialog");

            }
          });

          //Add positioning for the div
          $myModule_Item_TestRequest_modal_dialog.position({
            my: "center",
            at: "center",
            of: window
          });

          //Display the throbber in the dialog while the form loads
          $myModule_Item_TestRequest_modal_dialog.html('

Loading..

');

          //Load the html returned from the testurl function and attach behaviors to the new content.
          $.get(testurl, function(data) {
            $myModule_Item_TestRequest_modal_dialog.html(data);
            Drupal.attachBehaviors($myModule_Item_TestRequest_modal_dialog);
          });

          //When the dialog close button is clicked, detach behaviors and remove the dialog
          $('#myModule_Item_TestRequest_Dialog_Close').click(function() {
            Drupal.detachBehaviors($myModule_Item_TestRequest_modal_dialog);
            $myModule_Item_TestRequest_modal_dialog.dialog('destroy').remove();
          });
      });

After troubleshooting this, I figured out that when the popup hangs, there is absolutely no request being logged for that particular click in the Apache request log.  How could this happen?  I know the function is working all the way until that .get request because I've got the popup loaded and the throbber displayed, but what happens after that?  It's appears as though it is failing to even send the request to Apache.  Do requests go ignored in jQuery?
Hope you guys can give me some pointers on why this could happen.  Any help would be highly appreciated.
Comment: First thing to do is to look at the network tab in the Chrome debugger and see if the request is being sent or not over the internet.  That tells you where to look next (client or server) for the next step in the troubleshooting.  And, if you see a request being sent examine it to see if it is formed correctly and to the right destination.  You may also be on the lookout for any caching issues (IE particularly known for aggressive caching) that might prevent the real request from being sent.
Comment: In my Firebug debugger, I've only got two things visible for this request, the Request Headers and the Cookies tab.  I compared the Request Headers with a request that worked and they look exactly the same.  So, I checked my Apache Server Request log, but I couldn't find an entry for this request.  So, it's like it never was sent.
Comment: What dies Firebug show for response headers?  For response? Are you 100% use the URL for the request is correct?  Can you tell if the response is coming from cache?  Does Firebug show a response of any kind?  Or any kind of response timing?  Perhaps post a screenshot of what you see in Firebug for that request.
Comment: There are no tabs for the response headers and response for the request that hangs. Basically, it just times out after around 35 secs. My url is correct. Please note that this request works 90% of the time, only sometimes does it hang. And when it does hang, it does not register in the Apache Request Log and I get no response tabs in firebug.
Answer: It appears to me that you have not yet enclosed your script as described in this post.  That might be it?
(function($) {
Drupal.behaviors.myBehavior = {
  // your function goes here, I think.
};
})(jQuery);

Comment: I copied and pasted just the function, the script is being properly closed.
Comment: It's not so much about it being properly closed as being **enclosed** in the Drupal wrapper.
Comment: Everything is enclosed properly. There are no bugs regarding enclosure.

Ajax Request Failing


Questions which are too broad

Question: It happens a few times in the past, that I just wrote an answer to a question which might be too broad, and when I was ready to post, the question was closed.
I think many too broad questions can be answered with a recommendation on how to implement this, but not going into details.
So this is first a call for thinking about it might be an option to let the question open and give the people a roadmap how to do something and second a question for your opinion on this, of course :-)
Answer: In this case please use "Reopen" button.
Comment: The problem is, that the question is then not reopened immediately and so I forget this. But you are right :)

Questions which are too broad


Filter on date in MySQL

Question: I am trying to convert a date time column to date and get all the rows in a particular day . But when try it. The query returns 0 rows .What is wrong with this code
        where date(a.refresh_time) = '2016-06-11'
Comment: It would help if you showed data, and the actual query (or a reasonable facsimile of both).
Comment: doesn't look too terrible. His code has back-ticks in it, thus making the formatting of the question go sour. Maybe you lack that data, or you are British looking for November 6.
Answer: Use the correct date_format
 where date_format(`a`.`refresh_time`'%Y-%m-%d') = '2016-06-11'

Comment: of what you thanking   me  .. if you think my anser is useful  you can rate it ..
Answer: Do not!!! use a function on a field in WHERE clause like the Answer from @scaisEdge. If you do that like this sample MySQL must read ALL rows in the table convert it with your function and can then compare it. And it never can use a index
If is better and quicker to use like this
SAMPLE
WHERE `a`.`refresh_time` >=  '2016-06-11 00:00:00' AND `a`.`refresh_time` <=  '2016-06-11 23:59:59';

OR
WHERE `a`.`refresh_time` BETWEEN  '2016-06-11 00:00:00' AND '2016-06-11 23:59:59';

So MySQL can direct use a INDEX to find the correct ROWs
You can test it with EXPLAIN before your SELECT.

Filter on date in MySQL


Stirling number of first kind monotone for a half

Question:
Show that every $n>0$, there is some $m(n)$ such that $$s_{n,0}<s_{n,1}<\cdots < s_{n,m(n)}>s_{n,m(n)+1}>\cdots>s_{n,n},$$
  where either $m(n)=m(n-1)$ or $m(n)=m(n-1)+1$ and $s_{n,k}$ is the Stirling number of the first kind.

I have no clue to prove the claim. Can anyone give me some hints? Thank you in advance!
Answer: SKETCH: Use the standard recurrence for the Stirling numbers of the first kind,
$${{n+1}\brack k}=n{n\brack k}+{n\brack{k-1}}\;,\tag{1}$$
to prove it by induction on $n$. (I use the notation $n\brack k$ for your $s_{n,k}$.)
Suppose that
$$\begin{cases}
{n\brack k}<{n\brack{k+1}},&\text{if }0\le k<m(n)\\
{n\brack k}>{n\brack{k+1}},&\text{if }m(n)\le k<n\;.
\end{cases}$$
If $1\le k<m(n)$, then ${n\brack{k-1}}<{n\brack{k}}<{n\brack{k+1}}$, and
$$\begin{align*}
{{n+1}\brack{k}}&=n{n\brack{k}}+{n\brack{k-1}}\\
&<n{n\brack{k+1}}+{n\brack{k}}\\
&={{n+1}\brack{k+1}}\;,
\end{align*}$$
so ${{n+1}\brack{k}}<{{n+1}\brack{k+1}}$, and you can easily check that this also holds for $k=0$.
Now make a similar calculation to show that ${{n+1}\brack{k}}>{{n+1}\brack{k+1}}$ when $m(n)<k<n$, and verify that the inequality also holds for $k=n$. At this point you'll have shown that
$$\begin{cases}
{{n+1}\brack k}<{{n+1}\brack{k+1}},&\text{if }0\le k<m(n)\\
{{n+1}\brack k}>{{n+1}\brack{k+1}},&\text{if }m(n)<k<n+1\;.
\end{cases}\tag{2}$$
The only two adjacent Stirling numbers for $n+1$ whose order relationship isn't specified by $(2)$ are ${{n+1}\brack{m(n)}}$ and ${{n+1}\brack{m(n)+1}}$, and how they're ordered determines what $m(n+1)$ is.
Comment: I understand the logics of your argument. But in the inductive step, shouldn't we have to consider the intervals $0 \le k \lt m(n+1)$ and $m(n+1) \lt k \lt n+1$, but not $0 \le k \lt m(n)$ and $m(n) \lt k \lt n+1$ like in your proof?
Comment: But this is brilliant nonetheless! Did you have some sort of observation that led you to come up with this proof?


Rails Cocoon: Don't destroy the model

Question: I've got two models. Let's name them parent and child:
class Parent < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children, reject_if: :all_blank, allow_destroy: true
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

As you can see, a parent could have many children. Now I'm using Cocoon to easily manage the associations. Now I'm having the following problem:
I want to destroy the association (in the view: <%= link_to_remove_association 'Remove', f %>) but not destroy the actual model. So I want to detach the child from the parent but not remove it entirely from my database. allow_destroy is only in there to test everything, without it just nothing works.
Is there any elegant way of doing this?
Comment: Similar to https://github.com/nathanvda/cocoon/issues/173 ?
Comment: Sorry, but I do not see any relevance of that bug for my question. I do not get any error: I only want to prevent Cocoon from destroying my object.
Answer: class Child < ActiveRecord::Base
 belongs_to :parent
end

Comment: Uh, oh. Yeah, that's in there, too. Forgot it while writing the question. Sorry about that!
Comment: Well, it actually could have been a problem with my code. So I guess it is an answer?

Rails Cocoon: Don't destroy the model


Combinatorics-number of permutations of $m$ A's and at most $n$ B's

Question: Prove that the number of permutations of $m$ A's and at most $n$ B's equals $\dbinom{m+n+1}{m+1}$.
I'm not sure how to even start this problem.
Comment: Do you already know how many permutations there are of $m$ A's and *exactly* $n$ B's?
Comment: m+n spots, so (m+n) choose (m) ways to place A.
Comment: Good: that's all that you really need in order to follow Thijs's solution.
Comment: Srivatsan's argument is very elegant, but the identity at the end of Thijs's solution is well worth knowing, as is its 'dual' $\sum_{i=m}^n \binom{m+i}{m} = \binom{m+n+1}{m+1}$.
Comment: A question from Sep 2011 marked as duplicate of one of Apr 2013; the mention "This question has been asked _before_..." would seem somewhat unjustified.
Answer: By summing all possibilities of $n$, we get that the number of permutations $P_n$ satisfies
$$P_n = \binom{m+n}{n} + \binom{m+(n-1)}{(n-1)} + \ldots + \binom{m+0}{0} = \sum_{i=0}^n \binom{m + i}{i}$$
Note that
$$\binom{a}{b} = \binom{a-1}{b} + \binom{a-1}{b-1}$$
Repeatedly applying this to the last term, we get
$$\begin{array}{rcl}
\binom{a}{b} &=& \binom{a-1}{b} + \binom{a-1}{b-1} \\
 &=& \binom{a-1}{b} + \binom{a-2}{b-1} + \binom{a-2}{b-2} \\
 &=& \binom{a-1}{b} + \binom{a-2}{b-1} + \binom{a-3}{b-2} + \binom{a-3}{b-3} \\
 &=& \binom{a-1}{b} + \binom{a-2}{b-1} + \binom{a-3}{b-2} + \binom{a-4}{b-3} + \ldots \\
 &=& \binom{a-1}{b} + \binom{a-2}{b-1} + \binom{a-3}{b-2} + \binom{a-4}{b-3} + \ldots + \binom{a-b-1}{0} \\
 &=& \sum_{i=0}^b \binom{a-b-1+i}{i}
\end{array}$$
Substituting $b$ by $a-b$ we similarly get
$$\binom{a}{a-b} = \sum_{i=0}^{a-b} \binom{b-1+i}{i}$$
Replacing $b = m + 1$ and $a = n + m + 1$ we thus get
$$\binom{n + m + 1}{n} = \sum_{i=0}^{n} \binom{m+i}{i} = P_n$$
Answer: Here's a combinatorial solution. Take a string $\alpha$ containing exactly $m+1$ A's and $n$ B's. Identify the final occurrence of $A$ in $\alpha$. Form the string $\beta$ by deleting this final occurrence of $A$ and all the characters that follow it (the characters following it must all be $B$).
It is clear that $\beta$ contains exactly $m$ A's and at most $n$ B's. Further, the strings $\alpha$ and $\beta$ are in one-to-one correspondence with each other. (We already described how to obtain $\beta$ from $\alpha$. To write down $\alpha$ given $\beta$, concatenate $\beta$ with an $A$ followed by enough $B$'s to make the total number of $B$'s exactly equal to $n$.)
Thus the number of permutations with $m$ A's and at most $n$ B's is equal to the number of permutations with exactly $m+1$ A's and exactly $n$ B's, which is clearly $\binom{m+n+1}{m+1}$.


Efficient way to find a selector which apply on specific element

Question: I have predefined css selectors list in js array and an element. I need to find which selectors would apply on that element.
Here is my code: http://jsfiddle.net/mjALF/
html

js
var selectors = ['#main .a', '#main .a .b', '.a', '#main .c', '#main .a .b .c'];

// pseudo code
/*

find_selectors($('#d4'), selectors);
result: null

find_selectors($('#d1'), selectors);
results: ['#main .a', '.a'];

*/

Answer: You can use $.grep() to get a filtered array with .is(), like this:
var elem = $("#d1");
var results = $.grep(selectors, function(s) { return elem.is(s); });

You can test it out here.  Or, as a plugin!
$.fn.selectorMatch = function(sArray) {
    var elem = this;
    return $.grep(selectors, function(s) { return elem.is(s); });
};

Then you can call it like this:
var results = $("#d1").selectorMatch(selectors);

You can test the plugin version out here.
Comment: 111k, the biggest reputation score I have ever seen :p. Thank you.
Comment: @StoneHeart - There's more active users than me =P http://stackoverflow.com/users welcome though!
Comment: @gov - I'd watch that if I were you. Looking back at your questions, a lot of different people here have helped you. (Nothing against you Nick. +1 Nice answer.)
Comment: @gov - post all your questions anytime, there are **tons** of *extremely* smart people here at all times, for [jQuery for example](http://stackoverflow.com/tags/jquery/topusers) there are lots of active/smart users, like @patrick above :)
Comment: @patrick  i agree withyou ,yeah there are lot of brilliant people here and we get very quick answers...and i always appreciate that. I just said hi to nick like that...


Tratamento de Exeções na MODEL

Question: Como eu faço para mandar uma exeção do Model para View em forma de um Alert, por exemplo MODEL :
Try {
    // codigo

}catch{

    // Aqui quero tratar o erro e mandar uma mensagem pra ser exibida na view em forma de alerta.

}

Obrigado.
Answer: Se achar um problema na model, você pode mandar um alert assim:
public ActionResult Create(ItemModel fvm){
   try
   {

   }
   catch (Exception e)
   {
      TempData["msg"] = "";
   }
}

@Html.Raw(TempData["msg"])

ou
return JavaScript(alert("Olá mundo"));

ou
return Content("");

Comment: É bem isso, ótima resposta !!!
Answer: Você pode utilziar o AddModelError. Com ele, não será exibido um alert com a mensagem de erro, mas o erro será exibido na tela igual tratamento de erro que são feitos em inputs.
Na sua controller:
Try {
    // codigo

}catch{

     ModelState.AddModelError("", "Coloque seu erro aqui.");
}

Na view, você utiliza @Html.ValidationSummary(true, "", new { @class = "text-danger" }) para o erro ser exibido.

Tratamento de Exeções na MODEL


Angular2 Detect id and class

Question: Let say I have the following in angular:

      some content

Then in .ts, I have the following:
  someFunction(){
       //Want to detect the class and id of the div i clicked.
  };

I want to detect the id and class of the div that the click function lies.
How do I do it?
Comment: duplicate of https://stackoverflow.com/questions/36006894/angular2-get-clicked-element-id
Answer: You can use srcElement property and get that info.
<button (click)="someFunction($event)" id="myid"
     class="myclass">Click</button>

  someFunction(event) {
      console.log(event);
      console.log(event.srcElement.attributes.id);
      console.log(event.srcElement.attributes.class);
  }

Angular2 Detect id and class


How do I login to private Docker Registry with a self signed cert using WSL2 on Windows?

Question: I have a private Docker registry that uses https and a self signed certificate. I have this working on my OSX machine by adding the certificate to The keychain. However, I would not like to connect to it from a Windows Machine with WSL2.
I tried adding the cert to certlm and I tried to restart Docker but it didn't seem to help. Since this was WSL I tried also adding the crt file to /usr/local/share/ca-certificates/ but neither of these prevent...
docker login https://...:5000
Error response from daemon: Get "https://...:5000/v2/": tls: failed to verify certificate: x509: certificate signed by unknown authority

What do I need to be able to use the Docker cli from WSL2 (Ubuntu)?
Answer: In my case I needed to have my certificate file under "Trusted Root Certification". I had it under personal since it was managed by myself. Is there a way to still have it work while not putting it as a root cert?


Equality constraints in trait in Rust. Variant with Into trait

Question: I want the ToKeyIter::Item be equal to ToKeyIter::KeyIter::Item as KeyIter should implement Iterator trait. I couldn't do it because with constraint equality in where clause. That's why I decided to use trait Into.
pub trait ToKeyIter {
    type Item: Clone + Hash + Eq;
    type KeyIter<'b>: Iterator where Self: 'b, <Self::KeyIter<'b> as Iterator>::Item: Into<Self::Item>;
    fn key_iter<'a> (&'a self) -> Self::KeyIter<'a>
    where <Self::KeyIter<'a> as Iterator>::Item: Into<Self::Item>;
}

The trait itself compiles, but when I try to impl it for str or String, the compiler fails with "overflow evaluating the requirement".
impl ToKeyIter for str {
    type Item = char;
    type KeyIter<'a> = Chars<'a>;

    fn key_iter<'a> (&'a self) -> Chars<'a> {
        self.chars()
    }
}

impl ToKeyIter for String {
    type Item = char;
    type KeyIter<'a> = Chars<'a>;

    fn key_iter<'a> (&'a self) -> Chars<'a> {
        self.chars()
    }
}

If you can tell how to write something like this
Key::Item == Key::KeyIter::Item

it will be great. But also I want to know what I should do to have correct impl for str and String with Into trait.
Answer: You can specify the Iterate<Item=Self::Item> to obtain what you want. See the playground for a live version of this:
#![feature(generic_associated_types)]

use std::hash::Hash;
use std::str::Chars;

pub trait ToKeyIter {
    type Item: Clone + Hash + Eq;
    type KeyIter<'a>: Iterator<Item=Self::Item>
    where
        Self: 'a;
    fn key_iter<'a>(&'a self) -> Self::KeyIter<'a>;
}

impl ToKeyIter for str {
    type Item = char;
    type KeyIter<'a> = Chars<'a>;

    fn key_iter<'a> (&'a self) -> Chars<'a> {
        self.chars()
    }
}
impl ToKeyIter for String {
    type Item = char;
    type KeyIter<'a> = Chars<'a>;

    fn key_iter<'a> (&'a self) -> Chars<'a> {
        self.chars()
    }
}


Should JQueryMobile apps have a php extension

Question: In my job I have been ordered to make a dynamic application.Also, that all the pages should have a .php extension rather than a .html extension. I could strongly agree the php files will be needed for dynamic related subjects, but I just don't know why is a php file needed ?
Security? it's going to be view on mobile phones for the most part
Comment: Good sir: I must strongly recommend you have a long and serious talk with your supervisor. The requirements you have been given do not make a great deal of sense, and I can therefore only conclude that there has been a terrible incident of miscommunication. Please confirm with your immediate superior the specifics and purpose of these demands, and return to us with an explanation, lest we lose hope in the basic tenets of human interaction which compose our living!
Comment: I'm not sure even where to begin. PHP is Scripting language which requires a web server to parse and serve the files. What are you trying to build? Is it a website? A downloaded app using something like phone gap
Comment: And what does this have to with jQuery mobile? Which is a dom manipulation library meant for use on mobile web pages.
Answer: Php pages give you the versatility and security to render pages how you WANT them to appear, without being affected by the user's browser version and/or settings. Also, it's much easier to dynamically create content when utilizing php over its alternatives.
Answer: File extensions don't mean much.  The web server is configured to do something with certain extensions, but they could be anything really.  It has no security implications, and as far as the browser is concerned it's basically a vanity title.
I've built various applications that used unique extensions... such as a C# .NET web app which had two:  .portal was for web page requests, and .taj was for ajax requests.
Someone just likes .php I guess.
As for it being a jQuery mobile site, it sounds like they just want you to build it with PHP (and it must not be intended for Phonegap.)


Help with Mozart 6 bar long chord progression?

Question:
Can someone please explain what chords progressions are happening in this 6 measures ?
My guess is that the first measure is a A chord and the last one is a V going to I .
My confusing is regarding the middle 4 measures.
Especially the 3rd measure...is it supposed to be an A7 ? If so why...?
If not please explain what exactly is happening in those 4 measures ?Thank you
Comment: Flute , Bassoon , French Horn in A , Clarinet in A , Violin 1 , 2 , Viola ,Cello , Bass.   The very last chord is a V going into the 1 in the following messure,
Comment: What instruments are playing in this excerpt, in order? The ones with no sharps in their key signatures look like transposing instruments, but I've seen that some transposing instruments always lack key signatures regardless of the key of the piece. Also, the last bar looks like I to V instead--A major to E major chords.
Answer: Bar 1: A-E-A-E
Bar 2: A
Bar 3: A7 - A+5
Bar 4: D - B7 without the note B
Bar 5: The tone E (V) without chord but upwards scale movement and cromatic movement down, on beat 3 creating an E7 and on beat 4 creating an A chord
Bar 6: A chord with E bass, and then E chord on beat 4

As a whole bar 1,2 and 3 are centered around the A, tonic
bar 4, D and B7, subdominant followed by the dominant's dominant
bar 5 and 6 centered around E, dominant
Comment: Thanks. Actually you could argue that the B7 without the b is kind of an augmented D, so it is still kind of a subdominant, but, as I said, you could also say it is a dominant's dominant which makes sense in my opinion.
Comment: Thank you very much for the fast reply. Could you perhaps kindly explain bar 3...A7-A5+ ..why and how it works ?
Comment: I guess A7 , A+5 leads to  D and B7 leads to E ...but I`m not sure what is the conection beetwen D and B7 ...?
Comment: We are in A major, then in the third bar the seventh is added which makes the A7 chord work as a secondary dominant leading towards D. But instead of keeping the seventh Mozart changes the note g to the augmented fitth, the e sharp, which leads to f sharp, which is the third in the D major chord. Very delicate and nice. I think typical Mozart to make something like that.
Comment: The note d in the D major chord is augmented, changed to d sharp which leeads to e in the next bar. By only changing that note d to d sharp it is suddenly a B7 without the note b, the dominant's dominant. Another delicate detail by Mozart.
Comment: Thank you very much for your fast and detailed answers Mr. @LarsPeterSchultz ! It makes so much sense now ! You are very knowledgeable
Comment: I desagree with B7 without a B. The bass is on F#, so why is it not F#dim, or F#m(b5)?
Comment: It is not a complete F#dim. It has only 3 notes F#, A and D# and the function is clearly to lead up to E in the next bar.


Characterisation of one-dimensional Sobolev space

Question: I've got some doubts proving that $$H^1_0((a,b))=\{u\in AC([a,b]): u'\in L^2 \text{ and } u(a)=u(b)=0\}:=X.$$Let $$\mathcal A=\{v\in C^2([a,b]):v(a)=v(b)=0\}.$$

$H^1_0((a,b))\subseteq X.$

Let $u\in H^1_0(a,b)$. We want to use the Fundamental theorem of calculus for Lebesgue's integral to prove that $u\in X$.
Since $u\in H^1_0(a,b)$,  $u\in L^2$ and there exists a sequence $(u_h)_h\subset \mathcal A$ and a function $w\in L^2(a,b)$ such that:

$u_h\rightarrow u$ in $L^2$;
$u'_h\rightarrow w$ in $L^2$.

Now we know that $$ (*)\qquad u_h(x)=u_h(x)-u_h(a)=\int_a^x u'_h(t)dt, \text{ for each } x\in [a,b], h\in \Bbb N,$$
and we want to infer that $$ (**) \qquad u(x)=\int_a^x w(t)dt.$$
My problems start here. I think we should pass to the limit for $h\rightarrow \infty$ in $(*)$, using 1., 2. and Lebesgue's dominated convergence theorem.
I can't justify precisely why $(**)$ holds.
Concerning the application of Lebesgue's dominated convergence theorem, we only know that a subsequence of $u'_h$ pointwise converges to $w$, let's say $({u'_h}_k)_k$. We have to show that there exists $g\in L^1$ such that $|{u'_h}_k (x)|\leq |g(x)|$ for each $x\in[a,b],$ for each $k\in \Bbb N$. But who is this $g$?
If we had $g$, then $$\int_a^x {u'_h}_k(t)dt\rightarrow \int_a^x w(t)dt.$$
On the other hand, if  $\lim_{k\to \infty} {u_h}_k (x)=u(x)$ (for the same $k$) we would have finished, but I'm not sure that $\lim_{k\to \infty} {u_h}_k (x)=u(x)$ is true.
Can someone help me, please? Any suggestion would be very appreciated.
Comment: Are $a,b$ finite?
Answer: This proof cover all cases: $a,b$ finite or not. In the case that $a,b$ are not finite, $u(a)$ is understood as $\lim_{x\to-\infty}u(x)$. Analogous for $b$. Also, if $a,b$ are not finite, then we weill consider locally things, i.e. $BV_{loc}((a,b))$.
I am also assuming that $H_0^1((a,b))$ is the closure of $C_0^1((a,b))$ with respect to the $H^1((a,b))$ norm.

I- $H_0^1((a,b))\subset X$.

Take $u\in H_0^1((a,b))$ and let $\eta_\delta$ be the standard mollifier sequence. Let $u_\delta=\eta_\delta\star u$ and note that for any $c\in (a,b)$ $$|u_\delta(x)-u_\epsilon(x)|\le \int_c^x |u'_\delta (t)-u'_\epsilon(t)|dt+|u_\delta (c)-u_\epsilon(c)|\tag{1}.$$
If $c$ is a Lebesgue point of $u$, we conclude from $(1)$ that $u_\delta\to  u$ uniformaly in compact sets of $(a,b)$.
Therefore, once $$u_\delta (x)=\int_c^x u'_\delta (t)dt +u_\delta(c),\tag{2}$$
and $u'_\delta \to u'$ in $L^2_{loc}((a,b))$, we must conclude that $$u(x)=\int_c^x u'(t)dt+u(c)\tag{3}$$
If, for example $a$ is finite, then $u_\delta$ converge to $u$ uniformly in every compact set of the form $[a,y]$, hence, noting that $u_\delta (a)=0$ for all $\delta$, we have from $(2)$ that $u(a)=0$. The same happens for $b$, if it is finite.
On the other hand, if for example, $a=\infty$ then $lim_{x\to -\infty} u(x)=a$ (prove it). We conclude from the above that $u\in X$.

$X\subset H_0^1((a,b))$.

$X$ is obviously contained in $H^1((a,b))$, so it only remains to show that $u$ can be approximated by a sequence $u_\delta$ in $C_0^1((a,b))$. Let $u_\delta=\eta_\delta\star u$. This sequence satisfies $u_\delta (a)=u_\delta(b)=0$ for all $\delta$, so it is possible to aproximate each $u_\delta$ by a function in $C_0^1((a,b))$.
You can try to do it by yourself or you can take a look in theorem 8.12 of Brezis book.
Comment: @Tomás Since [a question](http://math.stackexchange.com/questions/911868/a-question-about-an-answer) asking about this answer was posted on the site, I thought it would be a good idea to notify you about that question.
Comment: Thank you for the answer! For the second inclusion also our professor suggested us to use mollifiers, but for the first one he suggested us to use the relations I've written in my question. The actual problem is that I'm not so sure why we can pass to the limit under the integral.
Comment: If $u\in L^2_{loc}((a,b))$ then $\in L^1_{loc}((a,b))$ by Holder inequality.
Answer: Let $Lf = -if'$ be defined on the linear space $\mathcal{D}(L)$ of absolutely continuous functions $f \in L^{2}[a,b]$ for which $f(a)=f(b)$ and $f' \in L^{2}[a,b]$. $L$ is symmetric on its domain, i.e., $(Lf,g)=(f,Lg)$ for all $f,g\in\mathcal{D}(L)$. It is not hard to show that $(L-\lambda I)$ is surjective for $\lambda \ne n\frac{b-a}{2\pi}$ for $n=0,\pm 1,\pm 2,\cdots$, which is verified by directly solving the the following ODE for arbitrary $g \in L^{2}$:
$$
                          -if'-\lambda f = g,\\
                           f(a)=f(b).
$$
This ODE has an explicit classical solution. Because $L\pm iI$ are surjective, then $L$ is densely-defined and selfadjoint. In particular, $L$ is closed. And,
$$
      \|(L+iI)f\|^{2}_{L^{2}}=\|Lf\|^{2}_{L^{2}}+\|f\|^{2}_{L^{2}}=\|f'\|^{2}_{L^{2}}+\|f\|^{2}_{L^{2}},\;\; f \in \mathcal{D}(L).
$$
The restriction $L_{0}$ of $L$ to $\mathcal{D}(L_{0})=\{ f \in \mathcal{D}(L) : f(a)=f(b)=0 \}$ has a graph which is of co-dimension $1$ in the graph of $L$. Because $L$ has a closed graph, then the same is true of $L_{0}$.
Now, assuming $\{ u_{h} \} \subset \mathcal{A}$ with $u_{h}\rightarrow u$ in $L^{2}$ and $u_{h}'\rightarrow w$ in $L^{2}$, then the ordered pair $(u,-iw)$ must be in the closure of the graph of $L_{0}$, which is the same as the graph of $L_{0}$ because $L_{0}$ is closed. That guarantees that $u$ is absolutely continuous with $u'\in L^{2}$ and $u(a)=0=u(b)$. Therefore, $H^{1}_{0}\subseteq \mathcal{D}(L_{0})$. The opposite inclusion follows from the norm identity stated above.


Dice and chance of three sixes

Question: We have 3 normal dices and a fake one who has on all sides the number 6.Randomly we put one away from the 4 dices and then we throw the other 3 dices.What is the probability of getting three sixes ?
Answer: Prob of putting the fake aside is $\frac{1}{4}$.  If so prob of 3 sixes $=\frac{1}{6}^3$
Prob of putting a good die aside is $\frac{3}{4}$.  In that case prob of 3 sixes $=\frac{1}{6}^2$.
Overall prob $=\frac{1}{4}\times \frac{1}{6}^3+\frac{3}{4}\times \frac{1}{6}^2=\frac{19}{864}$.

Dice and chance of three sixes


Route Parameter Validation Problem

Question: I have limited experience with D8 and custom routes.
Current mobile video system for client takes a scheme-less url for the video like so
https://example.com/mobile-video/some-video-desktop.azureedge.net
The routing has worked fine until we had a vendor change for video hosting and the new URLs include slashes and query strings which may or may not be the issue.
mobilevideo.routing.yml  looks like
mobilevideo.content:
  path: '/mobile-video/{vguid}'
  defaults:
    _controller: 'Drupal\mobilevideo\Controller\MobileVideoController::content'
    _title: 'Mobile Video'
  requirements:
    _permission: 'access content'
    vguid: '^[-a-zA-Z0-9.\/?=]+'

Prior to today the validation was just '^[-a-zA-Z0-9.]+'
So testing the new URLs I am getting 404s.  But if the parameter passed to the mobilevideo.routing.yml fails validation a 404 is the correct response so I assume the issue is validation.   https://www.drupal.org/docs/8/api/routing-system/parameters-values-validation-in-routes
So I changed the validation from vguid: '^[-a-zA-Z0-9.]+' to  vguid: '^[-a-zA-Z0-9.\/?=]+' that had no effect and I also tried '.+' and also the original without ? and =   with no change.
I should note that the original URLs with no slashes worked continously through all of this and that each change was followed by clearing all caches.
Also tried removing validation entirely and that also failed so I am wondering if my path cannot include slashes in the parameter for reasons beyond validation?
What should my next step be in debugging this?
A full example URL will look like
https://example.com/mobile-video/someidhere.cloudfront.net/sessions/forty-characters-or-more-of-vguid-here.mp4?invocationId=thirty-more-chars-here
UPDATE
Based on info re optional parameters and the comments on this post I added four more parameters and default values of '' for each updating mobilevideo.routing.yml to
mobilevideo.content:
  path: '/mobile-video/{vguid}/{vguidtwo}/{vguidhtree}/{vguidfour}/{vguidfive}'
  defaults:
    _controller: 'Drupal\mobilevideo\Controller\MobileVideoController::content'
    _title: 'Mobile Video'
    vguid: ''
    vguidtwo: ''
    vguidthree: ''
    vguidfour: ''
    vguidfive: ''
  requirements:
    _permission: 'access content'
    vguid: '^[-a-zA-Z0-9.]+'
    vguidtwo: '^[-a-zA-Z0-9.]+'
    vguidthree: '^[-a-zA-Z0-9.]+'
    vguidfour: '^[-a-zA-Z0-9.]+'
    vguidfive: '^[-a-zA-Z0-9.]+'

Then updated the controller to use public function content($vguid, $vguidtwo, $vguidthree, $vguidfour, $vguidfive) { and assemble the URL based on that array.
Attempting to flush the cache gets The website encountered an unexpected error. Please try again later..  What did I miss?
Comment: It's going to treat those slashes as additional parameters and I'm not sure if there's an easy way around that. Will it always be in this format from now on? https://example.com/mobile-video/someidhere.cloudfront.net/sessions/forty-characters-or-more-of-vguid-here.mp4?invocationId=thirty-more-chars-here because if so, you could do path: '/mobile-video/{service}/sessions/{vguid}' it's dirty but it might work for you. If there are various scenarios you could always make several routes that point to that same controller with different formats for the path.
Comment: once you have a slash, it becomes a new parameter. You only have a path with one parameter defined, but the path you are trying to validate has multiple parameters, which is why it fails validation. This is why it failed even when you removed the validation code.
Comment: Possible duplicate of [Is it possible to include a forward slash in a route dynamic property?](https://drupal.stackexchange.com/questions/203517/is-it-possible-to-include-a-forward-slash-in-a-route-dynamic-property)
Comment: Possible duplicate of [Slashes in single route parameter or other ways to handle a menu tail with dynamic number of params](https://drupal.stackexchange.com/questions/175758/slashes-in-single-route-parameter-or-other-ways-to-handle-a-menu-tail-with-dynam)
Answer: My solution was to modify the javascript directing traffic to the mobile video page so that it replaced the slashes with triple underscores.
urlNoProtocol = src.replace(/\//i, "___");
The validation in mobilevideo.routing.yml was updated to vguid: '^[-a-zA-Z0-9._?=]+'
Then in MobileVideoController.php the content() function was updated to reverse the replacement.
$url = preg_replace('/___/','/', $vguid);

Route Parameter Validation Problem


SQL select column value with biggest number of duplicates

Question: I am having a problem I can't seem to solve. I have a data table that looks like this:
Example:
https://i.stack.imgur.com/tbKEk.png
I need to select the ID_JOB value which is duplicated the most. In this particular example it would be ID_JOB = 1.
Answer: Adapt this  to your specific SQL implementation. Substitute [job_table] with the table you are querying.
<code>SELECT TOP 1 ID_JOB
FROM job_table
GROUP BY ID_JOB
ORDER BY COUNT(*) DESC
</code>
You may need to add more ORDER BY logic in case a count "ties".
Comment: This was the right answer for me. Just a tip for those working with mysql this would be the code: SELECT ID_JOB FROM job_table GROUP BY ID_JOB ORDER BY COUNT(*) DESC LIMIT 1. Thanks.


How to pass view array from controller to view

Question: I know this is just plain simple.. but I think I am missing on something, I get this error, I tried everything before posting here
Trying to get property of non-object

controller
$temp = Servers::all();
        $data = array();
        foreach ($temp as $key) {
            $data[] = array(
                'srv_id'     => $key->srv_id,
                'srv_name'   => $key->srv_name,
                'srv_status' => $key->srv_status,
                'srv_files'  => $key->srv_files,
                'srv_disk'   => $this->ConvertBytes( $key->srv_disk ),
                'srv_ip'     => $key->srv_ip

                );
        }

return View::make( 'pages.server', compact( 'data' ) );

If I vardump the code this is what i get
var_dump
array(10) {
  [0]=>
  array(6) {
    ["srv_id"]=>
    string(3) "389"
    ["srv_name"]=>
    string(3) "u02"
    ["srv_status"]=>
    string(2) "ON"
    ["srv_files"]=>
    string(5) "43832"
    ["srv_disk"]=>
    string(9) "520.07 Gb"
    ["srv_ip"]=>
    string(13) "18.104.22.168"
  }
  [1]=>
  array(6) {
    ["srv_id"]=>
    string(3) "392"
    ["srv_name"]=>
    string(3) "u07"
    ["srv_status"]=>
    string(2) "ON"
    ["srv_files"]=>
    string(5) "42566"
    ["srv_disk"]=>
    string(9) "495.16 Gb"
    ["srv_ip"]=>
    string(13) "184.108.40.206"
  }

view
This is how I view my array in my page
@foreach($data as $server)
    {{ $server['srv_id'] }}
    {{ $server['srv_name'] }}

Comment: Why go through that entire loop when you could just do ``$servers = Servers::all();``, pass ``compact('servers')`` to the view, and then do ``@foreach ($servers as $server) ... @endforeach``? Much shorter, and easier to read and maintain. :)
Comment: I'd argue that the method probably belongs on the model, then. No matter, at least you got the problem solved. :)
Comment: Of course I can do that but, I wrapped an element in a function that is found within the controller.. and I can't call that function in my view
Answer: The reason your getting the Trying to get property of non-object error message is because the data in $temp is an array and your trying to access it as an object. Try this instead.
$temp = Servers::all();
$data = array();
foreach ($temp as $key) {
    $data[] = array(
        'srv_id'     => $key['srv_id'],
        'srv_name'   => $key['srv_name'],
        'srv_status' => $key['srv_status'],
        'srv_files'  => $key['srv_files'],
        'srv_disk'   => $this->ConvertBytes( $key['srv_disk'] ),
        'srv_ip'     => $key['srv_ip']
    );
}

Arrays can be accessed like so:
$foo['bar'];

While objects can be accessed like so:
$foo->bar;


Deriving Fisher Information Matrix over a Histogram Structure

Question: I am reading a classic paper by Barron and Risannen, entitled:

The Minimum Description Length Principle in Coding and Modeling

In this paper they state the following idea:
On this point I am interested in how they derive that the determinant of the Fisher Information Matrix (FIM) evaluates to the multiplication of the inverse of the histogram probability values.
It's probably a simple idea but I seem to have a conceptual block ....
Thus far, I am convinced that the FIM should be a diagonal matrix, which means that the determinant is just the multiplication of the diagonal elements. However, I can't imagine how the inverse probabilities arise.
Answer: We know that the $(i,j)^{th}$ element of the Fisher information matrix is defined as
$$
[\mathcal{I}(p)]_{i,j} = -E \left[ \frac{\partial^2}{\partial p_i \partial p_j} \log f(y|p,m) \right]
$$
$f(y|p,m) = mp_{i(y)}$, so that $\log f(y|p,m) = \log m + \log p_{i(y)}$.
Derivating with respect to $p_i$ yields
\begin{equation}
  \frac{\partial}{\partial p_i } \log p_{i(y)}=\left\{
  \begin{array}{@{}ll@{}}
    0, & \text{if}\ i(y)\neq i \\
    \frac{1}{p_{i(y)}}, & \text{otherwise}
  \end{array}\right.
\end{equation}
Similarly,
\begin{equation}
  \frac{\partial^2}{\partial p_i \partial p_i } \log p_{i(y)}=\left\{
  \begin{array}{@{}ll@{}}
    0, & \text{if}\ i(y)\neq i \\
    -\frac{1}{p_{i(y)}^2}, & \text{otherwise}
  \end{array}\right.
\end{equation}
Also, $\frac{\partial^2}{\partial p_i \partial p_j } \log p_{i(y)} = 0$ for any $j \neq i$.
We finally have to compute the statistical expectation of this quantity:
$$
[\mathcal{I}(p)]_{i,j} = \int_{i(y) = i}dy \frac{1}{p_{i(y)}^2} f(y|p,m) = \int_{i(y) = i}dy \frac{1}{p_{i}^2} m p_{i} = \frac{1}{p_i}
$$
The FIM is thus a diagonal matrix which $i^{th}$ entry is $p_i^{-1}$ ; and, as you mentioned, its determinant will be their product.


Two questions regarding notation in Bach WTC Fugue in C major

Question: Please can someone tell me what the a 4. circled in the image below means?

Secondly, I am scratching my head over the following rest. My assumption is that if the treble stave is being played (or sung) in parts, the top part sings or plays a quaver/eighth note, and the bottom plays/sings a dotted quaver/dotted eighth note. In other words there is a dotted quaver superimposed upon a quaver. But as I am playing piano solo I have no option but to play the dotted quaver correct? Phew!
Answer: "in 4 voices".  And regarding your second question: harpsichords and some other instruments can have multiple keyboards so that you can play this nicely.  If you don't have the requisite extra keys, the key here is that Bach shows the music: a top voice and a bottom voice converging on a common note, the top voice ending there and restarting with another note later, the bottom voice continuing with its phrase.
That's what the listener is supposed to be able to hear in their imagination from the timing of the note's onset, its loudness, and its release.  So you phrase the action on this key to your best ability such that it does not disrupt the listener's idea of the two voices' actions.
It's not the last time you'll encounter this kind of thing in the WTC.
Comment: Ah thank you very much! Out of interest, on a multiple keyboard harpsichord how would you play the three parts in this section with only two hands?
Comment: The point of different manuals is to allow rapid contrasts in dynamic or sound color. No one would use them for two voices in a fugue just to be hyper-exact on some random phrase ending.


Changing form field requirement via ajax

Question: I have a selectbox field, that should change the disabled and required states of another field based on the value selected in the selectbox field. The change must be done via ajax.
In my modules form_alter function I have the following code:
$form['field_type_app_details']['widget']['#ajax'] = array(
  'callback' => 'ajax_type_callback',
  'event' => 'change'
);
if ($form['field_type_app_details']['widget']["#default_value"][0] === 'First') {
  unset($form['field_version']['#disabled']);
  $form['field_version']['widget'][0]['value']['#required'] = true;
} else {
  $form['field_version']['#disabled'] = 'disabled';
  $form['field_version']['widget'][0]['value']['#required'] = false;
}

And the corresponding ajax_type_callback function looks like this:
function ajax_type_callback($form, $form_state) {
  return $form['field_type_app_details'];
}

What I would expect is, that when I change the value in the selectbox, to i.e. "Second", that the required and disabled states of field_version change accordingly.
What actually happens is, that when I change the value in the selectbox, the ajax request fires correctly, but doesn't change anything of field_version. Additionally, not even the changed value of field_version is saved, when the form gets submitted.
Where is the mistake?
Comment: You should be testing `$form_state->getValue(['field_type_app_details', 'widget', 0, 'value'])` or similar
Comment: @Clive Thanks for the input, but what is the difference between the two variants?
Comment: @Clive I've tried your recommendation, but that just gets me NULL instead of the actual value set in the field, which is "first" at this moment.
Comment: Yeah it was just an example, if you inspect what's in `$form_state->getValues()` you should be able to work out the exact keys you need. The main point is to get that value from the `$form_state`, not from the `$form`, which is the original form build and doesn't contain any user input
Comment: @Clive Thanks for the clarification, I'll try that.
Comment: @Clive If I use $form_state->getValue(['field_type_app_details', 0, 'value']) I get the correct value, but the states of field_version still don't change accordingly.
Comment: Probably because you're returning a different field in the ajax callback, and haven't defined a wrapper to target with the replacement
Comment: Is a wrapper actually necessary every time? I don't want to replace the whole field, just change the required state ...
Comment: If you don't use a wrapper you'll need to construct the AJAX commands yourself in the callback. Perfectly doable, but unnecessary work when you can just replace the element
Answer: Thanks to @Clive for pointing me in the right direction.
I've managed to accomplish what I want with the following changes to the form_alter function:
$form['field_type_app_details']['widget']['#ajax'] = array(
  'callback' => 'ajax_type_callback',
  'event' => 'change',
  'wrapper' => 'version-release'
);
$form['field_version']['#prefix'] = '
';
$form['field_version']['#suffix'] = '
';
$typeValueChangedByUser = $form_state->getValue(['field_type_app_details', 0, 'value']);
$typeToCheck = $typeValueChangedByUser ? $typeValueChangedByUser : $form['field_type_app_details']['widget']['#default_value'][0];
if ($typeToCheck  === 'First') {
  unset($form['field_version']['#disabled']);
  $form['field_version']['widget'][0]['value']['#required'] = true;
} else {
  $form['field_version']['#disabled'] = 'disabled';
  $form['field_version']['widget'][0]['value']['#required'] = false;
}

And the following change to the ajax_callback function:
function ajax_type_callback($form, $form_state) {
  return $form['field_version'];
}


HP DL180 G6 P410 8x SATA 1TB, what is the optimal configuration?

Question: I have a HP DL180 G6 with a P410 raid controller.
Presently this runs using 4x 1TB Samsung Spinpoint SATA drives, in a RAID10 configuration using default settings.
I am about to add a backplane to increase the drive capacity from 4 to 12 drives, and I plan to install 4 more 1TB SATA Drives.

The drives are matched and have close serial numbers (They arrived together in the Manufacturers pallet).
Model HD103UJ 1000GB/7200rpm/32M
Rated for 3GB/s

I will also be installing RHEL 6.1 x86_64.
My question is what would be the optimal RAID settings (stripe etc.) for this configuration?
To recap:

8x Model HD103UJ 1000GB/7200rpm/32M
Rated for 3GB/s
RAID 10 configuration.

Thanks in advance.
Update for role:

Server is to become an iscsi target for an internal openstack deployment currently underway. (Glance)
Will also provide virtualisation through KVM
Comment: Your question is too vague...what are you doing with that server? Is it a DB server? Application server?...
Comment: Getting a bunch of drives from the same batch means they'll probably all have the same defects, meaning they're more likely to fail at the same time...
Comment: Already a dead setup. even 8 such drives wont make it fast. I run a raid of 8xVelociraptors, 300gb each, 10k drives and I REGULARLY overlaod it - enoug hto get a 2nd level cache now that is SSD based.
Comment: Well, it may not be helpfull but at the end a ford focus is not suitable to drive formula 1 races. Heavy virtualization needs heavy disc io - whether you like it or not. Your discs are slow end user side discs, large and not made for IO. Raid 10 is the b est you can make, but it is like a beefed up ford focus - still not suitable for the job.
Comment: @ChrisS whilst it has been a long time since I read into RAID, it at least used to be the case that it was far better to have closely matched drives to ensure that parity was not adversely affected, and that ideally you should look for the "same batch" drives, though I do take your point.
Comment: @TomTom, "Already a dead setup" that doesn't help at all, I just want to know the optimal setup using the hardware listed to avoid rebuilding later, I am not looking for the fastest available otherwise I would be using SAS drives, and SSDs
Comment: @Alex, I added an update to the end of the question to include the proposed role, thanks.
Comment: @Oneiroi That information might have been true years ago when HBA were particularly picky about getting matching drives, firmware, etc; it's usually unsound advice today.
Answer: A few quick things...
Does the Smart Array P410 controller in your system have a battery-packed or flash-backed cache unit? If not, you will want to add one in order to have acceptable write performance (and possibly allow expansion of the drive array).
Are you doing this as a complete rebuild of the server, or are you looking to expand in-place?
I'd recommend RAID 1+0 in general, but especially with high-capacity low-speed drives. You can probably get by with the defaults suggested by the HP Array Configuration Utility.
Comment: It is going to be a complete rebuild, I have already begun the process of migrating services off this system, I cam currently using 1+0 with default stripe, I am just unsure if that is the correct configuration.
Comment: Yep, it's fine. Do you have the cache module and battery attached to the card?
Comment: it has 256MB cache module but I do not believe it has a battery module I will liase with our supplier about getting one, thanks.
Answer: I always use RAID10 in iSCSI setup especially for virtualization.
To me it's the ideal balance between performance and reliability. And on top of it, it's much faster to rebuild a failed disk than in RAID 5 configuration. Especially with slowish 1TB drives.
Answer: My default answer to any of these questions is always RAID 10, unless there's very special circumstances anyway. It's a great balance of performance and resilience, that said trying to get the best performance out of big slow consumer drives always strikes me as an odd choice - it's a bit like entering the Indy 500 in a tricked out Honda Civic, it'll start but will it end. Specifically I'd be worried that those disks have a 30% duty cycle, like every other cheapo 7.2k SATA, and driving them significantly over that will massively impact their MTBF, make sure you have at least two spares very close to hand. I'd also be a little worried about using non-HP disks with that controller but they're the choices you've made I guess.


Encontrar o índice em um vetor de dicionários baseado no valor

Question: Se eu tiver um array de dicionários e quiser encontrar o índice no array de um determinado valor do dicionário, como eu faço?
Ex:
palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavras = [palavra1, palavra2]

Caso eu queira encontrar qual é o índice em 'palavras' que corresponda a 'valor2', como eu devo proceder?
Answer: Pra verificar se o valor da chave 'palavra' corresponde a 'valor2':
palavra1.get('palavra') == 'valor2'  # True

Isso evita que você tenha um KeyError por acessar uma chave que não existe.
Sabendo isso, você pode fazer um loop que itera sob sua lista e para quando encontra um resultado válido:
palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavras = [palavra1, palavra2]

for indice, palavra in enumerate(palavras):
    if palavra.get('palavra') == 'valor2':
        break

print('Indice:', indice)  # 1
print('Palavra:', palavra)  #  {'palavra': 'valor2'}

Você também pode fazer o mesmo com uma expressão geradora:
palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavras = [palavra1, palavra2]

indice, palavra = next((i, p) for i, p in enumerate(palavras) if p.get('palavra') == 'valor2')
print('Indice:', indice)  # 1
print('Palavra:', palavra)  #  {'palavra': 'valor2'}

Answer: O mesmo valor pode estar contido em vários elementos da sua lista de dicionários. Uma solução seria montar uma lista contendo o índice de cada elemento/dicionario no qual o valor foi encontrado, veja só:
palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavra3 = {'palavra': 'valor3'}
palavra4 = {'palavra': 'valor1'}

palavras = [ palavra1, palavra2, palavra3, palavra4 ]

idxlst = [i for i, d in enumerate(palavras) if d["palavra"] == "valor1"]

print( idxlst )

Saída:
[0, 3]