save the cropped bounding box

Question: I want to crop and save images from all the dataset which contains multi classes. but there is no output. and thank you.
def detect_face(img):
    detector = MTCNN()
    faces = detector.detect_faces(image)
return faces

dataset = '/content/drive/MyDrive/data_LFW/'

for img in glob.glob(dataset+'/*.*'):
    var_img = cv2.imread(img)
    face = detect_face(var_img)

    if (len(face) == 0):
       continue

    for(ex, ey, ew, eh) in face:
        crop_image = var_img[ey:ey+eh, ex:ex+ew]

   cv2.imwrite(os.path.join("/content/drive/MyDrive/data_crop",str(img)) ,crop_image)

Comment: maybe there is no input images therefore no output, or the detect_faces did not detect any face in input images. To check the hypothesis, just add a counter in the loop after continue to see how many faces detection are success. By the way, I spot an indentation error at "continue", shouldn't align with if statement, right?
Comment: my dataset contains two folders ,and each folder have other folders. It's still not working.
Comment: I see, then you might need to change the glob.glob statement to recursively traverse the two folders under  your dataset, see my answer below.
Answer: Assuming everything else are correct (since I don't have your dataset and detector code), you may want to try to correct couple indentations to see if you can get some different results:
if (len(face) == 0):
    continue #correct the indentation and try again

and if you want to save every detection, correct the cv2.imwrite indentation as well. Since you have two sub folders under the dataset, then you need to change glob statement as shown below to visit all sub folders:
for img in glob.glob(dataset+'**/*.*'):
    var_img = cv2.imread(img)
    face = detect_face(var_img)

    if (len(face) == 0):
        continue

    for(ex, ey, ew, eh) in face:
        crop_image = var_img[ey:ey+eh, ex:ex+ew]

    cv2.imwrite(os.path.join("/content/drive/MyDrive/data_crop",str(img)),crop_image)

save the cropped bounding box


Why CLARA clustering method does not give the same classes as when I do clustering manually?

Question: I am using CLARA (in 'cluster' package). This method is supposed to assign each observation to the closest 'medoid'. But when I calculate the distance of medoids and observations manually and assign them manually, the results are slightly different (1-2 percent of occurrence probability). Does anyone know how clara calculates dissimilarities and why I get different clustering results?
This is the function I use to do clustering manually:
Manual.Clustering <- function(Data,Clusters,Weights=NULL) {

if (is.null(Weights))   Weights <- rep(1,length(Data));
if (length(Weights)==1) Weights <- rep(Weights,length(Data));

Data2 <- Data[,rownames(Clusters)];
Data2 <- Weights*Data2;
dist  <- matrix(NA,nrow=nrow(Data),ncol=ncol(Clusters));

for (i in 1:ncol(Clusters)) {
    dist[,i] <- Dist2Center(Data2,Clusters[,i],Weights=NULL);
}

classes <- apply(dist,1,which.min);
Out <- cbind(Data,classes);
colnames(Out) <- c(colnames(Data),"Class");
Freq <- FreqTable(Out[,"Class"]);
Freq <- as.data.frame(Freq);

return(list(Data=Out,Freq=Freq));
}

=====================================
Dist2Center <- function(Data,Center,Weights=NULL) {

if (is.null(Weights))   Weights <- matrix(rep(1,nrow(Data)),ncol=1);
if (length(Weights)==1) Weights <- rep(Weights,nrow(Data));

if (ncol(Data)!=length(Center)) stop();

Dist <- Weights*apply(Data,1,function(x){sqrt(sum((x-Center)^2,na.rm=T))} );
return(Dist);
}

Data: Original Data.
Clusters: t(Medoids).
Medoids: 'medoids' picked by clara.
Dist2Center: A function which calculates Euclidean distance of each observation from each Medoids.
Behnam.
Comment: Have a look at the source code of Clara?
Comment: No. But I found the problem. I have that problem only when clara standardized the inputs. I did the same, but the difference is that (apparently) clara does the standardization one each sub set separately, while I was doing it on the whole data set together. When I don't do the standardization, no difference exists. B.
Comment: Having a look at the Clara C code, I found that Clara manipulates the distances if there is any missing values. The line " dsum *= (nobs / pp) " in the code shows that it counts the number of non-missing values in each pair of observations (nobs), divides it by the number of variables (pp) and multiplies this by the sum of squares. That is why it does not give the same results as my algorithm.
Answer: I found that this happens only when input data has NA values. For inputs without NAs, the results of my algorithm and clara are identical. I think this is related to how clara handles NA values while calculating the distances of observations to medoids. Any comment? Any suggestion for replacing clara with a better algorithm compatible with large datasets and NA values?
Answer: Having a look at the Clara C code, I found that Clara manipulates the distances if there is any missing values. The line " dsum *= (nobs / pp) " in the code shows that it counts the number of non-missing values in each pair of observations (nobs), divides it by the number of variables (pp) and multiplies this by the sum of squares. That is why it does not give the same results as my algorithm.


Why non-existence of Harder-Narasimhan filtrations for flat families of sheaves?

Question: Consider over $\mathbb{C}$. Let $X$ be a projective scheme and let $\mathcal{O}(1)$ be an ample line bundle on $X$. Consider Gieseker (semi)stability. For a coherent pure sheaf $\mathcal{F}$ on $X$, there is a unique filtration, called the Harder-Narasimhan filtration
$$0=\mathcal{F}_{\leq 0}\subsetneq\cdots\subsetneq\mathcal{F}_{\leq l}=\mathcal{F}$$
such that $\mathcal{F}_i:=\mathcal{F}_{\leq i}/\mathcal{F}_{\leq i-1}$ is semistable and $p(\mathcal{F}_1)>\cdots>p(\mathcal{F}_l)$ where $p(\mathcal{F})$ denotes the reduced Hilbert polynomial and $>$ is the total order on $\mathbb{Q}[t]$.
For a Noetherian local $\mathbb{C}$-algebra $A$, we can define a flat $S:=\mathrm{Spec}(A)$-family of semistble $\mathcal{O}_X$-modules, as a coherent $\mathcal{O}_{X\times S}$-module $\mathcal{F}$ such that $\mathcal{F}$ is flat over $S$ and at geometric points $s\in S$, the fibre $\mathcal{F}|_{X\times\{s\}}$ is semistable. It seems that for a flat $S$-family of coherent pure $\mathcal{O}_X$-modules, there is not always a filtration $\{\mathcal{F}_{\leq i}\}$ such that it restricts to the Harder-Narasimhan filtration at geometric points.
My question is why there is no existence in general. Are there calculable examples showing this?
Answer: I'm not sure that I understand your question correctly, but if you want the filtration on $X \times S$ to be a Harder-Narasimhan filtration, I think any example where $\mathcal F$ is not semistable, but $\mathcal F_s = \mathcal F_{X \times \{s\}}$ is semistable, should do.
Suppose there is a Harder-Narasimhan filtration for $\mathcal F$ which restricts to a HN-filtration on $X \times \{s\}$. If $\mathcal F|_{s}$ is semistable, it has trivial Harder-Narasimhan filtration. So $\mathcal F_{\leq i}|_{X \times \{s\}} = 0$ for $i < \ell$. But the support of a coherent sheaf is closed, so that $F_{\leq i} = 0$ on all of $X \times S$ (The support is a closed subset $Y \subset  X \times S$ which maps to a closed subset $Z = \operatorname{pr}(Y) \subset S$ by projectivity of $X$. But $Z$ does not contain the closed point $s \in S$, so $Z = \emptyset$).
So the HN-filtration of $\mathcal F$ is trivial, but if $\mathcal F$ is not semistable, this is a contradiction.
Comment: There is no definition for semistability of an $S$-family other than the pointwise one. This is okay since semistability is an open condition. Therefore if $S$ is a local scheme, I think $\mathcal{F}$ is a semistable family iff $\mathcal{F}_s$ is semistable.


Integral operator and it's spectrum

Question: I am doing some functional analysis and am struggling with the following exercise:
Let $T$ be an integral operator defined as followed:
$$T(f)(s)=\int_0^1(s-t)^2f(t)dt$$
I am asked to it's spectrum. I did/think the following:
I think this operator is compact thus it suffices to find all the eigenvalues. I.e. all the $\lambda\in\mathbb R$ satisfying: $\lambda f=T(f)$. After I tried some functions for $f$, I noticed that $T$ sends any integrable function to a polynomial of at most degree 2. So the eigenvalues are polynomials of at most degree 2.
Note: this is just my intuition I have not yet been able to make it rigorous. My questions are:

Am I on the right track?
How can I make this rigorous for a random integrable function $f$ instead of examples?
How do I find the eigenvalues given the eigenvectors are polynomials of at most degree 2?

Thank u :)
Comment: If $f(t)=1$, $T(f)$ is a cubic polynomial in $s$...
Comment: What exactly is the domain of the operator?
Comment: The exercise did not state the domain I think $C[0, 1]$, but I also believe $L^2 [0, 1]$ also works.
Comment: Does this answer your question? [Spectrum of a self-adjoint integral operator](https://math.stackexchange.com/questions/4005598/spectrum-of-a-self-adjoint-integral-operator)
Answer: In fact, $T$ sends integrable functions to polynomials of at most degree 2. To see that this is the case, note that the integral can be expanded to
$$
Tf = \left(\int_0^1 f(t)\,dt\right)s^2
- 2\left(\int_0^1 tf(t)\,dt\right)s
+ \left(\int_0^1 t^2f(t)\,dt\right).
$$
Other than that, your argument is correct. To prove that this kind of operator is generally compact, you could use one of the arguments presented here. In this case, however, it suffices to note that the image of $T$ is finite-dimensional.
From there, we can determine the eigenvectors of $T$ as follows. Consider the restriction of $T$ to the space $\Bbb P_2$ of degree-2 polynomials. Relative to the basis $\mathcal B = (1,t,t^2)$, we find that the matrix of the restriction $T|_{\Bbb P_2}$ is given by
$$
[T]_{\mathcal B} =
\pmatrix{\frac 13 & \frac 14 & \frac 15\\
-1& -\frac 23 & -\frac 12 \\
1& \frac 12 & \frac 13}.
$$
The eigenvalues of this operator are the non-zero elements of the spectrum of $T$.
You should find that these are equal to $-1/6$ and $(5 \pm 3\sqrt{5})/60$.
Comment: @Main It does not. In general, restricting a map to an invariant subspace yields a subset of the spectrum. You might find it to be a helpful exercise to convince yourself that each eigenvector of this matrix corresponds to a degree-2 polynomial that works as an eigenfunction of $T$.
Comment: If we restrict our map does that not change the spectrum? Thanks for answering! :)

Integral operator and it’s spectrum


using inline-block to truncate text in span breaks UI

Question: I want to truncate the text and the alignment of the elements must be kept. And to truncate text in span, display: inline-block must be used. But using it breaks the UI.
JSFiddle Demo
Code Snippets
HTML

{{text}}

CSS
.inline {
  max-width: 137px !important;
  text-overflow: ellipsis;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
}

Expected Output is to have the truncated text be aligned with the surrounding  tags.
Comment: adding `vertical-align: top` to `.inline{}` seems to work.
Comment: Could you the answer post how you solved it instead of updating the title/question as not seeing the solution is not helpful to future users coming here for a solution for the same/similar issue. You are also able to accept your own answers that solved your issue too.
Comment: How exactly does the UI break? What's the desired UI result?
Comment: Not so clear what you are asking for. Could you show by a picture?
Comment: @Fran yeah. seems to 'kinda' work, since the borders are not aligned like in the 2nd output. But I think this is the closest one so far.

to others. updated fiddle and question
Answer: As @Fran suggested, adding vertical-align: top fixes the issue.
.inline {
  max-width: 137px !important;
  text-overflow: ellipsis;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  vertical-align: top;
}

Examples can be seen on this JSFiddle Demo. You may notice that even adding vertical-align: top doesn't really align the elements like in the 3rd example. But it is the closest answer for now.


AdSense in a Chrome Extension

Question: Google recently sent developers a mail, saying that they "are updating our ad policies to allow extensions to monetize through ads". At first I thought this would mean I'm now able to use AdSense in a Chrome Extension, because you know... Google, ads, ... They are kind of related.
However, after looking a bit closer at the matter today, I found the AdSense policy to be the same as before:

Currently, we don't permit Google ads or AdSense for search boxes to be distributed through software applications including, but not limited to toolbars, browser extensions, and desktop applications. In order to comply with AdSense program policies, please note that Google AdSense code may only be implemented on web-based pages.

So, does that mean Google's encouraging developers to monetize their Google Chrome Extensions through ad networks other than Google AdSense?
Comment: I'm voting to close this question as off-topic because it is about the policies of advertising companies.
Answer: Surprising, yes, but correct. From Google Chrome Web Store Program Policies:

Currently, AdSense may not be used to serve ads in Chrome extensions or packaged apps.
Comment: Uhm, wow, they're even mentioning it explicitly. Thanks!
Comment: Here it says its allowed? https://developers.google.com/chrome/web-store/faq#faq-app-05
Comment: ^ That's for web apps not extensions
Answer: AdSense in packaged apps is being worked on. See the discussion here: https://groups.google.com/a/chromium.org/forum/?hl=en&fromgroups#!topic/chromium-apps/_47r_YKRdjA
In the meantime, star this issue: https://code.google.com/p/chromium/issues/detail?id=132602

AdSense in a Chrome Extension


Django - Como apresentar último valor cadastrado no banco de dados em uma tela de cadastro

Question: Sou novo e ainda enfrento dificuldades que possam parecer bem simples pra vocês.
Resolvi por motivos pessoais fazer uma aplicação em Django.
Ela é um simples cadastro de pessoas num banco de dados MySQL usando django adminLTE, adminLTE_theme:
em models.py
from django.db import models

class Pessoas(models.Model):
    nome = models.CharField(max_length=150, verbose_name='nome completo')
    registro = models.IntegerField(verbose_name='número do registro')

    class Meta:
        managed = True
        db_table = 'pessoas'
        verbose_name = 'Filiado'
        verbose_name_plural = 'Filiados'

    def __str__(self):
        return self.nome

em admin.py
from django.contrib import admin
from .models import Pessoas

@admin.register(Pessoas)
class PessoasAdmin(admin.ModelAdmin):
    list_display = ('nome', 'registro')

No acesso da página de cadastro na área administrativa, gostaria de ter uma linha (row, ou qualquer coisa) que apresentasse o número do último registro cadastrado.
Já tentei fazer cópia do template change_form.html e direcionar pra esse html:
from django.contrib import admin
from .models import Pessoas

@admin.register(Pessoas)
class PessoasAdmin(admin.ModelAdmin):
    list_display = ('nome', 'registro')
    add_form_template = 'cad_filiado.html'

e no html:
{% block field_sets %}

                    Pessoa
                    Registro

                {% for p in pessoas %}

                        {{ p.pessoa }}
                        {{ p.registro }}

                {% endfor %}

{% endblock %}

até copiei o código do change_list_result.html no cad_filiado.html e dá erro de reverse_url...
tentei várias coisas, li e reli a documentação e não achei resposta. (Talvez a resposta até esteja lá, mas eu não entendi como executar)
Talvez você possa se perguntar: por que vc quer essa informação na página de cadastro?
R.: Pra manter uma usabilidade agradável, sem que precise procurar os registros.
agradeço a paciência.
Answer: Era um problema bem simples de resolver mas que não tinha nada a ver com o que estava lendo pra tentar resolver.
Basicamente: criei uma tag e usei na cópia do html do template de change_form.html que tinha feito.
Passo 1:
Criei um diretório dentro da pasta do app com o nome templatetags
Passo 2:
Criei um arquivo dentro do diretório novo chamado filiado_utilitario.py
Passo 3:
Fiz os importes, registros e uma busca no banco de dados:
from django import template

register = template.Library()

@register.simple_tag
def pesquisa_filiado():
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute(""" SELECT registro FROM pessoas ORDER BY id DESC limit 1;""")
        ult_pessoa = cursor.fetchone()
    return ult_pessoa[0]

Passo 4:
no cad_filiado.html acrescentei o importe do arquivo .py
{% load i18n admin_urls static admin_modify filiado_utilitario %}
Passo 5:
fui até o arquivo .virtualenvs/Meu_Projeto_Estudo/lib/python3.7/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html e copiei o trecho:
<fieldset class="module aligned {{ fieldset.classes }}">

</fieldset>

e inseri a tag logo depois do começo do formulário:
<form {% if has_file_field %} enctype="multipart/form-data" {% endif %}
      action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>
    {% csrf_token %}
    {% block form_top %}
<fieldset class="module aligned {{ fieldset.classes }}">

     Uĺtimo Filiado cadastrado número: {% pesquisa_filiado %}

</fieldset>

e fim.
Dá pra escovar um pouco mais e aceito sugestões


Get primary key column value after inserting record using DetailsView and EntityDataSource

Question: I'm using DetailsView with EntityDataSource and binding EntityDataSource directly with Entity Model.
I want to get the primary key value after record has been inserted. How can I get it either in
protected void detailsVewUser_ItemInserted(object sender, DetailsViewInsertedEventArgs e)

or
protected void EntityDataSource_Inserted(object sender, DetailsViewInsertedEventArgs e)

Comment: Have you looked at the [EntityDataSourceChangedEventArgs](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasourcechangedeventargs.aspx) properties?  It's an argument of the `_Inserted` method and might have what you're looking for.
Answer: DetailsViewInsertedEventArgs has a property called Values, but when you insert from DetailsView, you don't provide a primary key via textbox usually, so that newly assigned primary key won't be in there.
You could use EntityDataSource.Inserted event instead.  It passes EntityDataSourceChangedEventArgs which has an Entity property which you can type-cast and then get the value of the primary key attribute.  For example, if I had an entity called Dependent that I just inserted into my ObjectContext through the EntityDataSource, my event handler for the EntityDataSource could look like this:
protected override dependentInformationDataSource_OnInserted(object sender, EntityDataSourceChangedEventArgs e )
{
    // let's say my Dependent entity's primary key is called DependentKey
    int newPrimaryKey = ((Dependent)e.Entity).DependentKey;

    // do something with newPrimaryKey
}

Answer: You could pull the new ID directly from the database (I'm assuming SQL, but whichever database you're using) now that it has been inserted:
// an int to store your newly inserted ID
int newID = 0;
// a string containing a query that gets your latest, inserted record.
// Modify to your specific needs =)
string newIDQuery = "SELECT TOP 1 ID FROM tableName ORDER BY ID DESC;";
SqlCommand getNewIdCommand = New SqlCommand(newIDQuery, New SqlConnection("You Connection String"));
getNewIdCommand.Connection.Open(); // open the SQL connection
newID = getNewIdCommand.ExecuteScalar(); // this loads the int variable with the newest ID
getNewIdCommand.Connection.Close(); // close the SQL connection

Note: This example assumes your primary key column is an auto-increment-style integer field named ID.  Modify the above code to suit your needs, or let me know if you have questions!
Answer: Exact syntax depends on the database, but usual way is to do somnething like in sql server
Insert MyTable()...) Values(...)
Select Scope_Identity
So just execute the above through a reader, or an sp (you could return it as scalar then).
How and where you pass it back is up to you, but if you are passing in a viewmodel instance with the other data, populating it's id property is nice and clean.
If you have triggers and default constraints etc reloading the instance using the passed back identity is better.


A tag  substitui a ?

Question: Estou começando a usar HTML5 e ainda não sei bem como escolher entre as tags  e
.
Vejo pessoas usando depois do header o , enquanto outras já usam o
. Queria saber qual é a mais apropriada para fazer o conteúdo do meio da pagina.
Por exemplo:
 ...

 ou
 ???

 ...

Comment: Um bom lugar para consultar sobre cada tag com explicações de uso "ideal" é no MDN, exemplo: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section e https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main
Answer: Do ponto de vista semântico, não. As tags  e
 têm significados diferentes para o HTML5, que se baseia em ideias de estrutura semântica.

De acordo com a documentação,  representa o conteúdo dominante da página. Essa seção deve idealmente conter o tópico central do documento ou a funcionalidade central de uma aplicação. Deve ser único.

Já
 representa uma seção menos hierarquicamente importante. É, pela definição, uma "seção genérica do documento", que não tem outro elemento semântico que melhor a represente.

Portanto,
 não substitui . A já referida documentação do
 é enfática em dizer que esta tag deve ser utilizada apenas quando nenhum outro elemento melhor representar semanticamente o conteúdo.
Como  é um elemento que indica a semântica de conteúdo principal, deve ser preferido sobre
.

Quanto ao exemplo de código colocado na pergunta, não tenho como responder de maneira que cobre 100% dos casos, já que a escolha depende do conteúdo da página. De modo geral, se o conteúdo depois do  for o principal da página,  deve ser usado.
Caso contrário, talvez
 faça sentido, mas nesse caso idealmente outra seção da página deve ser a "dominante", isto é, .

A tag  substitui a ?


Evaluation of all positive integer ordered pairs $(n,r)$ for which $\binom{n}{r} = 2016$

Question:
$(1)$ Evaluation of all positive integer ordered pair $(n,r)$ for which $\displaystyle \binom{n}{r} = 120$
$(2)$ Evaluation of all positive integer ordered pair $(n,r)$ for which $\displaystyle \binom{n}{r} = 2016$

$\bf{My\; Try::}$ Here $r=1$ and $n=120\;,$ Then $\displaystyle \binom{120}{1} = 120$
So $\displaystyle (n,r) = (120,1)\;\;,(120,119)$ (Using $\displaystyle \binom{n}{r} = \binom{n}{n-r}$)
Here $\displaystyle \binom{9}{3} = 84$ and $\displaystyle \binom{9}{4} = 126.$
So using Triangular numbers, Here $\displaystyle \binom{n}{r} = 120$ is valid, when $n>9$
Now when $r=2$ and $n=16\;,$ Then $\displaystyle \binom{16}{2} = 120$
So $\displaystyle (n,r) = (16,2)\;\;,(16,14)$
Now we will find when $\displaystyle \binom{n}{r}$ is an Increasing function.
So $\displaystyle \frac{\binom{n}{r+1}}{\binom{n}{r}}\geq 1\Rightarrow \frac{n-r}{r+1}\geq 1\Rightarrow r\leq \frac{n-1}{2}$
So If $r\geq 3\;,$ and $n>9\;,$ Then $\displaystyle 120=\binom{n}{r}>\binom{n}{3} = \frac{n(n-1)(n-2)}{6}>\frac{(n-2)^3}{6}$
So $\displaystyle (n-2)^3<720<(9)^3\Rightarrow n<11$
So we have $n=10$ and $r=3\;,$ So we get $\displaystyle \binom{10}{3} = \binom{10}{7} = 120$
So we get $\displaystyle (n,r) = (10,3) = (10,7)$
So we get Total positive integer ordered pairs $$\displaystyle (m,n) =  \left\{(120,1)\;\;,(120,119)\;\;,(16,2)\;\;,(16,8)\;\;,(10,3)\;\;,(10,7)\right\}$$
But i did not understand How can I solve $(2)$ one.
Although we know that $\displaystyle \binom{2016}{1} = \binom{2016}{2015} = 2016$
Help me, Thanks
Comment: If $n > 2016$, there are no solutions to $\binom{n}{k}=2016$. This makes your search finite.
Comment: Here is a hint for 2016. As you noted, since $\binom{n}{r} = \binom{n}{n-r}$, it's enough for look for solutions with $0 \leq r \leq n/2$. Within this range, $\binom{n}{r}$ increases when $r$ increases. We have $\binom{24}{3} > 2016$, so the only possibilities with $r \geq 3$ will have $n \leq 23$. Also, for a fixed value of $r$, $\binom{n}{r}$ increases with $n$ ($n\geq r$), so there will be at most one value of $n$ that works for that $r$. Finally, since $7 | 2016$, you can narrow the possibilities by examining how many times $7$ appears in the numerator and denominator of $\binom{n}{r}$.
Comment: Thanks Marty, Thanks David , but i did not understand how can i found $\displaystyle \binom{64}{2} = \binom{64}{62} = 2016$
Comment: Is this a question from an on-going contest?
Comment: I have changed the formatting of the title so as to [make it take up less vertical space](//math.meta.stackexchange.com/a/9686/290189) -- this is a policy to ensure that the scarce space on the main page is distributed evenly over the questions. See [here](//math.meta.stackexchange.com/a/9730/290189) for more information. Please take this into consideration for future questions. Thanks in advance.
Answer: I wrote a simple program
to search all
$\binom{n}{k}$
for
$n < 2016$.
The only solutions were the ones you found.
For a more sophisticated search,
I could use the factorization
$2016=2^53^27$,
to limit the possible values
of $n$ and $k$,
but not now.
Answer: (2)
The fact that $\displaystyle\binom nr\leqslant \binom{n}{\lfloor\frac{n}{2}\rfloor}$ should be helpful.
If $n\leqslant 13$, there are no solutions because $\binom nr\leqslant\binom{13}{6}=1716\lt 2016$.
If $n=14$, there are no solutions because $\binom{14}{5}=2002\lt 2016\lt 3003=\binom{14}{6}$.
In the following, $n\geqslant 15$.

For $r=1$, we have $n=2016$.

For $r=2$, solving $\frac{n(n-1)}{2}=2016$ gives $n=64$.

For $r=3$, we have $n(n-1)(n-2)=2^63^37^1$. Since LHS has only one integer divisible by $3$, LHS has an integer divisible by $27$. So, we have to have $n\geqslant 27$, but then $\binom{n}{3}\geqslant\binom{27}{3}=\frac{27\cdot 26\cdot 25}{6}=9\cdot 13\cdot 25>8\cdot 12\cdot 25=2400\gt 2016$.

For $r=4$, we have $n(n-1)(n-2)(n-3)=2^83^37^1$. Since LHS has only one integer divisible by $4$, LHS has an integer divisible by $32$. So, we have to have $n\geqslant 32$, but then $\binom n4\geqslant\binom{32}{4}=\frac{32\cdot 31\cdot 30\cdot 29}{24}\gt \frac{32\cdot 31\cdot 30\cdot 29}{32}\gt 30\cdot 30\cdot 10=9000\gt 2016$.

For $5\leqslant r\leqslant\lfloor \frac n2\rfloor$, we have $\binom nr\geqslant\binom{15}{5}=3003\gt 2016$.

Therefore, the answer is
$$\color{red}{(n,r)=(2016,1),(2016,2015),(64,2),(64,62)}$$


Repeating application in the Droid menu

Question: Just wondering if anyone has seen this problem and knows what might be wrong. I've constructed something of a library it has on the main page where you select A, B, C ... etc. and then it opens a page with buttons for whichever your choice is. Now the problem is when I load my app onto my phone it has one app button for the whole app and then it has one button for each A, B, C... etc .classes as in i can click on any of those and it opens directly from the phones menu. Its like the menu has been spammed and i don't think people would appreciate that. Anyone have any idea what it might be. Ive made an application that has a library type thing in it before and this problem never occurred.
Answer: Remove the MAIN and LAUNCHER intents from those other activities.
http://developer.android.com/guide/topics/intents/intents-filters.html

Activities that can initiate
  applications have filters with
  "android.intent.action.MAIN" specified
  as the action. If they are to be
  represented in the application
  launcher, they also specify the
  "android.intent.category.LAUNCHER"
  category:

<code> <intent-filter . . . >
     <action android:name="code android.intent.action.MAIN" />
     <category android:name="code android.intent.category.LAUNCHER" />
 </intent-filter>
</code>
Also, work on your accept rate.

Repeating application in the Droid menu


Finding a neighborhhod basis of a specific topological space.

Question: Let $X$ any set.
Let $T_f$ the cofinite topology ($T_f:=\{U\subset X , X\setminus U\text{ is finite}\} \cup \{ \emptyset\}$)
I am looking for a neighborhood basis of the topological space $(X, T_f)$
(Definition of a neighborhood basis:  Let $(X, T)$ be a topological space and $B_x$ a family of neighborhoods of $x \in X$. $B_x$ is called a basis of neighborhood at $x \in X$ if for all neighborhood of x, $\exists B \in B_x$ s.t $B\in N$)
Now I found neighborhood basis for other topological spaces but I am having trouble with this specific one.
EDIT $B_x$ has to be different than $\{U\in\tau_f:x\in U\}$
Comment: Just let $\mathscr{B}_x=\{U\in\tau_f:x\in U\}$; there really isn't anything simpler.
Comment: I'm sorry I forgot to specify that $\mathscr{B}_x \neq \{U\in\tau_f:x\in U\}$
Answer: Assuming that $X$ is infinite, let $\mathscr{B}_x=\{U\in\tau:x\in U\text{ and }|X\setminus U|\ge 2\}$. If $X$ is finite, let $\mathscr{B}_x=\big\{\{x\}\big\}$.


Fatal error: Maximum execution time of 240 seconds exceeded in ...database.inc on line 2171

Question: I have a dilly of a pickle here.
Not everytime, but frequently when I load any page Drupal 7 gets all of the contents of the page but then is still loading/spinning. After enough time goes by I get this error below:
( ! ) FATAL ERROR: MAXIMUM EXECUTION TIME OF 240 SECONDS EXCEEDED IN C:\WAMP\WWW\PROJECTS\ELAW\INCLUDES\DATABASE\DATABASE.INC ON LINE 2171
CALL STACK
#   TIME    MEMORY  FUNCTION    LOCATION
1   0.0000  245840  {main}( )   ..\index.php:0
2   34.1600 26139624    menu_execute_active_handler( )  ..\index.php:21
3   36.9871 40078664    drupal_deliver_page( )  ..\menu.inc:532
4   36.9871 40080080    drupal_deliver_html_page( ) ..\common.inc:2557
5   37.8472 40875392    drupal_page_footer( )   ..\common.inc:2673
6   38.1012 41024656    system_run_automated_cron( )    ..\common.inc:2700
7   38.1012 41025016    drupal_cron_run( )  ..\system.module:3505
8   40.5573 41112424    module_invoke( )    ..\common.inc:5265
9   40.5573 41112760    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
10  40.5573 41112960    search_cron( )  ..\module.inc:866
11  40.5573 41114344    module_invoke( )    ..\search.module:363
12  40.5573 41114688    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
13  40.5573 41114888    node_update_index( )    ..\module.inc:866
14  96.6225 42552024    _node_index_node( ) ..\node.module:2767
15  96.9115 43064736    search_index( ) ..\node.module:2798
16  277.8849    43777736    MergeQuery->execute( )  ..\search.module:720
17  277.9279    43789880    InsertQuery_mysql->execute( )   ..\query.inc:1621
18  277.9279    43790816    DatabaseConnection->query( )    ..\query.inc:36
19  277.9289    43793448    DatabaseStatementBase->execute( )   ..\database.inc:683

( ! ) FATAL ERROR: MAXIMUM EXECUTION TIME OF 240 SECONDS EXCEEDED IN C:\WAMP\WWW\PROJECTS\ELAW\INCLUDES\DATABASE\DATABASE.INC ON LINE 2171
CALL STACK
#   TIME    MEMORY  FUNCTION    LOCATION
1   0.0000  245840  {main}( )   ..\index.php:0
2   34.1600 26139624    menu_execute_active_handler( )  ..\index.php:21
3   36.9871 40078664    drupal_deliver_page( )  ..\menu.inc:532
4   36.9871 40080080    drupal_deliver_html_page( ) ..\common.inc:2557
5   37.8472 40875392    drupal_page_footer( )   ..\common.inc:2673
6   38.1012 41024656    system_run_automated_cron( )    ..\common.inc:2700
7   38.1012 41025016    drupal_cron_run( )  ..\system.module:3505
8   40.5573 41112424    module_invoke( )    ..\common.inc:5265
9   40.5573 41112760    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
10  40.5573 41112960    search_cron( )  ..\module.inc:866
11  40.5573 41114344    module_invoke( )    ..\search.module:363
12  40.5573 41114688    call_user_func_array:{C:\wamp\www\projects\elaw\includes\module.inc:866} ( )    ..\module.inc:866
13  40.5573 41114888    node_update_index( )    ..\module.inc:866
14  96.6225 42552024    _node_index_node( ) ..\node.module:2767
15  96.9115 43064736    search_index( ) ..\node.module:2798
16  277.8849    43777736    MergeQuery->execute( )  ..\search.module:720
17  277.9279    43789880    InsertQuery_mysql->execute( )   ..\query.inc:1621
18  277.9279    43790816    DatabaseConnection->query( )    ..\query.inc:36
19  277.9289    43793448    DatabaseStatementBase->execute( )   ..\database.inc:683
20  278.2359    43791168    _drupal_shutdown_function( )    ..\bootstrap.inc:0
21  278.4429    43791160    call_user_func_array:{C:\wamp\www\projects\elaw\includes\bootstrap.inc:3454} ( )    ..\bootstrap.inc:3454
22  278.4429    43791536    search_update_totals( ) ..\bootstrap.inc:3454
23  518.0976    43993744    MergeQuery->execute( )  ..\search.module:383
24  518.0986    44004992    UpdateQuery->execute( ) ..\query.inc:1643
25  518.0996    44006664    DatabaseConnection->query( )    ..\query.inc:1177
26  518.0996    44008880    DatabaseStatementBase->execute( )

This was a fresh Drupal 7 install that I installed Migrate & Drupal To Drupal Data Migration on and migrated some content from a drupal 6 site, and a drupal 5 site. I started noticing the timeout bug when I installed migrate and migrated the data from drupal 6 (which was done before the drupal 5 content. I am done with migrating now and have even uninstalled/removed Migrate & D2D Data Migration modules.
I also can't run cron. When I try I get "Cron run failed", and in the reports section:
"Attempting to re-run cron while it is already running."
Also, when I go to the modules page there is an error listed on top:

I have enough memory and my php timeout is set high. Also I have other Drupal 7 sites running under the same wamp server and they do not have any problems.
Please help me.  Thanks!
Comment: Disable the search module for now. Re-enable it at a later date. Also checkout my DIY performance slides for other ideas on how to improve your sites performance https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id.p
Comment: I disabled the "core" search module and saved.  I was then able to run cron successfully and as far as i know the timeouts stopped.  I was curious if that one time disabling fixed the issue, so I reenabled "core" search and tried running cron again manually, but it timed out just like before (with same message).  I don't have to have "core" search, but I will need some sort of searching, and am hoping that the Search API module will work where the "core" search module did not.  I'm not going to accept "disable core search" as the answer to my ? yet, as someone else might have a better solution
Comment: I think it's odd that "core" search is the problem, as after my initial migration with the migrate module I updated from Drupal 7.26 to Drupal 7.33 which replaces the "core" search module.  Is it possible it is not really the "core" search module but a problem with the schema, and when I install Search API module I will get the same sort of timeout issue?
Comment: I installed/enabled Search API module (and have core search disabled), and I can run cron without it timing out. I have also not noticed any other timeouts for general page loads....I would still like to find a solution for why "core" search is causing these timeouts and what I can do about it (I would rather not have a crazy bug show up in the future because i didn't do anything about this on the get go)
Answer: Check for a broken schema with the Schema module.
From the Schema module project page:

Schema comparison: the module compares the live database structure
  with the schema structure declared by all enabled modules, reporting
  on any missing or incorrect tables.
Comment: Hello, I installed this module but it did not find any discrepancies in the schema. Thanks for the good idea though!
Comment: How many rows are in the search-related tables in the db?
Comment: search_node_links = 11 rows, search_total = 78574 rows, search_index = 614638 rows, and I started the drupal 7 as a fresh install and used migrate api module to get data from a D5 site and a D7 site.
Answer: To fix this problem I re-migrated all my content and the error just went away.
Answer: Your Drupal cron job takes longer to run than 240 s, but its code limits itself to 240 s via drupal_set_time_limit(240). This is done in various other places in Drupal core as well.
Since in your case it's a fresh Drupal install, these cron runtimes seem not justified. But they might be, for example rebuilding the content access permissions did regularly take longer than 240 s in one of my sites with a lot of content. When it succeeds once for your site, it would not be called again during cron runs.
So as a solution, let's assume for now that these cron runtimes are jstified, and disable PHP's maximum execution time for them:

Configure Drupal to disable its "automated cron" feature (see here, section 'Disabling "automated cron"').
Set up the Drupal cron tasks to be triggered via the system's crontab and drush instead, following these instructions. This will use the PHP CLI interface ("PHP on the command line"), which always has max_execution_time=0 (unlimited), unlike your webserver.
Make sure that Drupal does not self-limit its now unlimited execution time for the cron job to 240 s again. Because,this happens prior to Drupal 7.40 due to Drupal Core issue #2233929. So just make sure you have Drupal 7.40 and it's fine.

Now, Drupal will still call drupal_set_time_limit(240) etc. in its code, but since Drupal 7.40 they have no effect anymore if execution time is unlimited as here (see the current source of drupal_set_time_limit()).


Telerik RadCalendar - Specialdays : How to display Date of the Special Day

Question: I am not familiar with RadCalendar component. Pleas bear with me if my question is a basic functionality.
My purpose is to display selected days with different BackColor values, according to the selection of the client. Basically only changing the ItemStyle for the selected days are acceptable for me, but I couldn't find how to do it?
So I tried a differen approach as follows:
I created SpecialDays in my Calendar
<telerik:RadCalendar AutoPostBack="true" ID="calendar1" runat="server"  Width="400px" Height="300px" FirstDayOfWeek="Monday">
            <SpecialDays>
                <telerik:RadCalendarDay TemplateID="temp1"></telerik:RadCalendarDay>
            </SpecialDays>
            <SpecialDays>
                <telerik:RadCalendarDay TemplateID="temp2"></telerik:RadCalendarDay>
            </SpecialDays>
            <SpecialDays>
                <telerik:RadCalendarDay TemplateID="temp3"></telerik:RadCalendarDay>
            </SpecialDays>
            <CalendarDayTemplates>
                <telerik:DayTemplate ID="temp1" runat="server">
                    <Content>
                       <asp:Label ID="lblTemp1" runat="server"></asp:Label>
                    </Content>
                </telerik:DayTemplate>
                <telerik:DayTemplate ID="temp2" runat="server">
                        <Content>
                            <asp:Label ID="lblTemp2" runat="server"></asp:Label>
                        </Content>
                </telerik:DayTemplate>
                <telerik:DayTemplate ID="temp3" runat="server">
                        <Content>
                            <asp:Label ID="lblTemp3" runat="server"></asp:Label>
                        </Content>
                </telerik:DayTemplate>
            </CalendarDayTemplates>
        </telerik:RadCalendar>

And in code behind, I am assiging the selected days to the desired template when the client press the button of choice as SetAstemp1, SetAstemp2 or SetAstemp3:
protected void BtnSetAsTemp1_Click(object sender, EventArgs e)
    {
        int daysCount = calendar1.SelectedDates.Count;

        for (int i = 0; i < daysCount; i++)
        {
            RadCalendarDay day = new RadCalendarDay();
            day.TemplateID = "temp1";
            day.Date = calendar1.SelectedDates[i].Date;
            calendar1.SpecialDays.Add(day);

        }
    }

But with this approach, I cannot use the embedded skin in RadCalendar control. When the selected day is assigned to a special day, the date of the cell is not displayed.
And I have to show the date in Content tag of the related SpecialDay. But I could not find a way to access the lblTemp1 control defined in the Content.
Could you please point me to the right direction if my approach is not right?
Or any suggestions to display the date in the lblTemp1.Text is appreciated.
Thank you!
Answer: Impulse, I think that the simplest method is to set the backcolors for selected dates hooking the DayRender event of the Telerik calendar. I found this online example that might be useful to you.
Answer: RadCalendarDay holiday = new RadCalendarDay();
holiday.Date = Datetime.Now;//Your date which you want
holiday.IsSelectable = false;
holiday.IsDisabled = true;
holiday.ToolTip = "NOT AVAILABLE";
TableItemStyle style = new TableItemStyle();
style.BackColor = Color.HotPink;
holiday.ItemStyle.CopyFrom(style);
calendar1.SpecialDays.Add(holiday);


How to determine which Windows update, updates a specific DLL?

Question: The combination of Windows XP SP2 and SQL Server Express 2005 SP3 can causes the machine to blue screen during the installation of SQL Server Express. One of the Windows Updates that you can apply to Windows XP SP2 fixes the problem. Unfortunately, if you install Windows XP SP2 and run Windows Update, it will tell you that it needs to install about 118 updates. I would like to know which of the 118 updates fixes the problem. I know that the fix involves updating SXS.DLL to version 5.1.2600.3019.
Other than installing each update one at a time and checking the version of SXS.DLL after each update, is there an easier way of determining which update fixes the problem?
Answer: Yes: put it into Google. Every Microsoft KB article about a hotfix shows the version numbers of replaced files, so it's quite easy to found the article referencing the update you're looking for.
http://www.google.it/search?q=SXS.DLL+5.1.2600.3019
http://www.microsoft.com/technet/security/Bulletin/ms06-075.mspx
About those 118 updates: why don't you want to install them? And why not install SP3? Updates are released for a reason (fix bugs, close security holes, etc.), you shouldn't run a plain Windows XP SP2 system in the year 2009.
Unless you have a really good reason for doing that, of course (like incompatible software); but if you are one of those people who just don't want to "lose time" installing updates, I strongly advise you against this; it's a really good way to look for troubles.
Comment: Rather than tell the customer they have to install ALL the updates or Windows XP SP3, we would like to tell them which specific update that they need to install. It's about minimal machine impact.
Comment: Agreed on the minimal impact issue, but I'm still heavily convinced that running an obsolete and unpatched O.S. release is just asking for **much more** impact in the long term.
Answer: The specific version of sxs.dll that you refer is from Microsoft Security Bulletin MS06-075.
How do you know that the bsod is fixed in that specific version?
Update to comment: I think that its not so simple. As explained in kb824994 there are two branches in windows fix/update land. except from the usual one. There is the quick fix engineering one. Maybe the fix you need is on that branch. So installing only the security bulleting wont install the fix you need. If you really want to update sxs.dll just look for the latest hot fix including it you can find. I have found kb943232.
Comment: Just through testing. It's actually fixed by an earlier downloadable 'hot fix' but it appears that it is also fixed by a later 'Windows Update'.
Comment: The Windows Update referenced in the article Microsoft Security Bulletin MS06-075 does fix the SQL Server 2005 SP3 blue screen issue. The Windows Update is number is 926255 and is only applicable to XP SP2 (XP SP3 updates SXS.DLL).
Answer: After posting this question I decided that I could probably determine which updates, update this file (SXS.DLL) by grep'ing the .log files in the C:\Windows folder after installing all of the updates. These log files list which DLLs are being updated along with version information.


How to return a co-ordinate structure in C

Question: float generateCoor()
{
    srand(time(NULL));

    coordinate cd; //structure variable
    cd.rx = genRand();
    printf("X-coordinate: %.2f\n",rx);

    cd.ry = genRand();
    printf("Y-coordinate: %.2f\n",ry);
}

Now since one function cannot return two variables simultaneously, than how can I return the co-ordinates back to the main function?
Comment: A common approach is to define a `struct`, and pass around a pointer to it.
Comment: Does C still not let you actually return a struct?  I figured they'd have fixed that by now.  Oh. wait...
Answer: You can use either of following :-
coordinate generateCoor() { ... return cd;}

int main(){
coordinate c = generateCoor();
}

OR
void generateCoor(coordinate *cd) { ... }

//Give it a proper name something like constructCoor

int main(){
coordinate c;

generateCoor(&c);
}

Comment: If i were going to require the caller to pass in a struct, i might call the function something less "i create stuff"y.  Maybe `constructCoor`?
Comment: @cHao _"What's in a name?"_ ~William Shakespeare :D
Answer: You can create structure, and return pointer to that structure.


What is the justsification for this restriction on UG?

Question: In my textbook, there is a restriction on universal generalization:
UG must not be used within the scope of an indented sequence(i.e. conditional proof or indirect proof) if the instantial variable y is free in the first line of that sequence.
Then the book gives a example using conditional proof:
1.∀x(Rx)→∀x(Sx)$\quad Premise$
$\quad$2.Rx  $\quad ACP$
$\quad$3.∀x(Rx)  $\quad 2.UG(Invalid)$
$\quad$4.∀x(Sx)  $\quad 1,3 \; MP$
$\quad$5.Sx  $\quad 4.UI$
6.Rx→Sx  $\quad 2-5\;  CP$
7.∀x(Rx→Sx)  $\quad 6\; UG$
This proof is invalid. However, I don't know what is the logic of this restriction. The UG used in line 3 looks perfectly fine to me. Since the "Rx" in the second line, as my book claims, is a statement function, which does not have truth value unless the variable is replaced by a constant, then what does the assertion of "Rx" in line 2 mean? Probably the assertion of "Rx" means that this statement function is always true. But if I take this meaning, then it seems that line 3 just reexpresses the sense of line 2, and then the UG used here  just looks valid. And I find it interesting that this restriction applies only to conditional proof and indirect proof, but why only them? I'm just confused by it.
Comment: The details of these systems tend to vary from book to book, but it seems that the $x$ in line 2 really means some *fixed* object $x$. You'd need to read the details of how these "indented" proofs are used in the book's system. In any case, you can tell that the deduction is invalid overall. For example, say $Rx$ is "$x$ is even," and $Sx$ is "$x$ is odd." Then for the set $\mathbf{Z}$, the implication "if every number is even, then every number is odd" is vacuously true, yet "for any number, if it is even, then it is odd" is obviously false. So you should be convinced there's a problem.
Comment: I edited the title. "What is the logic of X" can be misread as "what 'logic' is generated by X". For example, some rules may generate the usual first-order logic, while other rules generate other logics.
Comment: In the kind of proof system here, when you assume "$Rx$" as an assumption, you are assuming that it holds for *some* $x$. That is why the rule needs to be limited.
Answer: The problem is that :

$\varphi \rightarrow \forall x(\varphi)$

is not valid in first-order logic.
Basically, steps 2-3 in the (fallacious) proof of the question amounts to this; assume $\varphi$ [i.e. $Rx$] and infer $\forall x(\varphi)$ [i.e. $\forall x (Rx)$].
In order to show that the formula $\varphi \rightarrow \forall x \varphi$ is not in general correct, consider the following example :

$\varphi$ is $x > 0$

and take as the domain of the interpretation the set $\mathbb N$ of natural numbers.
Thus, the formula :

$\varphi \rightarrow \forall x(\varphi)$

means :

$x > 0 \rightarrow \forall x(x > 0)$

which is not true in $\mathbb N$.
We have to recall the basic semantic definitions; see Herbert Enderton, A Mathematical Introduction to Logic (2nd - 2001), page 83 :

we will define what it means for [a structure] $\mathfrak A$ to satisfy $\varphi$ with $s$ [where the assignement function $s : Var \to |\mathfrak A|$ is a function from the set $Var$ of all variables into the universe $|\mathfrak A|$ of $\mathfrak A$] :

$$\mathfrak A \vDash \varphi [s]$$

$\mathfrak A \vDash \varphi [s]$ if and only if the translation of $\varphi$ determined by $\mathfrak A$, where the variable $x$ is translated as $s(x)$ wherever it occurs free, is true.

In our example, if we consider $s$ such that $s(x)=1$, we have that :

$(x > 0)[s]$ is $1>0$, which is true in $\mathbb N$, while obviously $\forall x (x > 0)[s]$ is false in $\mathbb N$ [because not $0>0$].

Thus :

not $\mathbb N \vDash ((x > 0) \rightarrow \forall x(x > 0))[s]$

i.e. the above assignment $s$ does not satisfy our formula in $\mathbb N$.
Thus, according to the semantic "convention" regarding formulae with free variables, having found an assignment $s$ such that the formula is not satisfied by $s$ in $\mathbb N$, we say that the formula is not true in $\mathbb N$. [Note. Intuitively, a formula $\alpha(x)$ with free variable $x$ is said to be true in $\mathfrak A$ if every sentence obtained from it by replacing $x$ by an arbitrary element $s(x) \in |\mathfrak A|$ is true.]
Conclusion
Having found an interpretation in which the formula :

$\varphi \rightarrow \forall x(\varphi)$

is not true, we conclude that it is not valid.

This is the reason for the restriction regarding the application of $UG$ ...

Added
In David's answer you can find a different explanation : the key-point is the invalidity of :

$\varphi \rightarrow \forall x(\varphi)$.

As you probably know, there are different proof systems for first-order logic : Natural Deduction, Hilbert-style, ...
But all must be sound, i.e. they must not be able to prove invalid formulae.
In order to prevent this, there are some restrictions needed.
Regarding our example, we can roughly say that the problem is connected with the interplay between Generalization (your $UG$) and Conditional Proof (or Deduction Theorem).
Thus, different systems adopt different restrictions :

we can have (see my answer) an unrestricted Conditional Proof and put restrictions on Generalization,

or (see David's answer) :

we "prefer" an unrestricted Generalization, in which case we need restrictions on the Deduction Th.
Comment: Do you include $0$ in the natural numbers? I ask because $x > 0 \rightarrow \forall x(x > 0)$ is true in $\mathbb N := \{ 1,2,3... \} $ .
Comment: @john - yes I do; but is a matter of "taste"... See the post [How is $\mathbb N$ actually defined?](https://math.stackexchange.com/questions/1417042/how-is-mathbb-n-actually-defined)
Comment: If $\varphi \rightarrow \forall x(\varphi)$ is invalid, why is it listed as a proof method for non-indented proofs. Why is it only invalid in the indented part? Specifically the rule "$Fy$ we can infer $ \forall x (Fx )$" should never be allowed.
Also regarding restrictions on universal, you say there are two approaches;
we can have unrestricted conditional proof and put a restriction on U.G. , or unrestricted Generalization and put restriction on Deduction Theorem. Can you give examples of the former and the latter.
Also can you recommend a book, since this issue seems rather nuanced.
Comment: @john - you can see the post [Generalization rule and logical consequence](https://math.stackexchange.com/questions/580796/elliott-mendelson-introduction-to-mathematical-logic-fourth-edition-gen-rul) as well as [Two forms of Generalization Rule in logic](https://math.stackexchange.com/questions/3993715/two-forms-of-generalization-rule-in-logic).
Answer: I have used a different kind of format for these things, so don't know if this answer will help.  But it seems kind of similar, so will give it a try.
Here is the version I have learnt of the Deduction Theorem, which I think is essentially the same as what you are calling conditional proof:

if a formula $\Psi$ can be proved from a set of assumptions $\Sigma\cup\{\Phi\}$, and if the proof never involves applying the generalisation rule to a variable which is free in $\Phi$, then $\Phi\to\Psi$ can be proved from $\Sigma$.

From this point of view, the problem is not actually in line 3 but in line 6: your formula $\Phi$ is $Rx$ and $\Psi$ is $Sx$ and $\Sigma$ contains the formula in line 1.  Since $x$ is free in $\Phi$, it is not correct to say that line 6 is deduced from line 1.
To understand the reasons behind this, it may help to consider some simpler cases.  An easy case of the Deduction Theorem used correctly is:

from $Rx$ we can prove (in one line!) $Rx$; therefore, $Rx\to Rx$ is a theorem.

This is clearly reasonable, because $Rx\to Rx$ is always true.  On the other hand, here is a simple incorrect use of the Deduction Theorem:

from $Rx$ we can use generalisation to prove $\forall x\,Rx$; therefore $Rx\to\forall x\,Rx$ is a theorem.

This is clearly not reasonable, since $Rx\to\forall x\,Rx$ is not always true and therefore we would not want it as a theorem.  I think perhaps where you are going astray is when you say

Probably the assertion of "$Rx$" means that this statement function is always true.

On the contrary, we are not asserting that $Rx$ is always true; and maybe even "asserting" is not a good word, we are just temporarily assuming it.  After all, when we proved $Rx\to Rx$ as a theorem, it didn't matter whether $Rx$ is true or not, the theorem just says that if it's true, then it's true.  However in the following example we are, in effect, saying that if $Rx$ is hypothetically true even in one case, then it must always be true, which is clearly wrong.
Not sure if all these words help, but see how you go.
Comment: If "$Rx\to\forall x\,Rx$" is invalid, why is it listed as a proof method for non-indented proofs in the first place? In the original proof posted above it is used to go from line $6$ to line $7$. Specifically the universal generalization rule states "from $Fx$ we can infer $ \forall x (Fx )$, where $x$ is an arbitrary selected individual". This seems equivalent to "$Fx\to\forall x\,Fx$" which as you stated is invalid and should not be allowed. So we have a proof method that is based on an invalid inference?
Comment: Also I don't understand this "From this point of view, the problem is not actually in line 3 but in line 6: your formula $\Phi$ is $Rx$ and $\Psi$ is $Sx$ and $\Sigma$ contains the formula in line 1.  Since $x$ is free in $\Phi$, it is not correct to say that line 6 is deduced from line 1." I think this gets to the heart of the matter. Generalization is not the problem per se , but something to do with $x$ being free or not free?
Answer: You can not use generalization on x when x occurs free in undischarched assumptions of your proof. This is way of saying that you do not assume any properties of x so x can by any object. For more explanation you can consult logic and structure written by Dirk van Dalen or Mathematical Logic by Chiswell.
Answer: The answer is systemic but applies to each system. Generally, in prenex normal form, $M(\varphi) \vdash \forall x M(x)$, i.e., UG, is not allowed unless $M(x)$ does not include $\varphi$, where $\varphi$ an individual instantiation of the quantifier $x$. Informally, we can see that under this condition, what $\varphi$ is does not matter. The important thing is that $\varphi$ not be in $M(x)$. This preserves logical truth but not truth. See. Herbrandization, so soundness (of an inference) does not matter but consistency (of the system) does.
$\vdash M(\varphi)$ if and only if $\vdash \forall x M(x) : \varphi \not \in M(x)$.
This does not mean that $M(\phi) \vdash \forall x M(x)$ is sound even if $\varphi \not \in M(x)$.
Comment: I'm confused by this. Why are you talking about soundness? We are looking at natural deduction proofs , which is a syntactic thing. Can you give an example where it is not sound and what does that to do with universal generalization proof method. And what is the difference between logical truth and truth. I guess the former is true by logical validity and the latter is true in the sense that the premises are true.


Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form

Question: The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with the definition (photos = ...) makes the plus sign appear. However, in order to use a custom Field/Widget I need to figure this out.
class GalleryForm(ModelForm):

    photos = ModelMultipleChoiceField(queryset=Photo.objects.all(), label="Photos")

    def __init__(self, *args, **kwargs):
        super(GalleryForm, self).__init__(*args, **kwargs)

I've peeked at the Django source code and it seems like I have to wrap my widget in a RelatedFieldWidgetWrapper, but I haven't quite gotten my head around it. Any help is apprecietad!
Answer: With the help from lazerscience and this post I ended up with the following.
The ModelAdmin:
class GalleryAdmin(admin.ModelAdmin):

    form = GalleryForm

    def __init__(self, model, admin_site):
        self.form.admin_site = admin_site
        super(GalleryAdmin, self).__init__(model, admin_site)

And my form:
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper

class GalleryForm(ModelForm):

    photos = ThumbnailChoiceField(queryset=Photo.objects.all(), label='Photos', widget=MyWidget(), required=False)

    def __init__(self, *args, **kwargs):
        super(GalleryForm, self).__init__(*args, **kwargs)
        rel = ManyToOneRel(self.instance.photos.model, 'id')
        self.fields['photos'].widget = RelatedFieldWidgetWrapper(self.fields['photos'].widget, rel, self.admin_site)

Comment: In Django 1.2 an exception is raised saying that the form doesn't have a `admin_site` attribute. Am I doing something wrong?
Comment: @orokusaki A bit too late (like 7 years after) but you can try: `from django.contrib.admin import site as admin_site` as seen [here](https://github.com/django/django/blob/9dc83c356d363c090f3351c908cad6f823aeb7bf/tests/admin_inlines/tests.py#L9)
Comment: Thanks, Reimund for the response, I have been struggling to come up with this and your answer has really helped me.

But now my issue is that the popup is replacing the current URL and cannot open in a popup window. How can I go about it?
Answer: Yes you are right, you have to wrap your widget with django.contrib.admin.widgets.RelatedFieldWidgetWrapper, which turns out to be a bit complicated since it expects the current admin site as a parameter for initialization! Maybe you will find this post helpful!


change detection formula most suited to analyse 3 vector changes

Question: The following data is captured from the magnetic sensor of a device.
This data has a time factor.
The device is at times in motion and other times still
How can one detect (using formula) if there is a significant change in the magnetic field so as to differentiate between the device being in motion and the device being still.
Columns are as follows (x signal, y signal, z signal, timestamp)
Note: we may combine x,y,z into one field using a formula  sqrt(x^2 + y^2 + z^2)
<code>            -12.718201, -6.2164307, 62.046814   ,  1538194954316
            -43.415833, -12.576294, 62.527466   ,  1538195258969
            -19.099426, -20.405579, 53.93982    ,  1538195608542
            36.384583, -2.8259277, 125.75989    ,  1538196141515
            3.7750244, -52.175903, 7.0632935    ,  1538196696008
            -57.774353, -0.17547607, -34.48639  ,  1538197016697
            -19.52362, -33.039856, -11.776733   ,  1538197575860
            -14.483643, 7.3242188, 49.07837 ,  1538197889355
            -61.299133, -10.044861, -10.276794  ,  1538198275366
            -7.598877, -27.565002, 38.954163    ,  1538198604350
            6.6818237, -19.360352, 45.41931 ,  1538198916440
            5.3466797, -20.59021, 44.63806  ,  1538199218767
            4.4311523, -21.595764, 43.948364    ,  1538199662156
            20.075989, -32.650757, 91.15448 ,  1538200082654
            14.196777, -17.500305, 56.92444 ,  1538200408499
            14.120483, -17.33551, 56.60858  ,  1538200722135
            14.961243, -16.825867, 57.299805    ,  1538201524650
            14.060974, -17.636108, 55.8136  ,  1538202502702
            16.416931, -10.900879, 59.924316    ,  1538203467708
            34.70,  1538, -42.219543, -12.271118    ,  1538203770037
            26.541138, -33.729553, 42.088318    ,  1538204432606
            -2.9037476, -46.420288, 27.973938   ,  1538205300693
            28.746033, -42.57965, 12.928772 ,  1538205775288
            27.441406, -40.000916, 6.7489624    ,  1538206205786
            39.141846, -42.070007, 1.7837524    ,  1538206565996
            11.735535, -40.135193, -8.190918    ,  1538207068072
            33.441162, -34.03015, 4.109192  ,  1538207429684
            30.140686, -35.84442, 4.019165  ,  1538207922966
            -4.823303, -46.780396, 26.098633    ,  1538208284175
            -8.934021, -47.27478, 23.068237 ,  1538208716472
            56.64673, -32.35016, 3.5079956  ,  1538209153066
            0.8468628, 21.784973, 56.489563 ,  1538209521175
            1.5808105, 22.340393, 56.56433  ,  1538209824603
            0.7720947, 22.7005, 55.604553   ,  1538210815860
            0.2166748, 24.18518, -59.835815 ,  1538211721937
            -0.05340576, 23.62976, -59.925842   ,  1538212665907
            -11.079407, 23.675537, 45.49408 ,  1538213486000
            -8.4991455, 36.860657, 44.06891 ,  1538213789633
            -0.05340576, 22.219849, 56.89392    ,  1538214091858
            0.35095215, 22.399902, 55.79834 ,  1538214416776
            -14.604187, 33.54492, 45.7489   ,  1538214757598
            2.0462036, 21.679688, 57.658386 ,  1538215059916
            2.2705078, 22.070312, 56.217957 ,  1538215463919
            4.6417236, 23.464966, -55.485535    ,  1538215776043
            4.9560547, 23.480225, -55.770874    ,  1538216078469
            -6.3095093, 44.000244, 38.36975 ,  1538216396388
            10.08606, -19.270325, 65.608215 ,  1538263082893
            10.08606, -19.270325, 65.608215 ,  1538263082893
            15.606689, -14.515686, 55.18341 ,  1538263760629
            2.7053833, -24.6109, 38.14392   ,  1538264179725
            2.7053833, -24.6109, 38.14392   ,  1538264179725
            3.9367676, -24.624634, 38.7146  ,  1538264484521
            3.9367676, -24.624634, 38.7146  ,  1538264484521
            4.0115356, -23.980713, 38.684082    ,  1538264830196
            4.0115356, -23.980713, 38.684082    ,  1538264830196
            3.3660889, -25.645447, 37.709045    ,  1538265135334
            3.3660889, -25.645447, 37.709045    ,  1538265135334
            3.4866333, -24.549866, 38.77411 ,  1538265439125
            3.4866333, -24.549866, 38.77411 ,  1538265439125
            3.9520264, -24.760437, 38.323975    ,  1538265738751
            3.9520264, -24.760437, 38.323975    ,  1538265738751
            3.90625, -24.264526, 38.789368  ,  1538266042583
            3.90625, -24.264526, 38.789368  ,  1538266042583
            4.0115356, -24.925232, 38.128662    ,  1538266361898
            4.0115356, -24.925232, 38.128662    ,  1538266361898
            4.0863037, -24.085999, 38.414   ,  1538266666426
            4.0863037, -24.085999, 38.414   ,  1538266666426
            4.1015625, -23.905945, 38.789368    ,  1538266972752
            4.1015625, -23.905945, 38.789368    ,  1538266972752
            3.6514282, -24.685669, 38.15918 ,  1538267571704
            8.480835, -22.03064, 50.48828   ,  1538267875317
            8.570862, -20.87555, 49.96338   ,  1538268178843
            8.511353, -21.040344, 50.02289  ,  1538268482369
            8.976746, -21.220398, 50.143433 ,  1538268785994
            -1.4938354, -19.239807, 49.394226   ,  1538269583765
            9.965515, -21.174622, 34.918213 ,  1538270525838
            10.626221, -20.994568, 34.214783    ,  1538271159386
            11.735535, -20.080566, 35.264587    ,  1538271788831
            11.557007, -19.570923, 36.149597    ,  1538272087257
            9.516907, -21.76056, 34.709167  ,  1538272403782
            9.486389, -20.890808, 35.23407  ,  1538272702208
            9.306335, -21.534729, 35.24933  ,  1538273006933
            9.231567, -21.76056, 34.843445  ,  1538273314658
            8.840942, -21.775818, 35.23407  ,  1538273619714
            9.156799, -22.30072, 34.843445  ,  1538273927994
            8.992004, -22.239685, 35.534668 ,  1538275489504
            8.557129, -22.450256, 34.36432  ,  1538275787028
            8.390808, -22.929382, 36.523438 ,  1538276691072
            7.6705933, -22.975159, 36.98883 ,  1538277352472
            7.7163696, -22.735596, 36.883545    ,  1538278611579
            7.852173, -23.57483, 37.31842   ,  1538279282128
            2.4368286, 21.31958, -56.536865 ,  1538280332534
            2.7053833, 21.995544, -56.37207 ,  1538280937891
            2.6168823, 22.340393, -56.565857    ,  1538281844967
            2.9907227, 22.48993, -57.510376 ,  1538282750451
            -26.54419, 26.434326, 44.503784 ,  1538283048971
            24.066162, 5.104065, 61.079407  ,  1538283383594
            23.76709, 5.4504395, 61.33423   ,  1538283863574
            23.87085, 1.3549805, 60.598755  ,  1538284538406
            24.336243, 1.2054443, 61.288452 ,  1538285494179
            24.020386, 1.5945435, 61.228943 ,  1538286514128
            -17.408752, 34.71527, 45.133972 ,  1538287869792
            24.276733, 4.7454834, -59.74579 ,  1538288474649
            24.14093, 4.234314, -60.375977  ,  1538289084002
            -12.579346, 40.87982, 40.12451  ,  1538289775226
            -16.358948, 32.974243, 46.273804    ,  1538290103548
            7.446289, -15.234375, 49.768066 ,  1538301760672
            11.302185, -1.0757446, -55.036926   ,  1538302063111
            41.15143, -20.500183, -38.746643    ,  1538302490209
            49.23706, 8.360291, 19.708252   ,  1538302955188
            55.14679, 5.899048, 0.55389404  ,  1538303257514
            10.296631, -51.96991, -5.836487 ,  1538303592431
            5.555725, -52.149963, 3.8986206 ,  1538303913855
            15.156555, -48.519897, -0.105285645 ,  1538304216080
            55.252075, 0.78430176, 4.5440674    ,  1538304513209
            14.901733, -6.6848755, -50.31128    ,  1538304814535
            17.556763, -4.9453735, -49.531555   ,  1538305258231
            17.07611, -4.43573, -50.341797  ,  1538305885274
            16.80603, -4.0145874, -50.656128    ,  1538306849839
            16.911316, -5.064392, -50.35553 ,  1538307934275
            2.7069092, -9.054565, -54.196167    ,  1538311487005
            7.762146, -7.044983, -55.111694 ,  1538318042202
            8.226013, -7.029724, -54.571533 ,  1538318348333
            28.881836, -20.724487, 34.6344  ,  1538322159796
            55.836487, 2.0751953, 4.034424  ,  1538322473121
            55.40161, 0.74005127, 2.1881104 ,  1538322775548
            55.656433, -0.44555664, -0.6011963  ,  1538323077773
            6.111145, -53.260803, -5.041504 ,  1538323403594
            4.6569824, -53.260803, 3.237915 ,  1538323706020
            4.147339, -52.915955, 1.7837524 ,  1538324008146
            16.056824, -49.031067, -14.460754   ,  1538324310571
            16.671753, -38.830566, -33.00171    ,  1538324607800
            12.696838, -42.234802, -29.986572   ,  1538324904227
            15.2908325, -42.715454, -28.831482  ,  1538325200955
            15.802002, -41.410828, -30.33142    ,  1538325504501
            25.115967, -37.58545, -30.421448    ,  1538325806906
            26.000977, -31.40564, -36.106873    ,  1538326109333
            38.82599, 8.479309, -38.687134  ,  1538326411561
            2.6763916, -15.1901245, 54.553223   ,  1538326714988
            11.091614, -11.425781, 55.34973 ,  1538327101994
            5.2719116, -13.525391, 54.733276    ,  1538327760734
            3.5461426, -13.510132, 54.808044    ,  1538328693404
            3.7109375, -55.78003, -2.0858765    ,  1538328998328
            2.5558472, -56.289673, -4.470825    ,  1538329304253
            2.0767212, -55.97534, -6.826782 ,  1538329613277
            56.106567, -2.8305054, -1.7562866   ,  1538329943497
            6.126404, -55.23987, -6.3308716 ,  1538330245922
            4.685974, -54.699707, -10.140991    ,  1538330548249
            55.911255, -5.769348, 2.5482178 ,  1538330850574
            39.11133, 12.739563, -37.12616  ,  1538331152901
            -45.06836, 0.14038086, -38.160706   ,  1538331455232
            17.390442, 23.554993, 55.903625 ,  1538347134220
            -20.439148, 7.460022, -38.430786    ,  1538347747579
            7.8216553, -1.361084, 38.668823 ,  1538348220161
            7.8216553, -1.361084, 38.668823 ,  1538348220161
            -18.263245, -5.529785, 44.413757    ,  1538349874458
            -16.912842, -4.2099, 43.933105  ,  1538350264958
            -16.299438, -3.4606934, 44.248962   ,  1538350888812
            -17.408752, -3.2043457, 43.75305    ,  1538351816582
            -17.21344, -2.859497, 43.963623 ,  1538352751656
            -15.0390625, 18.469238, 39.65912    ,  1538353830887
            14.840698, 1.8951416, -48.661804    ,  1538354344165
            14.945984, 1.9851685, -47.98584 ,  1538355025003
            -20.063782, 19.309998, 33.494568    ,  1538355508777
            14.196777, -1.2557983, -48.435974   ,  1538355811207
            14.256287, -1.1352539, -48.616028   ,  1538356307085
            45.20111, 5.2993774, -1.725769  ,  1538356801760
            13.490295, -4.135132, -48.690796    ,  1538357330936
            13.116455, -4.4662476, -48.616028   ,  1538357983879
            -21.833801, 37.864685, 17.36908 ,  1538358586625
            -20.904541, 34.205627, 36.98883 ,  1538376675008
            -20.904541, 34.205627, 36.98883 ,  1538376675008
            -20.904541, 34.205627, 36.98883 ,  1538376675008
            -54.803467, -13.960266, 19.213867   ,  1538377228431
            12.892151, 18.515015, 49.409485 ,  1538377529758
            -19.299316, -15.115356, -50.37079   ,  1538377828945
            27.410889, 30.439758, 17.173767 ,  1538378132271
            33.14209, -121.65985, 58.439636 ,  1538378799010
            25.29602, -19.210815, -1.9210815    ,  1538379096134
            31.70166, 18.455505, -25.186157 ,  1538379398086
            -13.418579, -1.8707275, -58.546448  ,  1538420544161
            -13.418579, -1.8707275, -58.546448  ,  1538420544161
            -13.62915, -1.84021, -58.605957 ,  1538421151809
            -13.62915, -1.84021, -58.605957 ,  1538421151809
            -12.849426, -1.4953613, -58.410645  ,  1538422062386
            -12.849426, -1.4953613, -58.410645  ,  1538422062386
            -11.888123, -1.045227, -58.39691    ,  1538422970267
            -11.888123, -1.045227, -58.39691    ,  1538422970267
            -13.508606, 2.2994995, -58.621216   ,  1538426539190
            -13.508606, 2.2994995, -58.621216   ,  1538426539190
            -21.218872, 21.424866, 44.892883    ,  1538429695519
            -21.218872, 21.424866, 44.892883    ,  1538429695519
            23.81134, 1.1001587, -54.286194 ,  1538430409350
            23.81134, 1.1001587, -54.286194 ,  1538430409350
            -18.188477, 41.56952, 33.374023 ,  1538430735066
            -18.188477, 41.56952, 33.374023 ,  1538430735066
            56.570435, 4.849243, -1.876831  ,  1538431244046
            56.570435, 4.849243, -1.876831  ,  1538431244046
            -36.819458, 29.225159, 35.038757    ,  1538431665892
            -36.819458, 29.225159, 35.038757    ,  1538431665892
            -121.02814, -63.459778, -74.16077   ,  1538432237155
            -121.02814, -63.459778, -74.16077   ,  1538432237155
            5.4214478, -22.390747, -32.70111    ,  1538432879063
            5.4214478, -22.390747, -32.70111    ,  1538432879063
            22.805786, -68.98041, -22.291565    ,  1538433213184
            22.805786, -68.98041, -22.291565    ,  1538433213184
            15.306091, 17.480469, 71.15936  ,  1538433516174
            15.306091, 17.480469, 71.15936  ,  1538433516174
            -14.663696, -52.81067, 18.148804    ,  1538434199096
            -14.663696, -52.81067, 18.148804    ,  1538434199096
</code>
Comment: am trying to use a magnetic sensor as opposed to accelerometer because of power consumption, as the device will be getting this values every ~ 5 min
Comment: also accelerometer is more suited for small changes where us the magnetic field could be used to infer that the device has moved from one location to another.
Comment: What are the units of the signals, including time?
Comment: the time is in milliseconds since Unix Epoch, the x,y,z are signal strengths
Comment: Thanks for the time units. You have not yet provided the units for the other signals, since "signal strengths" is not a physical unit. Are we talking magnetic field strength, like Federico assumed? In that case the units might be Teslas. What we need here is a recognized physical unit for the three other signals.
Comment: @AdrianKeister Why would you even care about the unit constant? It's completely irrelevant. Changing unit would simply rescale the data
Comment: @Federico: Knowing the data before analyzing the data is, I believe, an important step. It helps flesh out what analysis would be relevant, and what would not be relevant. And knowing what units apply to which channels is an important step in understanding physical sensor data. For these reasons, I disagree with your statement that knowing the units is irrelevant. For example, while it's early yet, I'm interested in knowing whether $\mathbf{F}=q(\mathbf{E}+\mathbf{v}\times\mathbf{B})$ is relevant or not. Probably not, but you can't know until you thoroughly know the data.
Comment: But here we just have one field, not many to compare, where the relative units would be significant. With just one field, you don't care about the units. The unit is: "sensor of the device". If you like you can multiply all data so that it lies in $[-1,1]$ and the problem remains exactly the same
Comment: @Federico: What I'm getting at is the physical interpretation of those channels. What do they mean, physically? Data acquisition is an immensely complicated area (I know, I've worked in it for 7+ years), and knowing the units has always been important for me. Perhaps knowing the physical units isn't important for your understanding, but it is for mine, if for no other reason than, at the end, when I draw a graph, it'd better have SOUL: Scale, Origin, Units, and Labels. Are these channels components of $\mathbf{B}?$ Or $\mathbf{H}?$ Where are the sensors placed? This can all be important.
Comment: @AdrianKeister Ok, then tell me what would be different *in this example* if the unit were µT versus GT.
Comment: @AdrianKeister Moreover, we can probably infer that the unit is in the range of µT, because that is the order of magnitude of Earth's magnetic field ([source](https://en.wikipedia.org/wiki/Tesla_(unit)#Examples)). Unless if he went on a walk with his phone on the surface of a white dwarf, where fields of 100T are more common...
Comment: @AdrianKeister On a side note, soul seems quite a useless thing to have
Comment: @AdrianKeister lets assume the units are Teslas
Comment: It's been awhile since I've looked at this problem. I'm not sure you're going to be able to detect motion of the sensor itself using a magnetic field detection sensor. How could you tell the difference between the device itself moving through the earth's (or just ambient) magnetic field, versus the device being stationary, and the ambient magnetic field changing around it? I would think accelerometer data would be a lot more useful for detecting motion.
Answer: Since we don't have any information on the orientation of the device, I only looked at the norm of the magnetic field. Here is a plot:

As you can see, there are intervals over which the norm of the magnetic field is relatively constant (from 50 to 100 and around 130).
EDIT
Given we have not much additional information on the underlying physical process, the most reasonable thing to do seems to me to just look at some moving variances (see for instance here, here, here, here). What I mean is that you fix some window timeframe and look at how much the data oscillates in that window. If the oscillation is sufficiently low, then the field you are measuring is almost constant in norm, which could mean that you are almost stationary.
Comment: i took your suggestion and used Knime to get some Moving Averages . the smallest duration is 15 min and the highest duration is 2 hour, plotting a graph using this two lines, i get the lines crossing close to the times, the device was on the move. i have put a link to the Kinme export file. https://www.dropbox.com/s/dui57q33a1pdooe/KNIME_magnetic_signal_MA.knwf?dl=0
Comment: am assuming one axis should be the time stamp, correct me if am wrong
Comment: Oh yes sure, sorry. The horizontal axis is time, the vertical is the norm of the field
Comment: probably i can use several moving variances, where i can treat one of the variance as a signal line
Comment: here is a link to the data magnetic signal https://www.dropbox.com/s/at1mwuc9osssq5j/hardwareCsv_MAGNETIC_FIELD_SOURCE_analysis.csv?dl=0    the fields are [guid,source,x,y,z,accuracy,timestamp] the time stamp is in milliseconds since Unix Epoch


Gravar Informações de um FORM na mesma Página

Question: gostaria de uma ajuda bem breve, estou fazendo um formulário para envio de currículo com HTML + PHP, gostaria se saber  como seria feito o seguinte para adicionar um curso. (1º adicionamos um curso) , (2ª colocamos informações do curso) e depois quero que ele fique gravado como na imagem 3 na mesma página
Comment: Você pode fazer isso via javascript e ajax
Answer: É fácil, vou usar algumas variáveis do js para simular dados salvos no banco de dados:
No exemplo irei usar JS e HTML5:

$( document ).ready(function() {

    $("#saveCurso").click(function(){

      nome = $("#inpNomeCurso").val()
      tempo = $("#inpTempoCurso").val()
      area = $("#inpAreaCurso option:selected").text()

      var tr =
            ""+
              "
"+
              ""+nome+"	"+area+"	"+tempo+" hora	"+
              "
"+
            "";

      $("#tbody").append(tr);

      $("#inpNomeCurso").val("")
      $("#inpAreaCurso").val("")
      $("#inpTempoCurso").val("")
      $('#exampleModal').modal('hide')

    });

});
#addCurso{

  position: absolute;
  right: 0px;
  top: 0px;

}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Dados e formulario do curriculo

      <button type='button' class="btn btn-primary float-right" id="addCurso" style="" data-toggle="modal" data-target="#exampleModal">Adicionar Curso</button>

Cursos Extracurriculares

        Nome do Curso

        Área do Curso

        Duração:

Cursos Extra Curricular

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        Nome do Curso
        <input type="text" class="form-control" id="inpNomeCurso">
        ÁREA do Curso
        <select class="custom-select" id="inpAreaCurso">
          <option selected>Selecione uma Area</option>
          <option value="1">Tecnologia</option>
          <option value="2">Administração</option>
          <option value="3">Biologia</option>
          <option value="4">Advogacia</option>
          <option value="3">Matematica</option>
          <option value="3">Quimica</option>
        </select>
        Tempo de Curso (horas)
        <input type="number" class="form-control" id="inpTempoCurso">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
        <button type="button" class="btn btn-primary" id="saveCurso">Salvar</button>

Agora é só você enviar essas variáveis para salvar no seu banco
Comment: Exatamente o que precisava, muito obrigado


Css border outside of image width

Question: I want to keep border outside of image width
Let I have image with 75X75 Now I apply 5 px border on the image. still it 75X75 px. border placed inside the image width. But I want border placed outside of image width so total size will be 85X85
I try this code

img {
  border: 5px solid red;
  border-radius: 5px
}

Comment: Why not just change the image width and height to 85x85?
Comment: You're looking for the `box-sizing` css property, I believe
Comment: @jbutler483 yah you are right. its work. give an answer so that I can accept
Answer: I believe you are looking for the box-sizing CSS property,
in which sets the value of whether a border is included in the size of said 'box'
it can be set to either: content-box | padding-box | border-box

div{
  height:100px;
  width:100px;
  background:black;
  border:10px solid gold;
  display:inline-block;
  margin:10px;
  box-shadow:0 0 10px 5px black;
  }
.border-box{
  -webkit-box-sizing:border-box;
  box-sizing:border-box;
  }

html,body{
  height:100%;
  background:#222;
  }

Please also note
Using inline styling is seen as bad practise, as it can lead to specificality issues further down the line. Wrap your css in a <style> tag or go one better and use an external stylesheet for styling purposes.
Comment: I use external css. here use inline css for example
Answer: Try this:

Comment: I dont want to use img under a div. Is there any possible way to apply css in img tag
Comment: yes you can use css in img tag. remove inset from your img tag's style attribute. Post your code to jsfiddle and show me what do you want
Comment: Check edited answer, and provide a screenshot of your requirement. So that we can get what do you want exactly.
Answer: Try like this: Demo
img {
    width:75px;
    height:75px;
    outline: 5px solid red
}

Updated demo
You can use Border and border-radius itself, and its working as you expected.
img {
    width:75px;
    height:75px;
    border: 5px solid red;
    border-radius: 5px
}

Comment: good point :). I already use this. but problem is I have to make rounded border by using border-radious.
Comment: provide a screen shot of your requirement.
Comment: and add padding: 2px in GLP's answer, May be thats what you want
Answer: you need to add this to your css

html {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
*,
*:before,
*:after {
  -webkit-box-sizing: inherit;
  -moz-box-sizing: inherit;
  box-sizing: inherit;
}
Answer:

should do the trick

Css border outside of image width


Advice to join LibreOffice Base Table with a MySQL Table

Question: My situation is the following:
There are two databases in two different offices linked together by the corporate network. On of the databases is MySQL, which holds data that can change, but the field types never do. This is standard information for the whole company to access. The second database is LibreOffice Base. It holds extra bits and bobs that that changes, including the number of fields and the types of fields because the company can change their mind about what extra information they want for the products in the main MySQL database.
I only need to join one table in the MySQL database to one in the LO Base database. Both these tables have one field in common called "Code". Currently, we manually enter a large chunk of the data in MySQL into LO to use the "Report Builder" to make a pretty report with all the extra bits and bobs about the products. This is extremely counterproductive, and would be easier if I could just perform a join on these two tables and then use that join in the report builder. It would save a lot of time and be less error prone.
The trouble is that I don't know how to proceed with this. LO Base is a very limited system to work with, but it's all I have to work with as security doesn't allow anything more. I was thinking that I need to create another LO Base database on the computer and have it connect to the MySQL one and I would be able to somehow connect the two LO Base files together???? Is this the right line of thinking? Can't I just use the ODBC/JDBC/Direct Connect feature of LO and do the join?
Also, if I had to make a separate LO Base file, how would the join look? I have never done one between two files like that.
Thirdly, would it be possible to have a query that displays all records in my LO Base database that don't Join with the main DB as this would mean I have imputed the wrong "Code"? This Query would need to be done in LO Base, which is why I ask. I have done a very simple join that didn't cause LO to explode, but this is a bit more complex.
Answer: Don't think LibreOffice Base natively supports mixed data sources using different drivers.  Each LibreOffice database uses just one connector/driver or it uses the HSQLDB engine, but not a mix.
Python could be used to bridge the databases; the many options for getting into LO from Python are discussed in another topic/answer (How to access ODB files in Python 2.7).  Python can be used independently, or from within LibreOffice under the Macro tools.  Also may be possible to build the connection using LibreOffice Basic see API reference but not aware of any code examples.
Python also can use MySQL Connector.  After bridging the databases, most likely option would be to port/insert data into one database using Python SQL command, transferring all data into the same location.


android - auto-login with facebook sdk

Question: I want to use the facebook sdk and be able to automatically login after the app has already logged in once.
Currently from what I can gather if you use the facebook api and you have the facebook app installed and you have signed in with the facebook app then you don't have to login and you will be automatically logged in.
But if you don't have the facebook app then this automatic login will not happen. -----------I want to handle this case and be still able to automatically log in after the user has logged in with my app once.-------------. From my understanding the facebook sdk requires you to login if the facebook app is not there.
Also if the user has logged in once with my app, I will have the access token then as long as the access token has not expired then you don't need to log in again. But if the access token expires then you have to log in again.
Any help will be appreciated. Thanks.
Answer: The functionality you're describing is called single sign on.  Facebook has an entire article dedicated to describing how it works and how to implement it.  Enjoy:
http://developers.facebook.com/docs/guides/mobile/android_sso/

android - auto-login with facebook sdk


Converter binário para hexadecimal

Question: Existe alguma função equivalente à bin2hex() do php para Java?
Preciso converter um binário para hexadecimal.
Answer: Você pode fazer assim
String hexa = Integer.toString(Integer.parseInt("1111", 2), 16);

E de hexadecimal para binário também
String bin = Integer.toString(Integer.parseInt("ff", 16), 2);

Converter binário para hexadecimal


How to measure a spike in data

Question: For example, if I had data like the number of daily coronavirus cases for different countries and I wanted to compare the 'intensity' of the spikes (abnormally large number of cases), what statistical method should I use? Thank you!
Comment: If you define what is expected somehow, then you can define what is the departure from expected. This principle appears everywhere in statistics from looking at deviations from a mean through chi-square tests using counted frequencies to regression-like residuals, and beyond. With coronavirus I would think a minimum processing would be subtract out day of the week effects first by taking a moving average (or just possibly median or geometric mean). That could just be a start.
Comment: No one voted to close so far, but the brevity here didn't encourage any detailed answers until now.
Answer: A spike in data is usually measured as a z-score. And as a kind of rule of thumb, z-scores lower than -3 or higher than +3 could be considered extreme, as 99.7% of values in a normal distribution should fall between -3 and +3.
This requires you to make the assumption that your data distribution is normal.
Because it is a number, the z-score satisfies your desire to be able to compare different spikes in the data. Of course, you could have just compared their absolute values. But with a time-series you could have a moving mean and standard deviation. So if you want to use this to discover unusual daily peaks you might using a moving window of the past 60 days, and base z-scores off the mean and s.d. in its 60 day window.
Aside: Having found the spikes, you will then want to sanity-check them. For instance, with "raw" reported deaths you will find the biggest spikes are just after weekends and public holidays. So you may choose to first smooth that raw data with a 7-day moving average, and then run your 60-day window on the smoothed data; remember though that all peaks and troughs will have been smoothed by this, not just the ones that occur every 7 days.
Comment: This starts with dubious advice and then improves on it.   I wouldn't go further than saying that spikes are usually measured as differences, and sometimes as ratios (differences on a log scale). The OP asks about counts that must be zero or positive and even if we are focusing as we are on departures from expected, it is far from obvious that normal distribution is a reference.
Comment: @NickCox Yes, when values have to be >=0 I'd be raising a flag if subtracting 3 or 4 s.d. from the mean took it below zero. And you might want to try detrending the data (in the example of coronavirus cases they seem to either be rising or falling, rather than mean-reverting). But as you noted it is a relatively brief question, on a topic it is possible to go very deep on.

How to measure a spike in data