Django - ValidationError does not display

Question: I recently tried the forms validations and faced an issue with ValidationError().
The form error does not appear in my website when I submit the form.
Here is the code:
forms.py
class ArticleForm(forms.ModelForm):

    def clean_titre(self):
        titre = self.cleaned_data['titre']
        if len(titre) < 5:
            raise ValidationError('myError')
        return titre

form = ArticleForm()

template.html

TITRE
  {{ form.titre.errors }}
  {{ form.titre }}

views.py
def AddArticle(request):
    form = ArticleForm(request.POST, request.FILES)

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.user = request.user
        save_it.save()
        form.save_m2m()
        return HttpResponseRedirect('/')

What did I do wrong?
--- EDIT ---
Full template.html
<form class="form" action="{% url "article.views.AddArticle" %}" method="post" enctype='multipart/form-data'>
    {% csrf_token %}

TITRE
      {{ form.titre.errors }}
      {{ form.titre }}

SUMMARY
      {{ form.media }}
      {{ form.summary.errors }}
      {{ form.summary }}

CONTENU
      {{ form.media }}
      {{ form.contenu.errors }}
      {{ form.contenu }}

      {{ form.image.errors }}
      {{ form.image }}

TAGS
      {{ form.tags.errors }}
      {{ form.tags }}

   <input type="submit" class="btn btn-default" value="Submit" autocomplete="off" autocorrect="off" />
</form>

I'll post the full forms.py too, it may help.
forms.py
class ArticleForm(forms.ModelForm):

    def clean_titre(self):
        titre = self.cleaned_data['titre']
        if len(titre) < 5:
            raise ValidationError('myError')
        return titre

    class Meta:
        model = Article
        exclude = ['date', 'rating', 'user']

        widgets={
            "titre":forms.TextInput(attrs={'placeholder':'Le titre', 'class':'form-control'}),
            "contenu":forms.Textarea(attrs={'placeholder':'Le Contenu de votre message', 'class':'form-control'}),
            "image":forms.FileInput(attrs={'placeholder':'Votre Image', 'id':'uploadBtn'}),
            "tags":TagWidget(attrs={'placeholder':'Vos Tags', 'class':'form-control'}),
        }

form = ArticleForm()

Comment: Where's the rest of that view? What happens if is_valid is not True? Or if it's not a POST?
Comment: I don't have the rest, I didn't know I needed one, what should I write it the "else:"?
Comment: In that case you would definitely get an exception, because every view must return a response. If your form is not valid but you are not getting an exception, you cannot be using this view at all.
Answer: You are missing the else portion within your view. Here is the general flow of what forms usually do:

Users navigate to a page via GET which presents them with a form
Users fill in the form and submit it by using POST
If the form is valid, users are directed to a different page
If the form is not valid, users are presented with the same page as in step 1 with the validation errors displayed. After users correct them, they are process to step 2.

Here is that flow in django view:
def AddArticle(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.user = request.user
            save_it.save()
            form.save_m2m()
            return HttpResponseRedirect('/')

    else:
       form = ArticleForm()

    return render(request, 'template.html', {'form': form'})

I would however look into using class based views in Django. Initially they can seem very confusing but over time you will learn to appreciate them. Docs. Another useful resource when learning CBV.
By using CBV, the above can be simplified to:
class AddArticleView(CreateView):
    success_url = 'name_of_view_here'
    form_class = ArticleForm
    template_name = 'template.html'

# urls.py
urlpatterns = patterns('', url(r'^articles/add/$', AddArticleView.as_view()))

Template
You also need to include the overall form error in the template, in addition to each field errors:
<form class="form" action="{% url "article.views.AddArticle" %}" method="post" enctype='multipart/form-data'>
    {% csrf_token %}
    {{ form.non_field_errors }}
    ...
</form>

Please note that you might need to wrap the errors with some bootstrap markup. More info in docs
Comment: But the mystery is that the view couldn't possibly have worked the way it is now, so there is something OP is not telling us.
Comment: @Sia can you post your complete form template since currently you only posted  template for a single form field
Comment: not sure as well. try debugging with ipdb to verify that form is indeed invalid and that errors are present in the view. if so, then a bug is in the template. if not, then bug could with with form or view


Show that $\hat{\beta}$ and SSE are independent

Question: For a multiple linear regression model y = X$\beta$ + $\epsilon$, the maximum likelihood estimator of $\beta$ and e is noted as $\hat{\beta}$ and e respectively.
Please shows that $\hat{\beta}$ and SSE = $e^T$e are independent.
Comment: This seems a homework-type question. What have you tried?
Comment: The claim is not true in general; it does hold for the normal linear model.
Comment: Please add the [tag:self-study] tag.
Answer: In the classical normal linear regression model (with deterministic regressors) we have $y \sim \mathop{\mathcal N}\left(X\beta, \sigma^2I\right)$.
Consider
$$
\begin{pmatrix}
\hat{\beta}\\
e
\end{pmatrix}
=
\begin{pmatrix}
\left(X^\top X\right)^{-1} X^\top \\
I - X\left(X^\top X\right)^{-1} X^\top
\end{pmatrix}
y
$$
and
$$
\begin{align}
\mathop{\text{Cov}}\left(\hat\beta, e\right)
&=
\left(X^\top X\right)^{-1} X^\top \mathop{\text{Cov}}\left(y,y\right) \left(I - X\left(X^\top X\right)^{-1} X^\top\right)^\top \\
&=
\left(X^\top X\right)^{-1} X^\top \sigma^2 I \left(I - X\left(X^\top X\right)^{-1} X^\top\right)\\
&=
0.
\end{align}
$$
What does this tell you about $\hat\beta$ and $e$?


Guitar pickup selection

Question: Most electric guitars and some basses allow players to select different combinations of pickups. For example, modern Stratocasters have a five-way switch between the neck, middle, and bridge pickups. Some of the Fender documentation refers to the neck pickup as "Rhythm" and the middle or bridge pickup as "Lead." They also note that only the neck and middle pickups have tone control; the bridge does not.
What does this all mean for guitarists in practice? What are the differences in sound between different pickup positions? Are neck pickups better suited for clean rhythm sounds, and bridge pickups better suited for crunchy lead sounds, as the Fender manuals suggest? Where does the middle pickup fit into all this?
Answer: Because of the way vibrations on a string work, from the fundamental all the way up to the highest harmonics, the closer to the bridge you get, the more the balance skews towards higher harmonics. Conversely a pickup at the 12th fret would be overwhelmed by the fundamental on the open string.
From Wikipedia:

So what Fender mention is generally correct: you get a fatter sound from the neck pickup, with more lower harmonics, which is usually good for playing rhythm guitar. The bridge pickup gives a tone which can cut through the sound of a band, with the bias towards higher frequencies, and while it may be lower amplitude, it can be very clear.
A tone pot is usually used to roll off higher frequencies, so for example if the bridge pickup is too piercing, you can roll off some of those top frequencies to make the sound a bit 'mellower'
The middle pickup is just halfway between the two - giving a bit of a blend. Depending on wiring, one or more pickups may give you the option to be 'out of phase' which lets a combination of two pickups actually cancel some frequencies, allowing even more tonal variety.
Comment: On Teles, in particular, the neck pup is exactly under the 24th fret harmonic node. Whether accidental or purposely I don't know. But the sound of that harmonic (also over 5th fret) disappears when the neck pup is on, but re-appears when the bridge in switched on.
Answer: A pick-up will pick up (!) the sound a string is making just above it. The three pups on Strats are (or used to be, originally) identical. The string vibrates at a different amplitude - hope it's the correct word - as in the movement is greater the closer to the string centre you get. So by the bridge, the pup will hear a tighter, thinner sound. One uses the pup configuration one likes for a particular situation. Generally, neck pups will give a rounder sound, more suited to chord/rhythm playing. Les Pauls have a 'treble/rhythm' switch, between bridge and neck pups.
I guess Leo thought that if you wanted a more piercing sound, thus using the bridge pup, there would be no necessity to attenuate the sound with a tone control. Jazz players will often use the neck pup, and roll some treble off that.
It emulates where you pluck the strings, to a degree. As in, if you use a pick close to the bridge, then the sound will be a lot less bassy than anywhere else. That's the sort of tone that the bridge pup hears.
A lot of guitars these days will wear different pups in different places along the strings, and can be switched in and out of phase.
The middle pup gives a sound somewhat between the other two. Fender was an electrician rather than a guitarist, but realised that there was another sound to be harvested between bridge and neck, and on the original guitars, he only had a 3-way switch. We soon found that it could be put carefully into the 'in-between' positions, giving 5 options. Later, Strats were equipped with the now common 5-way.
This still left a decent sound unavailable, that of bridge and neck combined. A Strat I played some years ago got over this by having 3 push button switches, one for each pup. This gave 2 more options also - all on and all off ! The bridge and neck combination on my own guitar ( not a Strat) is one that works well for rhythm playing in a big band situation - the roundness is there with an edge to cut through for the more choppy bits.
I played a bass last year, Steinberg, maybe, that had one pup, that was slideable on rails. The tone could be changed by moving it about 4/5 " between bridge and neck. Different !

Guitar pickup selection


Python not catching MemoryError

Question: I've wrapped some code that can run out of memory with a try/except block. However, though a MemoryError is generated, it is not caught.
I have the following code:
    while True:
        try:
            self.create_indexed_vocab( vocab )
            self.reset_weights()
            break;
        except MemoryError:
            # Stuff to reduce size of vocabulary
            self.vocab, self.index2word = None, None
            self.syn0, self.syn1 = None, None

            self.min_count += 1
            logger.info( ...format string here... )

I get the following Traceback:
File "./make_model_tagged_wmt11.py", line 39, in <module>
  model.build_vocab(sentences)
File "/root/CustomCompiledSoftware/gensim/gensim/models/word2vec.py", line 236, in build_vocab
  self.reset_weights()
File "/root/CustomCompiledSoftware/gensim/gensim/models/word2vec.py", line 347, in reset_weights
  self.syn0 += (random.rand(len(self.vocab), self.layer1_size) - 0.5) / self.layer1_size
File "mtrand.pyx", line 1044, in mtrand.RandomState.rand (numpy/random/mtrand/mtrand.c:6523)
File "mtrand.pyx", line 760, in mtrand.RandomState.random_sample (numpy/random/mtrand/mtrand.c:5713)
File "mtrand.pyx", line 137, in mtrand.cont0_array (numpy/random/mtrand/mtrand.c:1300)
MemoryError

I'm running Python 2.7.3 under Ubuntu 12.04
The reset_weights line self.syn0 is exactly the line I am expecting to raise the exception (it allocates a big array). The puzzling thing is that I can't catch the memory error and do things that will make the array size smaller.
Are there special circumstances that result in the MemoryError being unable to be caught?
Comment: are you sure those are the lines that throw the exception? try to change the except line to except: and print something there just to make sure those are the right lines.
Comment: @Eponymous is the argument `vocab` in your call to `create_indexed_vocab` supposed to be `self.vocab` ? And, to @DannyElly's point, perhaps there's a call to `reset_weights` hidden in a the call to create_indexed_vocab? That likely wouldn't matter here, since it's reporting a MemoryError...
Comment: @Eponymous I would still change the except line and print something there. Oftentimes, we are positive we debug the right block of code when in fact the problem is in a different one. that can very frustrating. When I encounter such BUGs I just add as much prints as I can to make sure that I'm working on the right problem.
Comment: @DannyElly it seems as though the stacktrace shows a call to reset_weights() which is the last line before the except. I expect that reset_weights is being called.
Comment: @Eponymous are you sure the lines in the try block throws an exception. Did you have prints before and after the suspected line (`self.reset_weights()`) and see only the before print. this is the best that I can help. I know I'm suggesting trivial and stupid pointers but we are all humans and sometimes we are missing obvious things. good luck to u!
Comment: @apgwoz `vocab` and `self.vocab` are different. `vocab` is a local variable that takes 3-4 hours to calculate. `create_indexed_vocab` uses it to initialize `self.vocab` and `self.index2word`. There isn't a call to `reset_weights` in the `create_indexed_vocab`, it only calls the logger and built-ins.
Comment: @DannyElly `except:` didn't catch anything. I'm giving up. One way I haven't tried of catching the uncatchable exception is to put the allocation code and the rest in a separate process. I can pass the adjustment parameters and vocab through interprocess communication and detect if the process exits successfully through printing something. Ugly.
Answer: Note that because of the underlying memory management architecture (C's malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.
(See the docs)
Usually, you can catch MemoryErrors nevertheless. Without knowing what exactly happens when a MemoryError gets thrown, I'd guess that you might not be able to catch it when shit really hit the fan and there's no more memory there to handle it.
Also, since you may not be able to really recover from it (see above), it probably wouldn't make that much sense to catch it. You should really avoid running out of memory and limiting the amount of memory your program uses by e.g. only allowing a list to have a limited size.
Comment: RAM is a shared resource, thus, avoiding running out of memory is impossible. Even if the `resource` module were available on MS-Windows so there was a built-in way to check memory, another process could eat up some of the memory you want between the time you check available memory and the time you allocate it. So the memory allocation cycle for a program that wants to use as much RAM as possible needs to be `while(allocation fails): adjust requirements; allocate`. In Python, the only way I know to detect a failed allocation is a `MemoryError`.
Comment: That hint in the docs is why I wrote this question. I want to know if uncatchable exceptions actually happen (and if it might be happening in my specific case) or if my python-fu was too low and there was a language nuance I was missing.
Comment: I'm giving up, so I'll give you the accepted answer. (Yours being the only answer.)
Comment: "by e.g. only allowing a list to have a limited size"  But what size?  Using large blocks of memory can speed up computations.  How do we find the right balance in Python, considering memory differs from machine to machine and minute to minute?
Comment: @Eponymous I know you made your comment many years ago and probably have learned that running out of memory is possible. Systems will have physical limits on how much storage they have and how much storage is available to user/system processes. Otherwise you could write a program that first filled RAM, then persistent storage, and crashed leaving the system potentially permanently broken. Even in 2023 it's possible to exceed virtual memory and system configuration will lead to process termination, or OS crash.

Python not catching MemoryError


Inline entity form shows a content type select list

Question: I am using Inline entity form for a non-commerce project.
The settings are:Widget:multiple values,Node:Allow users to add existing content.
Mode:Views:Filter by Entity reference view.So I have created an Entity reference view to show only nodes that have been created by the user.
The issue is:When looking at the Inline entity form to create or add existing content,there is a dropdown with all the content types of the site.This only appeared when I change the mode to Views:Filter by Entity reference view
How can I remove that?
thanks
See image attached
Comment: Actually it allows me to create a new node of ANY content type.However,I want to be able to create a specific content type,the one that the view uses.
Answer: Try editing the inline entity field and only setting one entity (ie Company content type in your example) that can be referenced.
Answer: I managed to solve this by making changes to inline_entity_form.module specifically the inline_entity_form_settings function. This fix requires you to have already selected the target bundle in the ief tables module and limits to only one content type (I'm sure someone can easily adapt this logic to include multiple by adding a separate settings option).
After the line
<code> // Allow other modules to alter the settings.
drupal_alter('inline_entity_form_settings', $settings, $field, $instance);
</code>
add in the following code:
<code>if (empty($settings['bundles']) && isset($instance['widget']['settings']['type_settings']['ief_table_view_mode']['bundles'])) {
    if (array_search('1', $instance['widget']['settings']['type_settings']['ief_table_view_mode']['bundles']) != false) {
        $settings['bundles'][] = array_search('1', $instance['widget']['settings']['type_settings']['ief_table_view_mode']['bundles']);
    }
}
</code>
Comment: I'd like to point out that modifying a contributed module's code is not the right way to handle a situation like this. You should instead be adding a custom module that implements the hook offered by that call to drupal_alter.

So, if your custom module is named 'custommodule', you would have a function like:
function custommodule_inline_entity_form_setttings_alter($settings, $field, $instance)


Prove the matrix is positive

Question: Consider the matrix $A=\begin{bmatrix}
    1 & 1/2 & 1/3 &\dots &1/n \\
    1/2 & 1/3 & 1/4 &\dots  &1/(n+1) \\
    \vdots & \vdots & \vdots & \vdots & \vdots\\
    1/n & 1/(n+1) & 1/(n+2) & \dots& 1/(2n-1)
    \end{bmatrix}$
Prove that $A$ is positive.
My work: $A$ is diagonalisable, symmetric but I can't seem to put these facts togheter to help me. I tried to prove by induction (a naive attempt) that the determinant of its minors is always positive but knowing $det(A^{k,k})>0$ there is no information of $det(A^{k+1,k+1}).
Comment: A pretty quick way is to see $A$ as a Gram matrix of an inner product under some basis.
Comment: That was fast, thank you! Can you please post it as answer so I can accept it?
Comment: @2ndYearFreshman   if you wish someone to be notified of your reply to a comment, begin your reply with an @ sign and the beginning of that username.
Comment: @SangchulLee I think the OP here is addressing you,  requesting you to post a full answer
Comment: @WillJagy Thank you.
Answer: tried two , Sylvester Inertia
$$ Q^T D Q = H  $$
$$\left(
\begin{array}{rrr}
1 & 0 & 0 \\
 \frac{ 1 }{ 2 }  & 1 & 0 \\
 \frac{ 1 }{ 3 }  & 1 & 1 \\
\end{array}
\right)
\left(
\begin{array}{rrr}
60 & 0 & 0 \\
0 & 5 & 0 \\
0 & 0 &  \frac{ 1 }{ 3 }  \\
\end{array}
\right)
\left(
\begin{array}{rrr}
1 &  \frac{ 1 }{ 2 }  &  \frac{ 1 }{ 3 }  \\
0 & 1 & 1 \\
0 & 0 & 1 \\
\end{array}
\right)
 = \left(
\begin{array}{rrr}
60 & 30 & 20 \\
30 & 20 & 15 \\
20 & 15 & 12 \\
\end{array}
\right)
$$
$$ Q^T D Q = H  $$
$$\left(
\begin{array}{rrrr}
1 & 0 & 0 & 0 \\
 \frac{ 1 }{ 2 }  & 1 & 0 & 0 \\
 \frac{ 1 }{ 3 }  & 1 & 1 & 0 \\
 \frac{ 1 }{ 4 }  &  \frac{ 9 }{ 10 }  &  \frac{ 3 }{ 2 }  & 1 \\
\end{array}
\right)
\left(
\begin{array}{rrrr}
420 & 0 & 0 & 0 \\
0 & 35 & 0 & 0 \\
0 & 0 &  \frac{ 7 }{ 3 }  & 0 \\
0 & 0 & 0 &  \frac{ 3 }{ 20 }  \\
\end{array}
\right)
\left(
\begin{array}{rrrr}
1 &  \frac{ 1 }{ 2 }  &  \frac{ 1 }{ 3 }  &  \frac{ 1 }{ 4 }  \\
0 & 1 & 1 &  \frac{ 9 }{ 10 }  \\
0 & 0 & 1 &  \frac{ 3 }{ 2 }  \\
0 & 0 & 0 & 1 \\
\end{array}
\right)
 = \left(
\begin{array}{rrrr}
420 & 210 & 140 & 105 \\
210 & 140 & 105 & 84 \\
140 & 105 & 84 & 70 \\
105 & 84 & 70 & 60 \\
\end{array}
\right)
$$
Comment: Upvoted because it taught me the Sylvester Inertia.
Answer: (Migrated from comment)
The matrix in question is called the Hilbert matrix. To see that $A$ is positive-definite, let $x \in \mathbb{R}^n$. Then
$$ x^T A x
= \sum_{i, j = 1}^{n} \frac{x_i x_j}{i+j-1}
= \sum_{i, j = 1}^{n} \int_{0}^{1} t^{i+j-2} x_i x_j \, dt
= \int_{0}^{1} \left( \sum_{i=1}^{n} x_i t^{i-1} \right)^2 \, dt
\geq 0 $$
Moreover, the equality in the last step holds if and only if $\sum_{i=1}^{n} x_i t^{i-1} \equiv 0$ on $t \in [0, 1]$, which is equivalent to $x = 0$. Therefore $A$ is positive-definite as required.
Answer: This is not a new answer. It is essentially the same ideas as already presented by  Sangchool Lee. I'm giving it just as yet another application of the identity
$$ \frac{1}{x} = \int_0^\infty e^{-sx} ds.$$
Observe:
$A_{i,j} = \frac{1}{i+j-1}$.
\begin{align*} (Av,v) &= \sum_{i,j} \frac{v_j v_i}{i+j-1}\\
  & = \sum_{i,j} \int_0^\infty  (e^{-(j+1/2)s} v_j) (e^{-(i+1/2)s}v_i) ds \\
  & = \int_0^\infty \sum_{i,j}   (e^{-(j+1/2)s} v_j) (e^{-(i+1/2)s}v_i)ds \\
  & = \int_0^\infty \sum_{j} (e^{-(j+1/2)s} v_j)^2 ds\\
  & \ge 0
\end{align*}
Note that the proof works whenever $A_{i,j} = 1/(f(i) + f(j))$ where $f$ is a positive function.

Prove the matrix is positive


Seeking proof that powers of 3 greater than 9 divided into powers of 10, decimal representation with period greater than 1

Question: Anybody have a good proof for this fact? 1/3 and 1/9 have decimal representations with period 1, but numbers of the form (10^a)/(3^b) where b > 2 have period 2 or higher from what I've been able to see. I've tried looking it up with no luck, was wondering if someone could point me in the right direction. I have a feeling modular arithmetic will play a role here.
Comment: $$10^a = (1+9)^a = \sum_{k=0}^a \dbinom{a}{k}9^k$$ So, when you divide by $3^b$, you get:  $$\sum_{k=0}^a \dbinom{a}{k}3^{2k-b}$$ which for $b\in \{3,4\}$ gives: $$\dfrac{1}{3^b}+\dfrac{a}{3^{b-2}}+\text{an integer}$$ And as $b$ increases, the period likely becomes more difficult to calculate.
Answer: The decimal with a non-repeating initial part $a$ that lasts $n$ digits and repeats the digit $d$ starting at place $n+1$ has a value $$\frac{a}{10^n} + \frac{d}{9 \times 10^n} = \frac{9a + d}{9 \times 10^n}$$ (for example, $0.27444\ldots = \frac{27}{100} + \frac{4}{900}$). The fractions that can be written in such a form are those whose lowest-terms denominators divide $9 \times 10^n$, and the highest power of $3$ that divides $9 \times 10^n$ is $9$.
Answer: The period of the decimal representation of fractions of the form $\ \frac{n}{3^b}\ $ with $\ n\ $ not divisible by $3$ is the order of $\ 10\ $ modulo $\ 3^b\ $—i.e. the smallest positive integer $\ p\ $ such that $\ 3^b\mid 10^p-1\ $. For $\ b\ge 2\ $, $\ 10^{3^{b-2}}=1+m_b3^b\ $ where $\ m_b\equiv 1\ (\hspace{-0.6em}\mod3)\ $, from which it follows that the order of $10$ modulo $\ 3^b\ $, and hence the period of the decimal representation of $\ \frac{n}{3^b}\ $, is $\ 3^{b-2}\ $.
The above assertion can be proved by induction.  It's clearly true for $\ b=2\ $, so let $\ b\ge2\ $ be any integer for which the order of $10$ modulo $\ 3^b\ $ is $\ 3^{b-2}\ $ and $\ m_b=\frac{10^{3^{b-2}}-1}{3^b}\equiv 1\ (\hspace{-0.6em}\mod3)\ $. Then $\ 10^{3^{b-2}}=1 + 3^b m_b\ $, so
\begin{align}
 10^{3^{b-1}}&=\left(1 + 3^b m_b\right)^3\\
&=1+3^{b+1}m_b+3^{2b+1}m_b^2+3^{3b}m_b^3\\
&=1+3^{b+1}\left(m_b+3^bm_b^2+3^{2b-1}m_b^3\right)\\
&\equiv\ 1\ \left(\hspace{-0.7em}\mod3^{b+1}\right)\ ,\text{ but}\\
10^{3^{b-2}}&\not\equiv 1\ \left(\hspace{-0.7em}\mod3^{b+1}\right)\ .
\end{align}
Therefore, the order of $10$ modulo $\ 3^{b+1}\ $ is $\ 3^{b-1}\ $, and
\begin{align}
 \frac{10^{3^{b-1}}-1}{3^{b+1}}&=m_b+3^bm_b^2+3^{2b-1}m_b^3\\
&\equiv 1\ (\hspace{-0.9em}\mod3)\ ,
\end{align}
which completes the induction.


Update Metro App UI ObservableCollection from Background Task

Question: Is two-way communication possible between a BackgroundTask and a Metro App UI?
The desired functionality is as follows:

If Metro App is closed/suspended, BackgroundTask continues to do what
is required.
If Metro App is open/resumed, BackgroundTask continues to do what
is required, but also notifies the Metro App, that new data is
available.
Metro App then updates its UI with the new data.    Metro    App UI
allows user to take certain actions.
These actions are Queued in memory. BackgroundTask monitors
this memory Queue and processes these actions.

Please advise if this is possible, or suggest a design to meet these requirements.
Answer: Just use a background thread or a Task
Task.Factory.StartNew(() =>
{
   // Download data
}).ContinueWith(t =>
{
   // Update UI
}, Scheduler.FromCurrentSynchronizationContext());

The ContinueWith in the synchronization context is important because you will get an exception for updating an ObservableCollection from a different thread, you can also use the Dispatcher to execute a code block on the UI thread.

Above text remain to show original answer:
The MSDN guidelines for background tasks as linked here clearly state:

Background tasks shouldn't update the UI at all except for system UI like notifications etc
Background tasks should communicate with the application via persistent storage

Your problem needs to be addressed by maintaining a "new data" storage for your application, the background worker will download data and write it here, your application when resumed / opened will check and remove that data allowing you update your UI - the storage acts as your in-the-middle queue.
Comment: Well then, you don't need to update the UI do you? In fact, the MSDN guidelines tell you explicitly not to so your question is moot. http://msdn.microsoft.com/en-gb/library/windows/apps/xaml/hh977051.aspx If instead you're asking for a way to queue tasks and then have them picked up by a background task then you should have asked that question instead.
Comment: @c0D3l0g1c the guidelines I linked state that you should use persistent storage to communicate between your application and background-task, if your app is closed / suspended then you'd have a problem. You'll need to push any data downloaded by the task into storage which your app will then pick up when it's resumed / started again.
Comment: @c0D3l0g1c essentially yes, background task won't do it itself, you'll have to do it, the MSDN pages are always a good place to start for the Microsoft technologies, especially if you're not familiar with them.
Answer: Found a good detailed understanding of BackgroundTasks here:
Introduction to BackgroundTasks
Which implicitly answers my question.


Can we say the frequentist interpretation of probability is more appropriate in the dice rolling problem?

Question: Suppose we role a dice and see what we get, the sample space is $\{1,2,3,4,5,6\}$ and each outcome occurs with probability 1/6. For example, if we look at the probability that 6 appears, it seems natural to interpret the probability of 1/6 as $plim \frac{n_6}{n}$ where $n$ is the total number of trials and $n_6$ is the number of times we get a 6. That is to say, the frequentist interpretation of 1/6 as the limiting frequency seems natural. This is also something that could be verified using repeated experiment.
My questions are:

In this example, how to take a Bayesian interpretation of the probability 1/6?  Is the Bayesian interpretation less appropriate/suitable in this example compared to the frequentist interpretation?

In general, is it true that the Bayesian interpretation of probability makes more sense under certain scenarios, while the frequentist interpretation of probability is better in other scenarios?
Comment: We don't even need frequentism for this example where the probabilities are well defined without repeated sampling; the "classical probability" described in the following link suffices https://plato.stanford.edu/entries/probability-interpret/#ClaPro
Comment: See my answer at https://stats.stackexchange.com/questions/332026/can-we-think-of-a-probability-in-both-the-classical-and-subjective-sense-simulta/332218#332218 Also Bayesians need idealized frequencies to give meaning to probabilities!
Comment: @kjetilbhalvorsen Thanks! I've read it. Very insightful!
Comment: @JohnMadden Thanks, John! This is extremely helpful!
Answer: If you know that the die is fair, then this can equally be viewed as a Bayesian interpretation with a dogmatic prior that puts all prior probability on the die being fair, so one could argue that the Bayesian interpretation does equally well.
If, on the other hand, the die is not fair, then, if you have prior knowledge on the sense in which it is not fair, you may improve your inference over the frequentist estimator $n_6/n$, especially when $n$ is "small".
Comment: Thanks! Very interesting. So these two interpretations are not entirely exclusive for each other.
Answer: Bayesians and modern "frequentists" both use the same underlying laws of probability theory, and in my view, both can reconcile their views on the "frequentist definition of probability".  Both groups of practitioners agree with the strong law of large numbers, which says that if you have an exchangeable sequence $X_1,X_2,X_3,...$ then (with probability one):$^\dagger$
$$\mathbb{P}(X_i \in \mathcal{A}) = \lim_{n \rightarrow \infty} \frac{1}{n} \sum_{i=1}^n \mathbb{I}(X_i \in \mathcal{A})
\quad \quad \quad \text{for any measurable set } \mathcal{A}.$$
Frequentists take this as a "definition" of probability, whereas Bayesians use an alternative interpretation of probability (usually an epistemic interpretation), but also agree that it corresponds to limiting frequency in this case.  Bayesians don't disagree with the strong law of large numbers, and they tend to view it as something that clarifies the notion of "repeated trials" in the frequentist viewpoint ---i.e., the idea of infinitely repeated trials of a stable experiment is provided by the concept of exchangeability.
If you go back to the older probabilists like Venn, Reichenbach and Von Mises, you will find that they made philosophical arguments about the frequentist meaning without the aid of Kolmogorov's strong law of large numbers.  To do this, they tended to invoke the idea of repeated trials that could occur hypothetically infinitely often, under unchanging conditions.  This is captured well by the modern condition of exchangeability of an infinite sequence, which is the basis for the strong law of large numbers.

$^\dagger$ One might wonder if it is legitimate to invoke laws of probability theory in answer to determining the meaning of probability --- i.e., whether this is circular logic.  For this purpose we may treat $\mathbb{P}$ as purely a mathematical operator, and then imbut it as a "probability" only once we have satisfied ourselves that it meets the requirements of the meaning of this concept.


Mutating a button into a form within a tabel cell

Question: I currently have a table cell which contains a form and allows me to update a row in the database.
However I hope to be able to use Jquery to make the UI cleaner and user friendly.
http://i48.tinypic.com/mvq80n.png
what I visualize the end result to be after an onclick event.
http://www.facebook.com/ajax/messaging/attachment.php?attach_id=f174a5e079756755f4c947eb8960b556&mid=id.380435762042825&hash=AQAYxjuwritoKoQZ
Answer: Jeditable might be of use to use. It allows on click (or other events) to make text editable. Here you can find some demos.
Comment: can u go a little into the specifics?
Comment: Look at the source code if the demo. That should be helpful. Also the documentation provides examples....


For which of the starting polynomials can Alice ensure that Bob does not win in finite number of moves?

Question: Note: More than one option maybe correct.
Alice and Bob are playing a game. At the beginning of the game, there is a
cubic polynomial with integral coefficients written on the blackboard, which we denote as
the starting polynomial. The two players take turns one by one. In each turn, the player either chooses any natural number $n$ and replaces the existing cubic polynomial $f(x)$ on the blackboard by any one of $f(n + x), f(nx), f(x) + n$ or just changes the sign of the
coefficients of $x^2$ , i.e. if the existing polynomial is $a_0 + a_1x + a_2x^2 + a_3x^3$, then he can replace it by $a_0 + a_1x - a_2x^2 + a_3x^3$. Alice takes the first turn. Bob wins if, after finitely many moves, the cubic polynomial on the blackboard has all coefficients (upto $x^3$) non-zero and equal. For which of the starting polynomials can Alice ensure that Bob does not win in finite number of moves?
a) $x^3+4x^2+4x+1$
b) $x^3+6x^2+7x$
c) $x^3+3$
d) none of the above
It is an art of problem-solving question and I am not getting any clue. Please help how to solve these problems.
Comment: If $n$ is natural, how could he get the example you gave, with a negative coefficient $-a_2x^2$?
Comment: @LinconRibeiro:  that was one of the options for the players, to negate the quadratic term.
Comment: Are you sure you stated the problem correctly?  It seems so hard for Bob to win that I would expect there to be cases where he does to make it interesting.
Comment: Yes, https://artofproblemsolving.com/community/c6h1574839p11554312 this is the link.
Answer: Alice can keep from losing with any starting polynomial with nonnegative coefficients that includes a non-zero cubic term.  She can always use the $f(x)+n$ option leave a polynomial $ax^3+bx^2+cx+d$ with $d \gt a$ and the ratio $\frac da$ not a cube.  If Bob negates the squared term she just negates it back.  As long as all the coefficients are nonnegative, all the options except $f(nx)$ will keep the constant term larger than the coefficient of the $x^3$ term.  As long as the ratio is not a cube Bob can never make the coefficient of the $x^3$ term match the constant.
The only reason I specified non-negative coefficients was to make sure the $f(x+n)$ option cannot decrease the constant term.  I would be surprised if Alice cannot win all of those as well.
The same argument applies to quadratics and linear polynomials using the leading term, but you need to adapt the requirement for the ratio between the the constant term and the leading coefficient.
Comment: Alice just adds $2$ to get $x^3+4x^2+4x+3$.  Bob can't win this move because the only way to get the leading term higher is $f(xn)$ which multiplies the $1$ by a cube.  He cannot produce $3$ this way, so cannot win this time.  If Bob moves to $f(2n), 8x^3+16x^2+8x+3$ Alice can just add $6$, say.  As long as $d \gt a$ the only polynomials that Bob can win from are ones of the form $ax^3+anx^2+an^2x+an^3$.  Alice just has to avoid these.
Comment: Hi,
Will you please explain with one of the example say for the polynomial a)?


PostgreSQL full-text search from one column or two columns (A, AB but not B)?

Question: I have a table of names with one column being given names and one column being surname.  Say I have the name "Mary Smith".  I want that row return when I search for "Smith" or "Mary Smith" but not for "Mary".  How can I achieve this for a full-text index?
Comment: So, if there are two names, search for either, but if only one, only search for surname. Because your title and explanation do not correspond logically.
Answer: I think this is what you need:
WHERE surname = 'yoursearch' OR (name || ' ' || surname) = 'yoursearch'

Both
WHERE surname = 'Smith' OR (name || ' ' || surname) = 'Smith'

WHERE surname = 'Mary Smith' OR (name || ' ' || surname) = 'Mary Smith'

returns Mary Smith but
WHERE surname = 'Mary' OR (name || ' ' || surname) = 'Mary'

does not
Comment: That's the correct logic, but I'd prefer to use full-text searching.
Comment: Do you really need full-text search? Full text search is for long text fields
Comment: I'd rather avoid ilike searches.
Comment: @BrunoCalza. Full-text search does not have to be for long text fields. It is actually done on tsvectors, which can be make up of one or many fields.
Comment: @JohnBarça you're right. it's just that i don't any benefit of using tsvectors on people's name. i don't know much about text search though


What is the best AWS infrastructure to run a migration of data from one SQL server to mongoDB?

Question: I have some terabytes of data in our legacy system which runs SQL server. Our newer version runs on MongoDB. We are migrating this data to MongoDB. We have python scripts written and verfied, all data movement happens properly.
we did this on a lower machine which 4 cores, if we do it on bigger machine, its going to be very expensive. AWS Lambda has 15 minutes processing time, this takes more than 24 hrs for one iteration to finish. AWS step functions promises it, but not sure if it is the right one.
Comment: Does this answer your question? [Can you help me with my capacity planning?](https://serverfault.com/questions/384686/can-you-help-me-with-my-capacity-planning)
Comment: Thanks for response, but  Im not looking for capacity planning, I have those details, I need what is the best infra (mostly from AWS cloud) to run my scripts uniterruptedly for few days, which would migrate data of SQL to mongo, so that they are finished on time.
Answer: Can you not do "mongoexport" locally, export to S3 (or a physical AWS Snowcone device), use an EC2 instance to "mongoimport", then run your script to do any updates since the dump?
As for how to run it, you would probably get away with using a spot EC2 instance, particularly if you use it outside peak hours for the region - perhaps a weekend. If your job can't be interrupted then on-demand EC2. An m5.xlarge with 4 cores / 16GB RAM is $0.20 per hour, a couple of days of that is $10.
I'll also point out that say 3TB at 100Mbps will take 2.6 days to send, but at 800Mbps will take 7 hours - but sustaining that bandwidth may be difficult without DirectConnect. You might be best off using an AWS Snowcone which is a physical device you copy data to then ship to AWS.
I would suggest using AWS Database Migration Service to migrate from MongoDB to AWS DocumentDB, which is their version of MongoDB with a different name. DMS will migrate the data, then you just point your application at the new instance and turn the old one off.
Comment: Yeah, I was thinking the Snow family, I'll edit to be more precise.
Comment: For "only" 3 TB a Snowball maybe overkill. Perhaps consider a Snowcone?
Comment: Im already using m5.xlarge, its not helping much. but thanks for snowcone and snow family, will take a look at it.
Comment: You're best placed to consider instance requirements since you have access to metrics - do you need more CPU, more RAM, more or faster storage, or something else? I do think a snow family device will be a good choice for this.
Comment: Yes, I need more CPU and RAM, highspeed, Im not doing offline datamigration, Im doing from one live DB server to another live DB server.
Comment: The cost of a larger instance for a day or two to migrate a huge database shouldn't be much. I would look at using AWS Database Migration Service to migrate to AWS DocumentDB which is basically MongoDB with a different label, instead of using custom scrips and your own EC2 instance. Answer updated.


Drupal 8 Commerce Module Hook_Theme()

Question: I'm working on a custom module that I want to hook into a custom commerce template.
Heres is the code inside of my custom module the returns the variable.
 /**
     * Implements hook_theme().
     * @param $existing
     * @param $type
     * @param $theme
     * @param $path
     * @return array
     */
    function my_theme($existing, $type, $theme, $path) {
        return [
              'commerce-product--full' => [
                'variables'=> array (
                    'key'=> "I'm a key.",
                ),
              ],
        ]
}

Inside of commerce-product--full, using kint(key), I get null as a response.
Am I missing something?
Comment: What function is that in?
Comment: I edited the question to show the function.
Comment: Sorry I don't know a hook named my_hook(). Can't help. Maybe someone else will know it.
Answer: Try implementing hook_theme_registry_alter() and see how that goes.
function mymodule_theme_registry_alter(&$theme_registry) {
    $theme_registry['commerce_product__full']['path'] = drupal_get_path('module', 'mymodule') . '/templates';
}

Your module presumably will have a folder named templates. And inside the folder you have a file called commerce-product--full.html.twig
Comment: @Jeremy you resolved it?
Comment: My answer is actually messed up. Just realizing that. For context purposes how are you using that template? Inside a block? Or is it rendered for a given path?
Comment: Thank you but that wasn't it. I think it's directly related to the Commerce plugin.
Comment: No. Still looking into Commerce docs and around the web for a solution.
Comment: It's a custom twig file that replaces the default commerce.html.twig.
Comment: I think what you are looking for is `hook_theme_registry_alter()`. Let me see if I can do a code sample for you.
Answer: So I did figure out the answer. It was a combination of turning dashes into underscores and using a preprocess function.
/**
     * Implements hook_theme().
     * @param $existing
     * @param $type
     * @param $theme
     * @param $path
     * @return array
     */
    function my_theme($existing, $type, $theme, $path) {
        return [
              'commerce_product__full' => [
                     'preprocess functions' => ['my_preprocess_function'],

              ],
        ]
}

function my_preprocess_function(&$variables) {
    $variables['slogan'] = "I'm a slogan!!";
}

Thanks for everyone's help.

Drupal 8 Commerce Module Hook_Theme()


Deletar elemento array JavaScript

Question: Estou fazendo uma calculadora(estou usando para estudar), e coloquei um botão que deveria apagar o ultimo número do array, porém quando eu clico ele me retorna um erro:

script.js:16 Uncaught TypeError: nums.pop is not a function
      at limpa (script.js:16)
      at HTMLButtonElement.onclick (index.html:12)

let tela = document.getElementById('visor');
let verifica;
let nums = [];
let oldnum = 0;
let operation;

function mostranum(num){
  tela.innerHTML += num;
  nums += num;
}

function limpa(){
  nums.pop();
  tela.innerHTML = nums;
}

function operator(ope){
  let regx = /^[0-9]{1,8}$/;

  if (regx.test(nums) == true) {
    oldnum = nums;
  } else {
    alert('digite ate 8 digitos ');
  }
}

    <button id='clear' onclick="limpa()">C</button>

    <button class="num" id="n7" value="7" onclick="mostranum(7)">7</button>
    <button class="num" id="n8" value="8" onclick="mostranum(8)">8</button>
    <button class="num" id="n9" value="9" onclick="mostranum(9)">9</button>
    <button class="ops" id="sum" onclick="operator('sum')">+</button>

    <button class="num" id="n4" value="4" onclick="mostranum(4)">4</button>
    <button class="num" id="n5" value="5" onclick="mostranum(5)">5</button>
    <button class="num" id="n6" value="6" onclick="mostranum(6)">6</button>
    <button class="ops" id="subtract" value="-" onclick="operator('subtract')">-</button>

    <button class="num" id="n1" value="1" onclick="mostranum(1)">1</button>
    <button class="num" id="n2" value="2" onclick="mostranum(2)">2</button>
    <button class="num" id="n3" value="3" onclick="mostranum(3)">3</button>
    <button class="ops" id="multiplication" value="*" onclick="operator('multiplication')">*</button>

    <button class="num" id="0" value="0" onclick="mostranum(0)">0</button>
    <button class="ops" id="float" value=".">.</button>
    <button class="result" id="result" onclick="operator('result')" >=</button>
    <button class="ops" id="division" value="/" onclick="operator('division')">/</button>

Answer: Inicialmente, nums foi declarado como array:

let nums = [];

No entanto, na função mostranum, você está tentando utilizar o operador += em um array. Nesse caso, o array será convertido para uma string, veja:

let arr = [];
arr += 5;

console.log(typeof arr, arr); // string 5

Desse modo, você está recebendo o erro já que uma string não tem o método pop em seu protótipo. Em suma, é errado utilizar o operador += para inserir um novo item ao fim do array.
Nesses casos, utilize o método push:

let tela = document.getElementById('visor');
let verifica;
let nums = [];
let oldnum = 0;
let operation;

function mostranum(num) {
  tela.innerHTML = parseFloat(tela.innerHTML || 0) + num;
  nums.push(num);
}

function limpa(){
  nums.pop();
  tela.innerHTML = nums;
}

function operator(ope){
  let regx = /^[0-9]{1,8}$/;

  if (regx.test(nums) == true) {
    oldnum = nums;
  } else {
    alert('digite ate 8 digitos ');
  }
}

    <button id='clear' onclick="limpa()">C</button>

    <button class="num" id="n7" value="7" onclick="mostranum(7)">7</button>
    <button class="num" id="n8" value="8" onclick="mostranum(8)">8</button>
    <button class="num" id="n9" value="9" onclick="mostranum(9)">9</button>
    <button class="ops" id="sum" onclick="operator('sum')">+</button>

    <button class="num" id="n4" value="4" onclick="mostranum(4)">4</button>
    <button class="num" id="n5" value="5" onclick="mostranum(5)">5</button>
    <button class="num" id="n6" value="6" onclick="mostranum(6)">6</button>
    <button class="ops" id="subtract" value="-" onclick="operator('subtract')">-</button>

    <button class="num" id="n1" value="1" onclick="mostranum(1)">1</button>
    <button class="num" id="n2" value="2" onclick="mostranum(2)">2</button>
    <button class="num" id="n3" value="3" onclick="mostranum(3)">3</button>
    <button class="ops" id="multiplication" value="*" onclick="operator('multiplication')">*</button>

    <button class="num" id="0" value="0" onclick="mostranum(0)">0</button>
    <button class="ops" id="float" value=".">.</button>
    <button class="result" id="result" onclick="operator('result')" >=</button>
    <button class="ops" id="division" value="/" onclick="operator('division')">/</button>

Comment: Obrigada, tem alguma maneira de não aparecer essa virgula quando estou deletando os numeros?

Deletar elemento array JavaScript


NSDateFormatter - "Yesterday, 3:30 PM"

Question: I want to get a particular format for my date in my iOS app.
Basically, it's a text message history list. I want to display the date with the following format if the text was received less than a week ago:
"Today, 3:30 PM"
"Yesterday, 3:28 AM"
"Monday, 1:12 PM"
etc.
How can I use NSDateFormatter to get that output? I've tried few combinations without success, the main problem reside in the first part; Today/yesterday, etc.
Thanks a lot!
EDIT: Here's my code at this moment. (The day part isn't working, I have trouble getting the "dateFromTemplate" & "timeStyle" to work at the same time.)
NSString *dateComponents = @"eee";
formatter=[[NSDateFormatter alloc] init];
formatter.timeStyle=NSDateFormatterShortStyle;
[formatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:[NSLocale autoupdatingCurrentLocale]]];
formatter.doesRelativeDateFormatting=YES;
formatter.locale=[NSLocale autoupdatingCurrentLocale];

Comment: its the best you can find over internet , check this link for [FormatterKit](https://github.com/mattt/FormatterKit)
Comment: NSDateFormatter alone won't do it.  But, unless you're all tied up in matching the locale or some such, it's a fairly simple matter to just write some code to do it.  Probably NSCalendar components:fromDate:toDate: is what you want.
Answer: It is easy to implement one yourself, if you take a look at NSDateComponents. However, there are some nifty libraries to do this. See this one, it looke good https://github.com/kevinlawler/NSDate-TimeAgo. This is the code I wrote for an application, you could extend it to your need. This is a category on NSDate.
@implementation NSDate(DateAgo)

+ (NSDate*)dateEarlierToDate:(NSDate*)date byDays:(int)days{
  NSCalendar *calendar = [NSCalendar currentCalendar];
  NSDateComponents *components = [[NSDateComponents alloc] init];
  [components setDay:-days];
  return [calendar dateByAddingComponents:components toDate:date options:0];
}

-(NSString*)timeAgoFromReference{
    static NSDateFormatter *formatter;
    if(!formatter){
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterShortStyle];
    }
    NSDate *now = [NSDate date];
    NSTimeInterval timeIntervalFromNow = [now timeIntervalSinceDate:self];
    if(timeIntervalFromNow/(60*60*24) > 9){
        return [formatter stringFromDate:self];
    }else{
        return [self timeAgoFromInterval:timeIntervalFromNow];
    }

}
-(NSString*)timeAgoFromInterval:(NSTimeInterval)interval{
    if(interval < 1){
        return @"A second ago";
    }else if(interval < 5){
        return @"5 seconds ago";
    }else if(interval < 10){
        return @"10 seconds ago";
    }else if(interval < 15){
        return @"15 seconds ago";
    }else if(interval < 30){
           return  @"30 seconds ago";
    }else if(interval < 60){
        return @"1 minute ago";
    }else if(fabs(interval/60) < 60 ){
        return [NSString stringWithFormat:@"%d minutes ago",(int)(interval/60)];
    }else{
        int timeInHours = interval/(60*60);
        if(timeInHours == 1){
            return @"1 hour ago";
        }else if(timeInHours < 24){
            return [NSString stringWithFormat:@"%d hours ago",timeInHours];
        }else{
            int timeInDay = timeInHours/24;
            if(timeInDay == 1){
                return @"1 day ago";
            }else{
                return [NSString stringWithFormat:@"%d days ago", timeInDay];
            }
        }
    }
    return @"0";
}
@end

If you have some date you could call it like this,
NSString *dateAgo = [date timeAgoFromReference];

This is however simple and easy to understand, you could add more features to this yourself easily
Comment: Yeah, I would like to implement it myself. See my edit for my current code.
Answer:
Create a date component and assign a day value to -1 and you can find yesterday's date by adding date component to current date-
NSDateComponents *NsD = [[NSDateComponents alloc] init];
NsD.day = -1;
NSDate *yesterday = [[NSCalendar currentCalendar] dateByAddingComponents:NsD toDate:dateNow  options:0];

You can get time by using date formatter
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSString *dateStr = [formatter stringFromDate:[NSDate date]];

Comment: You misunderstood the question

NSDateFormatter - "Yesterday, 3:30 PM"


How to connect to CentOS after killing permissions?

Question: So I will try to keep this short and simple.
For our dev server at work, I was trying to add a new user last friday and I think instead of changing his file permissions I ended up changing group file permissions. The owner is of /var is now "write" instead of "root" and as a result (since no one is in write group "write" now), none of us can log in. I can't even ftp or ssh into the server. Unfortunately, this server is virtualised on hardware in our server room. The server room is pretty close but I would need to get access permissions to actually go in to it. We only have a small server space.
Is there anyway to get around this? When I try to ssh in I get the error "server unexpectedly closed network connection", so do all my co-workers.
Comment: Is this server in the cloud, or on a virtualisation box in your server room?  Your question is unclear about this.
Comment: Its virtualized from our "server room".

Edit: By "server-room" I mean the sever room has like 500+ servers, big-ips etc. I would have to find someone who knew there way around better than I do because I am new here. I don't wanna break more than I have to to fix it.
Comment: Most virtualisation technologies have a method of accessing the virtual console; KVM (for example) offers this via a VNC server for each virtual host.  Have you tried logging in that way, preferably as root?
Comment: @MadHatter that is a very good idea. I didn't think of that. I was mostly wondering if there is a way to reset permissions without ssh or ftp.
Comment: I'm not sure if this helps, but after reading logs from last friday it looks like it might be because the permissions of /etc/ssh got changed.
Comment: You can easily access the virtual console remotely but you will still have to take down the system and reboot it into a live environment (e.g. Linux live CD) to repair this. This of course can also be done remotely.
Answer: The comments have mentioned connection to the virtual console. If that does not allow a login, you can fix the permissions by booting a Linux LiveCD, such as knoppix
Once in the LiveCD environment you can mount the disk from the virtual machine and reset the permissions. Bear in mind that the user id of root is 0, by standard, so there will be no userid mapping problem.
However, if you need to change the ownership of a file to another user you should view the user and group id's from the files on the virtual disk to get the uid and gid. That will allow you to set the ownership using the uid or gid.
For example, to change the ownership of /mnt/var/test.txt to the user "fred" who has the uid 500.
<code>chown 500 /mnt/var/test.txt
</code>


How to appropriately run an adonis or anosim test?

Question: I have microbiome data structured as follows:

PatientID
Treatment
Response

P1
Pre.
Yes.

P1.
Post.
Yes.

P2.
Pre.
No.

P2.
Post.
No.

where I want to look at differences in the microbiome between patients who did and didn't respond to drug treatment. I have approximately 40 patients.
I have used phyloseq to generate a bray curtis distance matrix:
bray_dist = phyloseq::distance(physeq, method="bray")

I now want to use that distance matrix to test for differences between patients who did and didn't respond. What is the correct way to do this with anosim or adonis?
I was thinking of this:
adonis(bray_dist ~ sample_data(physeq)$Response, distance = "bray", strata = sample_data(physeq)$Treatment)

But I am new to this and I am unsure if this is the correct way to do it: would the above test the pre and post samples individually?
Answer: As i have understood, adonis test (permanova) only tells you if there is significance among your treatments, but unfortunately does not tell you between which of them are different, in order to do that, you need to use another package as "pairwiseAdonis".
pairwiseAdonis::pairwise.adonis(your_distance-matrix, factors = metadata$Treatment, perm = 999).
But, if the differences in variation among your treatments are very big, i recommend to try with ANOSIM; unfortunately i dont know about any package in R that could do pairwise test, in such case i use the PAST software.
https://past.en.lo4d.com/windows


Making sure user provides Y or N only

Question: my program is almost done. The only thing that I am having trouble with is at the end.
I ask the user if they would like to restart the program but with new inputs by inputting y, Y, N, or n ONLY and if they accidentally provide with another character then the program should tell them that it is invalid and to try providing a valid input.
  //Asking the user if they want to restart the program
            cout << "Do you want to start the program again and input new data? Y/N: ";
            cin >> option;

                //making sure that they actually input 'y', 'Y', 'n', or 'N'
                do {
                 cout << "That is an invalid input. Try again.\n";
                 cin >> option;
                 } while (((option != 'y') && (option != 'Y'))  ((option != 'n') && (option !='N')));
                system("CLS");
                cout << "Ok thank you for using my program. BYE!" << endl;
        } while (option == 'y' || option == 'Y');

Since I am still a beginner with C++ the only things that I have tried is switching the order of the conditions inside the while loop, but aside from that, I would not know.
Below is the whole code with comments in it.
#include <iostream>
#include <stdlib.h>
#include <limits>
using namespace std;

int main()
{
    //This char is for the do...while loop
    char option;
    do {
        //variable names
        bool validInputStudent = false;
        bool validInputDay = false;
        int numStudents;
        float numHoursProg, numHoursBio, totalProg, totalBio, averageProg, averageBio;
        int student,day = 0;     // these are the counters for the loops
        int MAXDAY;
        cout << "This program will find the average number of hours a day"
             << " that a student spent programming over a set number of days? ";
        //This piece of code will make sure that the user inputs a numeric value
        do {
            cout << "\n\nHow many students are there? ";
            cin >> numStudents;
            //making sure that they input an actual number and not a letter bu accident
            if (!(validInputStudent = cin.good())){
                cout<< "That input is not valid! Try again!\n";
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(),'\n');
            }

        } while (!validInputStudent);

    //making sure that they enter a numeric value again
        do {
            cout << "\n\nHow many days did the student worked? ";
            cin >> MAXDAY;

            if (!(validInputDay = cin.good())){
                cout<< "That input is not valid! Try again!\n";
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(),'\n');
            }

        } while (!validInputDay);

        //This will add up the number of hours that they spent studying for each subject
            for(student = 1; student <= numStudents; student++)
            {
                totalProg = 0;
                totalBio = 0;
                for(day = 1; day <= MAXDAY; day++)
                {
                    bool validInputHProg = false;
                    bool validInputHBio = false;

                    //Making sure that the users input is a numeric value
                    do {
                        cout << "\n\nPlease enter the number of hours programming by student "
                             << student <<" on day " << day << ": ";
                        cin >> numHoursProg;

                         if (!(validInputHProg = cin.good())){
                        cout<< "That input is not valid! Try again!\n";
                        cin.clear();
                        cin.ignore(numeric_limits<streamsize>::max(),'\n');
                        }

                    } while (!validInputHProg);

                    //Making sure that the users input is a numeric value
                    do{
                        cout << "\n\nPlease enter the number of hours studying biology " << student << " on day "
                            << day << ": ";
                        cin >> numHoursBio;

                        if (!(validInputHBio = cin.good())){
                        cout<< "That input is not valid! Try again!\n";
                        cin.clear();
                        cin.ignore(numeric_limits<streamsize>::max(),'\n');
                        }

                    } while (!validInputHBio);

                    //Adding up all the hours per class
                    totalProg = totalProg + numHoursProg;
                    totalBio = totalBio + numHoursBio;
                }

                //Finding the average time spent studying per subject
                averageProg = totalProg / MAXDAY;
                averageBio = totalBio / MAXDAY;

                //This will find what subject the student spent studying the most
                if (averageBio > averageProg){
                    cout << "\n\nThe student spent more time studying Biology than programming" << endl;
                } else if (averageBio < averageProg){
                    cout << "\n\nThe student spent more time programming than studying Biology" << endl;
                } else if (averageBio = averageProg) {
                    cout << "\n\nThe student spent an even amount of time studying Biology and programming" << endl;
                }

            }

            //Asking the user if they want to restart the program
            cout << "Do you want to start the program again and input new data? Y/N: ";
            cin >> option;

                //making sure that they actually input 'y', 'Y', 'n', or 'N'
                do {
                 cout << "That is an invalid input. Try again.\n";
                 cin >> option;
                 } while (((option != 'y') && (option != 'Y'))  ((option != 'n') && (option !='N')));
                system("CLS");
                cout << "Ok thank you for using my program. BYE!" << endl;
        } while (option == 'y' || option == 'Y');
    return 0;
}

I just want the program not to accept any other characters or numbers that are not n, N, y, Y. If by any chance they do, the program should tell the user to try again. Currently no matter what I put it says that it is wrong. Even if I input the correct characters.
Comment: Please remove the `C#` tag.
Comment: Please provide [mcve] with emphasizes on **minimal**.
Comment: What is the issue?  Is it not compiling?  Not running correctly?
Answer: You are missing && between your valid options:
while (((option != 'y') && (option != 'Y'))  ((option != 'n') && (option !='N')));
//                                         &&

I'm surprised it compiles. It looks like you are using the first expression as a function where the second expression contains a bool argument to the function:
((option != 'y') && (option != 'Y'))  // the "function"
((option != 'n') && (option !='N'))   // the bool argument

So, add && between them.
You are also doing what looks like comparisons, but are assignments:
if(averageBio = averageProg)
Check those out. You should probably use == between them.
Comment: OMG dude thanks. Can't believe I missed that.
Comment: You ACTUALLY helped
Comment: @GuillermoMolinaMatus Glad it helped! :)

Making sure user provides Y or N only


Is there a way to simplify $\cos(\arcsin(x) - \arcsin(a*x))$?

Question: I worked out you can do $\cos(\arcsin(x)) = \sqrt{1-x^2}$ but can it be done if there is a difference between inverse sines?
Comment: Use the angle sum formula for cosine: $\cos (\alpha + \beta) = \cdots$.
Answer: On the one hand, you have the formula
$$
\cos(\alpha-\beta)=\cos \alpha \cos \beta+\sin \alpha\sin \beta\tag{1}
$$
On the other hand, for $\alpha=\arcsin(x)$ and $\beta=\arcsin(ax)$ you have
$$
\sin\alpha = x,\quad \sin\beta = ax.\tag{2}
$$
Also, note that
$$
\cos\theta = \sqrt{1-\sin^2\theta}\tag{3}
$$
for $\theta\in[-\pi/2,\pi/2]$.
Now combine (1) (2) and (3) to get your answer.
Answer: $$\begin{align*} \cos(\arcsin(x) - \arcsin(ax)) &=  \sin(\arcsin(x))\sin(\arcsin(ax)) + \cos(\arcsin(x))\cos(\arcsin(ax)) \\ &= ax^2 + \sqrt{(1-x^2)(1-a^2x^2)}\end{align*}$$


Mimic special midi reverb event that gets quieter the higher it is set to

Question: I am looking for a way to play midis with a special reverb in a midi player or similar.
This reverb, which was used in a Nintendo 64 game, uses a special reverb technique that seems to be a combination of hall and reverb and conflicts with each other, resulting in a lower volume the higher the reverb event is set.
Here is an example. First note has no reverb event, second has one with a value of 70, then 90, 100 and 127. It gets steadily quieter even though the actual volume of the channels and notes are completely the same in the midi:
https://cdn.discordapp.com/attachments/502388312850300928/1092056255528435742/Reverb.mp3
The thing is, it doesn't have to be mimicked completely exactly, I'm just concerned about the volume being mimicked that way.
Answer: The reverb doesn't change. That's just the wet/dry balance changing. First is entirely dry [100% signal, 0% reverb], last is entirely wet [0% signal, 100% reverb].
The reverb itself I'd call a relatively un-spectacular room emulation, available anywhere. You might have to bit-filter it to get it as grainy as the original.
There is no dedicated controller message for wet/dry, though there are many controllers that could be used, all just labelled 'generic'. A manufacturer may be using any of thse, or even NRPNs. [non-registered parameter numbers]. You could possibly identify it if you have the actual midi file.
Here's an easy-to read list of controllers - Another Producer
Full [mind-numbing] detail is available from https://www.midi.org/
Comment: That will generate 'flutter' not grain. The graininess comes from the low bit-rate of the effect. I didn't address the awful 'clanginess'… but I'm sure you could find some point on even a decent reverb that would emulate your grandma's dining room ;)
Comment: I'd suggest using a fast delay in addition to a short reverb to get the graininess.
Comment: Yeah, I was using the word "grain" in the same sense as granular synthesis.
Comment: Thanks for the info! But with which midi editor or player could you set this reverb, or mimic? With VLC Player, for example, I can configure a reverb with the Spatializer, but this is then fixed to all channels and uses only a single fixed reverb value, instead of that it is oriented to the reverb midi event.
I have also experimented with LMMS, mimicking the reverb, but the program seems to use a completely different volume level, causing the volume levels of the individual instruments to be quite different.
Comment: It look like you should be able to do it in LMMS, but I've never tried it, so I really don't know how it works beyond what the first page of their advertising says. You'll have to wade through the manual.
Comment: I was able to mimic the reverb well in LMMS, but the individual volumes of the instruments don't seem to be accurate in this program. Could this have something to do with the normalization base or the gain?

In this example flutes and drums are too quiet:
https://cdn.discordapp.com/attachments/1121426057690611793/1121426057925500938/LMMS.mp3
It should sound like this:
https://cdn.discordapp.com/attachments/1121426057690611793/1121426058344923257/INGAME.mp3
I also tried the synthesizer sforzano, but it doesn't make any difference.
In VLC Player, it plays it in the right volume levels.
Comment: Note that the songs in the examples I have removed the reverb completely to show how much the volumes differ even though no effect is used.
Comment: You have to mix it for the playback engine & sample set that's going to be used in the final version. There is no real correlation between sample sets. there's *supposed* to be, but in reality there isn't.


How can I solve source.on is not a function when using form data?

Question: My code like this :

const axios = require('axios').default
import FormData from 'form-data'
import fs from 'fs'

export default class MyController {
  public async handleMultipleFile({ request }: HttpContextContract) {
    if(request.files('files').length > 0){
      const formData = new FormData()

      for( let i = 0; i < request.files('files').length; i++ ) {
        let file = request.files('files')[i]
        formData.append('files[' + i + ']', file)
      }

      axios.post(`https://example-api.com/assets/files`, formData, {
          headers: {
              'Content-Type': 'multipart/form-data'
          },
        }
      ).then(res => console.log(res.data))
      .catch(err => console.error(err))
    }
  }
}

When I call the code from postman, I find this error "message": "source.on is not a function"
I add return to see the formData in the postman
I had install library form data and axios in my code and I had import it
I want to post multiple file to a external api
How can I solve this problem? Please help. Thanks
Comment: Your code snippet does not contain `source.on`. Where is that in your code? Please add it to your question.
Comment: @jasie I's not in the code. The error happens when call `formData.append`. This seems to happen only in adonis
Comment: ah sorry. did you check this? https://stackoverflow.com/questions/57788965/getting-error-uncaughtexception-source-on-is-not-a-function-when-using-reques
Comment: @jasie I have read that before. But I'm still can't solve my case
Comment: pity.. what about this one? https://stackoverflow.com/questions/69763553/using-multipart-form-data-in-nestjs
Comment: did you try to debug the for loop? (what is in files, what is in formData during and after the loop...)
Comment: @jasie If I `console.log(file)` and remove `formData.append`, it's show  the file. The error happens when call `formData.append`. Does this have to use the `createReadStream` method? Because adonis is a backend not a front end
Comment: try to append a png image instead of your files and see if that works (without the loop). you can copy paste the code for that from here: https://masteringjs.io/tutorials/axios/form-data or use whatever real image or real text file you have in your project assets.
Comment: `formData.append(name, blob, fileName)` - maybe the last param is missing: fileName? see https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Comment: another idea: omit the index, like here: `formData.append('userpic[]', myFileInput.files[1], 'chris2.jpg');`  - userpic[] instead of userpic[i] -> https://docs.w3cub.com/dom/formdata/append | With formData.getAll('name'); you can check the content of your formData, pls do that.
Comment: last suggestion: check the posts here: https://github.com/request/request/issues/2366
Comment: @jasie Yeah. But my problem is I don't use path. So I can not your reference. The image uploaded from the front end is not stored in my local folder, but sent directly to the external api. So it seems I have to convert the uploaded file to blob/binary first so that it can be submitted using form data
Comment: have you got any solution? If yes kindly post it.
Answer: Sometime the data of the file is an object with the property value where is the content of the file. You have to append the file like this:
formData.append('files[' + i + ']', file.value,'NameOfFile.pdf')


Is it possible for the power curve to be lower under some alternative parameter value than under the null parameter value?

Question: Let $p_{n\theta}$ be the power function for testing $H_0:\theta=\theta_0$ versus $H_0:\theta\neq\theta_0$ using test statistic $T_n$. Is it possible that $p_{n\theta}<p_{n\theta_0}$ for some $\theta\neq\theta_0$ and $n$?  If it's possible, can you give an example (both analytical example and simulations are ok).
My guess is that it's entirely possible, but I don't know how to construct an example.
Comment: Or even a non-awful test. For example, an exact test for a binomial parameter often has its size considerably below the stated significance level, and the power curve has a sawtooth appearance due to the discreteness of the data.
Comment: Hint: construct a really awful test.
Comment: @RussLenth You were right about there being non-awful examples though. My answer includes three examples that wouldn't usually be considered awful (though the sample size on one of them was very small; on the other hand, one of the examples had a vary large sample size, the first was in between).
Comment: Oops, I may be mistaken here. In the sawtooth i got phenomena, I was thinking of power vs. sample size rather than power vs. the parameter value.
Comment: Example: https://stats.stackexchange.com/questions/279162/unbiased-hypothesis-test-what-does-it-mean-actually/279199#279199
Comment: @whuber Thank you very much! That's the right way to go.
Comment: @RussLenth I see. Thank you very much!
Answer: Sure, it's possible. Tests that do this are called biased tests. Many tests in common use have some bias against some alternatives, generally at smaller sample sizes. This is notably the case where the alternatives are very broad.

A common example is a chi squared goodness of fit with unequal probabilities; it's biased for some alternatives; sometimes the bias is surprisingly large.
An example of such bias for usual chi-squared goodness of fit for the multinomial occurs when the null is $\pi = (0.1, 0.2, 0.7)$. If you use the chi-squared $5\%$ critical value the actual significance level is about $5.2\%$ for $n=50$. Against the alternative $\pi = (\frac{27}{300}, \frac{58}{300}, \frac{215}{300})$, when $n=50$ the power is about $4.5\%$ (rejection rates based on $10^6$ simulations).

Indeed omnibus distributional goodness of fit tests are typically biased against some alternatives. The Kolmogorov-Smirnov and Anderson-Darling tests provide additional examples (e.g. vs light tailed alternatives, most severely for the Anderson-Darling). An example of testing a uniform against symmetric beta alternatives is here, the plot is reproduced below:

Here's another example I did a couple of years ago where you can draw a power curve and see the bias. In this case it's comparing mortality from a standard life table with simulated observed deaths where there's a constant percentage shift up or down in actual mortality rate from the standard table ($q_{x}=(1+\theta)q_x^s$ for adult ages). Here the model is not multinomial but rather a vector of binomials (which can also be formed as a $2\times k$ chi-squared table, but with $k$ degrees of freedom, since the total of observed frequencies and expected frequencies are not required to match across ages).

The hypothesized mortality is from a standard national life table, and the sample size is very large (representing observed mortality across age for membership of a hypothetical largish pension fund). The lowest rejection rate - the lowest point on the power curve - occurs near $\theta=-0.1$ (mortality is $90\%$ of hypothesized mortality), where the power is below $3.5\%$, and this is in spite of the actual type I error rate being above the nominal $\alpha=0.05$ (the true significance level is around $6\%$).
This bias would be a problem for a pension fund since a substantial drop in mortality would adversely impact their financial position. This sort of test is pretty commonly used for such a purpose, so such poor performance in a situation the fund would definitely want to detect the change should be a concern - a test that is fairly commonly taught for detecting shifts in mortality is unable to detect just the sort of change they need to be able to identify. The specific alternative is somewhat artificial, since we don't expect mortality change to be at a constant percentage rate across the range of adult ages, but it serves the purpose of illustrating a problem with using a chi-squared test to detect potentially lower mortality more broadly.
On the other hand the test does fairly well at detecting increases in mortality, albeit the power is likely well below what a life insurer (rather than a pension fund) would like.
Comment: I'm not sure I follow your intent there, sorry. The usual chi-squared goodness of fit test is a test for a specified set of multinomial probabilities; usually the intended alternatives would be any other sets of multinomial probabilities. There are other situations, such as test of a vector of specified binomial probabilities which would also be chi-squared (in this case still a test of goodness of fit but not the usual one)  and which also have a bias problem.
Comment: @whuber I included a specific example for the chi-squared; I don't know if that helps clarify the claim.
Comment: One explanation for the chi-square phenomenon is that you're pulling a bait-and-switch: the *right* power curve to construct should consider the *intended* alternatives for the test; but by considering *all* possible alternatives, you are contemplating applying the test in an unintended way.  This is not a criticism!  Indeed, it points out one way to construct many practical examples of nonmonotonic power functions.
Comment: Several further examples added
Comment: @Glen_b Thank you very much! This is very helpful!


Limit of inverse system where morphisms are non-zero products

Question: I have a rather complicated inverse limit which I am trying to compute. I will try to distil the question to its barest form, but if more details are necessary I can supply them.
Let $R$ be an integral domain and equip $\mathbb N$ with the usual ordering. Consider an inverse system $(A_i, f_{ij})_{\mathbb N}$ in $\text{Mod}_R$ defined by
$$f_{i,i+1}: A_{i+1} \to A_i, \quad a \mapsto r_{i+1} a, \qquad r_i \neq 0,1.$$
I would like to determine $\varprojlim A_i$.
Things seem to be as nice as possible: we're in a bicomplete category so we know the limit should exist, the directed system is totally ordered, etc. However, in trying to construct an element of this limit, it seems like every component must consist of an infinite product of the $r_i$'s. Does this mean that the only element of this limit is zero, and hence that $\varprojlim A_i = 0$?
Edit: Very little may be assumed about the $r_i$. For example, we do not know if they are units, and even if they are, we do not know whether their inverses appear in any morphism.
Comment: What are the $A_i$? Copies of the same module?
Comment: Sorry, I thought I had answered this question before but I guess it didn't stick. I would prefer to take them as nested submodules of some fixed module. If you like, you can take them as being the same module.

Edit: Also if it helps, we know that $r_{i+1} \in (r_i)$.
Answer: The inverse limit is not zero. You have a functor $A: \mathbb{N}^{op} \to Mod_R$, and you want a module that satisfies the universal property. The module:
$$ \{ x \in \prod_{n \in \mathbb{N} } A_n | x_n = f_{n,m}(x_m) \ for \  all  \ n \leq m   \} $$
has the universal property of the inverse limit, so this is isomorphic to the inverse limit.
The elements are not infinite products, but infinite vectors indexed by the natural numbers.
Also, this construction does not depend of the index set neither the ring (you can take any ring not necessarily commutative, with unit).
Comment: And it is easy to check that if all the $f_n=0$, then the inverse limit is the zero module.
Comment: All you have done is regurgitate the definition of the inverse limit on algebraic objects. Did you check what the morphisms do? That is the problem.

Choose an element $(a_n)$ and let's see what conditions $a_1$ must satisfy. By definition, for any $n$ we have $f_{1n} = f_{12} \cdots f_{n-1,n}$, so that
$$a_1=f_{1n}(a_n) = \left(\prod_{i=1}^n r_i \right) a_n.$$
Without information on the $r_i$, we cannot assume the product reduces, so $a_1$ is an $n$-fold product (of ring elements), *for each $n$*. Hence an infinite product.
Comment: Commutativity is a simplifying assumption so that we do not need to discuss left vs right vs two-sided modules. The construction does depend on both the ring and index set: If the module admits torsion, we're in a different situation since the stabilizing property could collapse to zero, and your construction above is not true if the limit is not filtered.
Comment: Finally, what use is the statement "And it is easy to check that if all the fn=0, then the inverse limit is the zero module?" This is irrelevant. There are plenty of examples of non-zero objects with non-zero morphisms which admit empty/zero limits. [Waterhouse 1972 - Proc. Amer. Math. Soc. 36 (1972), 618 ] is an excellent and simple example.
Comment: You're absolutely right. I didn't see the definition of the $f_n$'s. Sorry.


Is pitch tampering legal?

Question: I have seen a video where the goalkeeper have tampered the pitch so that the striker slips while attempting the penalty strike. (I don't recall the game, but it's from the German leagues).
The tampering is done when the team was arguing with the referee over the foul and when the referee was awarding the penalty.
The striker slipped, and missed the goal.
So, is this considered legal (the act of the goalkeeper)?
Comment: Video available here: https://www.facebook.com/video.php?v=1111643558854505
Comment: Just for future reference (videos online disappear), the game was between Augsburg and Cologne: http://www.theguardian.com/football/2015/dec/06/augsburg-goalkeeper-tampers-penalty-spot-miss-cologne
Comment: Legal or not, apparently [it costs you 122.92 euro for repairs](http://www.bbc.co.uk/sport/0/football/35040264).
Answer: This is unsporting behaviour and should be cautioned. Quoting from the 2015-2016 Laws of the Game:

If a player makes unauthorised marks on the field of play with his foot, he
  must be cautioned for unsporting behaviour.
Comment: That's probably better asked as a separate question as it's quite subtle. If the referee made an error of fact, for example if they saw the pitch tampering and did nothing about it, then the possible consequences are very wide; see eg [this incident](http://www.bbc.co.uk/sport/0/football/32231318). If the referee made an error of judgement, for example not seeing the tampering, then the result will stand.
Comment: @DavidRicherby agreed - although "unsporting behavior" is already the catch-all for the stuff they didn't want to write rules for :-)
Comment: @Konerak What does that change? It's still unsporting behaviour
Comment: Thank you for the answer.  Would the goal be accepted, if the footage comes to light some time later (maybe during the end of the game)?  Or would the player be fined instead?
Comment: I'd say it is arguable whether the pitch tampering by the goalkeeper was what was meant by this rule. I believe this rule prohibits _adding marks_ to the pitch, e.g. to help organize the defense, help a free-kick shooter with aiming, etc. (I'd say this was unsporting behavior, but punishable primarily by the respective association ex post.)
Comment: @Mormegil Rules such as this are usually written intentionally vaguely so that the rulemakers don't have to imagine in detail every possible way of cheating.
Comment: What if he does not make it with his foot?
Answer: The accepted answer is completely correct as to what action the referee should take against the goalkeeper.
Furthermore, if there is now a hole in the field which is large enough to make it difficult to take a penalty kick, in addition to cautioning the goalkeeper, the referee should suspend the game and not allow the penalty kick until ground staff or someone from the home team repairs the hole (depending on the level of competition). This is not only a fairness concern for the team taking the penalty kick, but also a safety concern for players from both teams.
The referee's power to suspend matches due to player infringements and for other interference is granted on p. 25 of the 2015/16 FIFA Laws of the Game:

The Referee:
...

stops, suspends or abandons the match, at his discretion, for any infringements of the Laws
stops, suspends or abandons the match because of outside
  interference of any kind

The power of the referee to make decisions with respect to the condition of the field of play is within the match official indemnity waiver (and strangely not within the law regarding the field of play) on p. 27:

A referee (or where applicable, an assistant referee or fourth official) is not held liable for:
any kind of injury suffered by a player, official or spectator
any damage to property of any kind
any other loss suffered by any individual, club, company, association or other body, which is due or which may be due to any decision that he may take under the terms of the Laws of the Game or in respect of the normal procedures required to hold, play and control a match.
Such decisions may include:

a decision that the condition of the field of play or its surrounds or that the weather conditions are such as to allow or not to allow a match to take place

...

Is pitch tampering legal?


Como obter a diferença entre datas e transformar em horas?

Question: No MYSQL, sei que posso retornar uma diferença entre datas através da função DATE_DIFF.
exemplo:
 SELECT * FROM table WHERE DATEDIFF(NOW(), created) <= ?

Porém, eu preciso que nesse DATEDIFF seja retornada a diferença em dia convertida para horas. Pois eu preciso comparar essa diferença para saber se um determinado prazo já venceu (e esse prazo é em horas, não em dias).
Como posso obter o valor em horas de um DATEDIFF no MYSQL?
Answer: Uma boa opção neste caso é usar TIMESTAMPDIFF(unidade, datetime1, datetime2), que já dá o resultado na medida desejada:
SELECT TIMESTAMPDIFF( HOUR, created, NOW() );

Você pode usar outras medidas no lugar de HOUR, dependendo da necessidade:

MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff
Answer: Use a função timediff() ele é parecida como datediff() porém retorna o tempo(hh:mm:ss) de duas datas. Para comparar apenas a hora, use função HOUR() dessa forma apenas a hora é retornada, como no terceiro exemplo.
Exemplo:
SELECT * FROM table WHERE TIMEDIFF(NOW(), created) <= ?

SELECT TIMEDIFF('2016-06-16 00:00:00', '2016-06-15 13:20:51') //10:39:09

SELECT HOUR(TIMEDIFF('2016-06-16 00:00:00', '2016-06-15 13:20:51')) //10


Notating the 3rd and 5th of an augmented chord

Question:
I am transposing a piano solo which is in A major. At a certain point (3rd beat of bar 7) the piano plays a dyad which consists of what I would normally call Eb and G natural (a major third apart). The harmony however implies that these are the 3rd and 5th of a B augmented triad. Diatonically, that would mean these notes are D# and F##.
I don't know whether it is clearer to notate it is D# and F## and be more "correct" or instead as Eb and G natural (or D# and G natural?) which I think is easier to grasp quickly, even though it's "wrong".
Which would be generally considered to be clearer?
Comment: Edited to include image of the relevant section. I contradict myself in the right hand by notating it as G natural rather than F, but it felt more "natural" (sorry).
Comment: the second accidental for the second C-natural in bar 8 seems unnecessary/inconsistent
Comment: It doesn't matter, Potato Potato. It won't change the sound.  You notate it in a way that makes most sense to you, generally what is easiest to read the quickest. What makes more sense? B+ or Eb+. They are enharmonic, same chord so it won't matter musically one bit. Although in context which one would be the most natural to understand musically? Eb in the key of A or B in the key of A? Beethoven would probably notate it as Eb+ while Schumann would use B+. No one is going to slap you on the knuckles if you use either one.
Comment: Bear in mind that like the 4 versions of the same diminished chord, augmenteds have 3. Add to that enharmonics, and there's lots of choice.
Answer: I would notate the entire two beats as an Eb augmented chord.

There is ample precedent for using enharmonically equivalent notation to improve readability, especially where double-accidentals are concerned.
The chord functions as a pivot. Initially, I agree, it's B augmented, inheriting its root from the preceding chord. But it also functions to lead downward to the D chord in the next measure, and then down again to the C augmented chord. By notating as Eb augmented, the downward movement is made more clear, especially the Eb - D - C root movement.
Comment: @yerman Yes, I would notate as Eb augmented (Eb - G - B) throughout.
Comment: Who is the notation and analysis for? If it's ultimately going to improvisers, choose the name that suggests to them what you want them to do with the chord. If it's going to sight-readers, choose the one that's easiest to play without thinking.
Comment: Thank you for your clear explanation of the pivot function. Cool how it can be two things at once (kind of). Would you change the right hand notation across those two beats to reflect the Eb augmented chord?


Django include template no data

Question: I am trying to include a file, into my base.html
Inside the base, inn the base.html
{% block content %}

{% include "something.html" %}
{% endblock %}

But nothing shows up from the included file, and I have tried to have blocks inn the something.html
{% block content %}
something something inside the something.html
{% endblock %}

I have also tried without using blocks, but nothing.
Comment: You forgot a closing double quote (`"`) in the `{% include "something.html" %}` tag.
Comment: Updated it, i just forgot it in the question, not in template
Comment: Does your "parent" template defined the `content` block?
Comment: all other templates that extends the base have block content yes
Comment: and you do not use `{% block ... %}`s, etc. in the `something.html`.
Comment: I use block content there also, but regardless there is no error, and no content from the included html
Answer: What you want to do is
base.html
{% block content %}

{% include "something.html" %}

{% endblock %}

something.html

my content in something

If you you put a block statement in the included template it will not show up.
More details https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#include
Comment: I tried with and without, still does not show up
Comment: Are they in the same directory? The include statement is relative to your TEMPLATE_ROOT
Answer: whatyouwanttoinclude.html

............
    {% block content %}
    {% endblock content %}
...........

whereyouwanttoinclude.html
{% extends 'whatyouwanttoinclude.html' %}
{% block content %}
    some html here
{% endblock content %}

Now when you render the template whereyouwanttoinclude.html, it will also show the contents of whatyouwanttoinclude.html

Django include template no data


sin graphing trig reflection issue precalculus

Question: $$-4\space \sin \space \left(-\frac{3\pi }{2}x+\frac{\pi }{5}\right)$$
When graphed out, the $x$-intercepts are $\displaystyle \frac{2}{5}$, $\displaystyle \frac{12}{15}$, and $\displaystyle \frac{22}{15}$ which I got. However, the graph is NOT reflected when I use a calculator
However, the function is clearly reflected (negative in front of the amplitude). Why is that?
Comment: try plotting without the $\frac{\pi}{5}$
Comment: how would that affect the reflection?
Comment: experiment with [ http://www.wolframalpha.com/input/?i=plot+%7B%E2%88%924+sin+%28%E2%88%923%CF%80%2F2+x%29%2C%E2%88%924+sin+%28%E2%88%923%CF%80%2F2+x%2B%CF%80%2F5%29%7D ]
Answer: Let's massage the equation a bit.
You have
$$y = -4 \sin \left(-\frac{3 \pi}{2}x + \frac{\pi}{5}\right).$$
Since the sine function is an odd function, $\sin(-x) = -\sin(x).$  So we can re-write your function as:
$$y = 4 \sin \left(\frac{3 \pi}{2}x - \frac{\pi}{5}\right).$$
Now, $\pi /5$ is only $36^{\circ}$, which isn't that much of a phase shift.  Maybe this is why it looks like it's not reflected (inverted).


Can I add external js and css via module info files?

Question: I have read that I can add js and css file via .info files. Can I add external css and js files there as well? Eg http://somewhere.com/in_a_galaxy
Answer: External JS/CSS files can't be specified in the info file at all. You need to add them via hooks, typically I use THEMENAME_preprocess_page() for things that need to be included on all pages, or you can use drupal_add_js() in your .module file.
And you can refer to this page. Here you can see how many ways you can add script/css files.
Comment: Actually it is possible in .info files ... of themes and of modules ! https://www.drupal.org/docs/7/creating-custom-modules/writing-module-info-files-drupal-7x#stylesheets
Comment: @rémy No, it is not possible for **external** js/css files. Take a look: https://www.drupal.org/docs/7/theming/working-with-css/adding-style-sheets-from-info-files (very end "Adding external stylesheets"). The right way is to use the `drupal_add_css()` and `drupal_add_js()` functions.
Comment: ups - i guess i was in D8 mode ...
Comment: @MichaLeuth: it is possible also in Drupal 7 to import an external CSS (I did it several times) stylesheets[all][] = file.css into the info file.
Spceified here in D7
https://www.drupal.org/docs/7/creating-custom-modules/writing-module-info-files-drupal-7x#stylesheets
Answer: To add external javascript.
drupal_add_js('http://example.com/example.js', 'external');

To add external css.
drupal_add_css('https://fonts.googleapis.com/css?family=Droid+Serif:regular', 'external');


Can Pathauto fallback to another pattern if the first pattern yields an empty path?

Question: I want pages to have an auto generated path if they are in a menu and another one if they are not in the menu; not an empty path like Pathauto currently generates if the page is not in a menu.
How can I do that?
Details: I'm using this pattern for my pages content type which works perfectly when a page is in a menu.
<code>[node:menu-link:parents:join-path]/[node:menu-link]
</code>
The problem is, when a page is not in a menu, it gets an empty path. I want to give it another path based on the "title" of the page, for example.
Answer: You can now achieve this using hook_pathauto_pattern_alter().  Something like:
<code><?php
/**
 * Implements hook_pathauto_pattern_alter().
 */
function mymodule_pathauto_pattern_alter(&$pattern, array $context) {
  // Alter any node entity path patterns we need to
  if (isset($context['data']['node'])) {
    $node = $context['data']['node'];

    switch ($node->type) {
      case 'page':
        // Check condition, and change the pattern when appropriate
        $pattern = '[node:title]';
        break;

    }
  }
?>
</code>
Comment: Thanks for the code. However, this changes the pattern depending on node type no matter what. I needed a way to change the pattern and regenerate the path only when the original pattern fails to generate a proper path.
Answer: Sadly, conditional tokens was requested many times and never implemented, so fallback you ask for is not possible.
You can use Rules instead. Description on Drupal.org claims it's easy - instead of pathauto, set up a rule on node creation / update, and create aliases needed. Rules support conditions, as you can see in Rules examples project, so you can create aliases conditionally all right.
Comment: Sad to hear that. If I find a better answer I'll update here for future reference. Thanks.
Answer: I took what m4olivei wrote and made it work for falling back to node title if no menu item is generated:
<code>/**
 * Implements hook_pathauto_pattern_alter().
 */
function mymodule_pathauto_pattern_alter(&$pattern, array $context) {
  // Set up pathauto fallback to node title if no menu item is generated
  if (isset($context['data']) && isset($context['data']['node'])) {
    if (isset($context['data']['node']->menu) && isset($context['data']['node']->menu['enabled'])) {
      if (!$context['data']['node']->menu['enabled']) {
        $pattern = '[node:title]';
      }
    }
  }
}
</code>