TinyMCE prevent image resizing

Question: I am adding an image to a TinyMCE editor using:
var params = {
             src: filename,
             title: "Attached image: " + filename,
             width: 500
             };

ed.execCommand("mceInsertContent", false, ed.dom.createHTML("img", params));

This insert the image correctly in the editor. However, when the user clicks on the image he has the ability of resizing it.
I would like to know if there is a way to:

Prevent the user to resize only in one direction (i.e. how do I keep a fixed aspect ratio for the image)
Completely prevent the user to resize the image
Answer: I found a (partial) answer, so I thought I will share it here.
Adding
'object_resizing' : false

In the editor config prevents the resizing.
Note that this is a feature of Mozilla only (e.g. Google Chrome does not allow you to resize the image).
I am still looking for a way of keeping aspect ratio in real time, but I do not know if that is really possible.
Answer: You can simply add this little plugin to tinyMCE, I used it and it works very well!
Here's the documentation: Link
Answer: You would need to implement a resize handler (for example a jQuery handler).
It might be helpfull to add attributes to your images to save its dimensions or to use one single setting holding the aspect ratio. For this you will adjust the tinymce configuration setting valid_elements to allow those attributes for images - otherwise tinymce would strip them out.
When resize gets fired you grab the new dimensions and adjust the dimensions according to the aspect ratio - eigther adjust using the new width or new heigth (the other value is needs to get corrected).
Example: images have an attribute aspectratio holding the aspect ration
You may place this code in thetinymce setup configuration parameter
   setup : function(ed) {
      ed.onInit.add(function(ed) {
        $(ed.getBody()).find('img').resize( function(event){

          $(event.target).css('width', parseInt ( event.target.width * this.aspectratio)  );

        });
      });
   }

Update:
I have created a tinymce fiddle to show an example to use with IE.
Comment: Thanks for taking the time of doing that. However, at least in FF and Chrome (sorry, using Linux, cannot test with IE), I do not have the option of resizing the image. If I turn on `object_resizing` resize events are NOT called... Is there something I am missing?
Comment: there exists a tinymce bug report for the handles under webkit (safari/chrome): tinymce.com/develop/bugtracker_view.php?id=2495
Comment: well, that is not the problem, `object_resizing=FALSE` turns off the handles in Firefox (don't know about IE). The fact that Webkit does not show them is simply because it does not implement object resizing in `iframes`. My point is that resize events are not called even in Firefox. I assume this is due to the fact that the event is not in the same window. So my question is: in IE 1) do you see handles with `object_resizing=false`? 2) are resize events called when you resize the image?
Comment: 1) i see handles in IE. 2) yes resize events are called (unfortunatly too many are firedm, which requires special treatment here (see the fiddle)). but object_resizing:true leads to no handles in firefox

TinyMCE prevent image resizing


Group composition for hypothesis testing

Question: I am working for an online marketing agency and we are often testing different titles/pictures for products etc. which are then shown for example at google shopping.
If we want to test 2 variants of a title to improve the click trough rate (ctr) or conversion rate (cr), we usually randomly assigning a certain amount of products, lets say 10.000, to two different groups. The relevant KPI´ are normally quite similar, differences are being eliminated by switching products to one group or the other. In the end you end up with two groups (~ 5.000 products each) with the same KPI´s.
It will look like this:
Group   Impressions  Clicks  Orders   CTR   CR  No. Products
A       70,160       5,262    421     7.5%  8%  5042
B       74,287       5,572    446     7.5%  8%  4958

My question: is this a legit way or should this be done in a different way?
The KPI´s are usually from the last 30 days, but if you use a different time period, they look already different.
What is a correct way of assigning products with different attributes to two groups? Is a random selection enough if the number is big enough?
Thank you!
Comment: Are you just trying to find if there is a difference in the CTR or CR between two different types of KPI's?
Comment: Yes. But would it make a difference if I would be interested in other KPI´s?
Answer: First and foremost you have to analyze your data to find out how it is distributed. If it is normally distributed, you could do a simple t-test which will tests if two sets of data are significantly different from one another.
Alternatively, if your data is not normal you could used something like a non-parametric Wilcoxon signed-rank test. This will compare your two KPI's if they lack normality by measuring if they came from a similar distribution.
There are plenty of other options for AB testing (a few can be found here). Another option, however, that could be intriguing since you are working with click through rates that are percentages, would be a Fischer's Exact Test. Here you can create a 2x2 contingency table:
Group   Impressions  Clicks
A       70,160       5,262
B       74,287       5,572

From this you can test the null-hypothesis that the rates of A and B are the same versus the alternative hypothesis that they differ. I really like the Fischer's test for the problem you have presented. Hope this helps, and at a minimum the links should provide with more information as you decide what is best for your data and testing.
Comment: Sorry, it must be my language, I am not very fluent in English. Since no lengthy comment discussions are wanted, i will move this to the chat. Anyway, thank you for your help!
Comment: Thank you for your answer. I am using Beta Distribution for these tests, and for comparing the groups, a bayesian test. But my answer was more concerned with the composition of the initial groups. Do these just have to be put together randomly or should one use more sophisticated methods?
Comment: If the initial groups are from the same group they will likely not be any different from one another and I don't know why you would want to compare them. If they are different, I would simply just split them into group A and B based on the different KPI's. I don't see any need to randomly select data -- you can just leave it all in.
Comment: Well these are all different products with different prices, pictures etc. Meaning they all have a different CTR and CR. We have a wide range of products, from pants, to toys, to electronics etc.

Randomly assigning them to one of two groups is how we do it now, but the two groups could end up being not comparable, due to differences in for example number of products of a certain category. Therefore the question if a random process is enough...
Comment: Like you said - the groups may not be comparable. If you're comparing toys to pants that is difficult. I don't see the need for head-to-head testing if you don't want to test the difference between two distinct products or groups.
Comment: If you compare two groups of people together the individuals itself might not be comparable as well, but a large set of people will be. So the idea is that with enough products in each group the groups are comparable.
Comment: I think I am just unsure what you are trying to accomplish from this??


Pegar nome da exceção em Python onde não está específico

Question: Estou usando a exceção Exception, mas queria ser mais específico e pegar a exceção correta, sem o tratamento o código me retorna a seguinte mensagem:

F:\Bel\Desktop\tpredes>guiCliente.py Exception in Tkinter callback
  Traceback (most recent call last):   File
  "C:\Python27\lib\lib-tk\Tkinter.py", line 1537, in call
      return self.func(*args)   File "F:\Bel\Desktop\tpredes\guiCliente.py", line 80, in enviar
      self.test(True)   File "F:\Bel\Desktop\tpredes\guiCliente.py", line 77, in test
      comunicacao.enviar()   File "F:\Bel\Desktop\tpredes\guiCliente.py", line 93, in enviar
      s.connect((self.ip,self.porta))   File "C:\Python27\lib\socket.py", line 228, in meth
      return getattr(self._sock,name)(*args) error: [Errno 10061] Nenhuma conexÒo p¶de ser feita porque a mßquina de destino as recusou
  ativamente

Já tentei vários, mas não funcionam, também pesquisei sobre e não encontrei algo específico, será que a biblioteca que não criou exceções diferentes da mais geral, Exception?
Desde já agradeço a atenção de todos.
Answer: Parece-me que tem a haver com a conecção. Tente:
try:
   s.connect(('IP', 'PORT'))
except socket.error as exc:
   print 'Cautela: %s' % exc

Comment: Muito obrigado, funcionou certinho, você poderia explicar? o socket.error é provavelmente pq buscou na lib, mas e o as exc é uma área específica? Desde já agradeço sua atenção.
Comment: @ViníciusMarques `as` é para dar o nome que quiser só isso. Poderia ser ... `as YOO_MA_MEN:` se quisesse, e depois seria: `print 'Cautela: %s' % YOO_MA_MEN`


$\mathcal{C}$ a family of connected sets with connected union. For all $C \in \mathcal{C}$ there is $C' \in \mathcal{C}$ with $C\cup C'$ connected.

Question: It is easy to show that if the union of a finite family $\mathcal{C}$ of (more than one) connected sets is connected, then for any $C \in \mathcal{C}$ there must always be some other $C' \in \mathcal{C}$ such that $C \cup C'$ is connected. In fact I think this works if $\mathcal{C}$ is a locally finite collection.
But what if $\mathcal{C}$ is not a locally finite collection? I suspect that such $C'$ may not exist in general, but I cannot find a counterexample.
Answer: What about $\mathcal{C} = \{[\frac{1}{n}, 1]\mid n\in\mathbb{N}\}\cup\{\{0\}\}$?
Comment: Not at all. You should always question why you need the hypotheses that are put in place. Finding counterexamples helps to develop mathematical maturity. Great question and a great answer (by you).
Comment: Great answer! Better than the one I thought of right after asking the question, $\mathcal{C} = \{\{x\}\ |\ x \in \mathbb{R}\}$, which is so trivial. I asked a stupid question.


nginx, gunicorn and django weird 504 gateway timeout

Question: I have an nginx / gunicorn / django setup as follows:
Nginx
server {
    listen 80;
    server_name myserver.com;

    root /www/python/apps/pyapp/;

    access_log /var/log/nginx/myserver.com.access.log;
    error_log /var/log/nginx/myserver.com.error.log;

    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 10;
        proxy_read_timeout 10;
        proxy_pass http://localhost:8081/;
    }
}

My upstart script for gunicorn
description "pyapp"
start on [2345]
stop on [06]

respawn

# start from virtualenv path
chdir /www/python/apps/pyapp/
exec /usr/bin/gunicorn  -w 11 -b 0.0.0.0:8081 --error-logfile=/var/log/nginx/pyapp.log wsgi:application

The server is running fine, requests are getting responded to pretty well. However, when i start directing traffic to this setup from my old server, pages start giving 504 gateway timeout errors.
What the requests are doing is only a matter of fetching data from DB and rendering using django-rest-framework. Looking at MySQL processlist, there doesn't seem to be any stuck queries there. This is kinda weird.
Any recommendations?
Answer: First you could try how your backend (django/gunicorn) performs without nginx in front.
ab (apache benchmark) is a simple tool for this task.
You can run it directly from the server, or if your 8081 port is not firewalled from any machine:
ab -c 50 -n 500 http://localhost/path-xyz/

(ab is available through the apache2-utils package, at least on Debian-based systems)
the -c stands for 'concurrency', the -n for number of requests.
If the backend is the bottleneck, and you're using nginx anyway - it could be an option to do some caching (don't know your application, but maybe...).
If your API exposes data that changes often you could set the cache time really short. (1 to 10 seconds) - so if you have e.g. 100 requests per second, only one of those has to hit the backend, the others will get the cached response.
For nginx proxy/cache see e.g. here.


Calculo valor com Virgula com Vue.JS

Question: Boa tarde, o Vue.JS consegue calcular direto no mustache {{}} porém quando um valor vem com virgula, aparece NaN o resultado
ou seja, se a variável for valor = 2 e eu fizer {{ valor - 1 }} ele exibe 1 de boa mas se eu fizer valor = 2,5 e então {{ valor - 1 }} ele exibe NaN

{{ valor - 2 }}

como eu poderia calcular este valor de virgula nos mustaches?
Comment: Vou postar um exemplo, poderia ser com `method` com `filter`, vai de ti mesmo
Comment: É só a vírgula que você precisa tratar mesmo? Que tipo de valores você quer aceitar nesse campos? Vale `1.500`, `R$ 1.500,00`, `1,6%` etc?
Comment: Poderia usar o valor bruto para cálculo e um filter para exibição, daí não teria necessidade de tratar a vírgula
Comment: @bfavaretto sim, a virgula, é bem básico, a variável recebe 4,5 e preciso mostrar 3,5 na verdade
Comment: @DenisRudneideSouza é que o valor bruto é 4,5
Comment: Você poderia utilizar a função `replace`, ex: `number.replace(',', '.')`, porém vai retornar uma `String`, o que pode causar comportamentos estranhos
Comment: Se `valor` é uma string não faz sentido algum fazer cálculos com a variável nos mustaches. Só vai tornar seu código obscuro e/ou gerar gambiarras. A variável `valor` deveria ser do tipo `float`, quem fará essa conversão depende de você, mas nos mustaches não rola...
Comment: @fernandosavio é que é uma informação no topo da página que desejo repetir em vários lugares porém em 1 lugar ela precisa subtrair um certo valor, sei que é obscuro e bizarro, é que não domino, estou estudando e me deparei com esta lacuna
Comment: Então nesse lugar específico você pode fazer a conversão, calcular e depois converter de volta para string. Pode fazer fazer isso no `methods()` se quiser.
Comment: @fernandosavio então eu iria lá onde está o method() ou criar um que recebe a Virgula, troca para Ponto e return com Virgula, seria isso?
Comment: @fernandosavio muito valew amigo
Answer: Troque a vírgula por ponto:

{{ valor.replace(',', '.') - 2 }}

Recomendo criar uma propriedade computada do Vue e fazer o replace lá, para não sujar sua view.
Outra coisa, isso vai funcionar para subtração, multiplicação e divisão, mas adição será tratada como concatenação de strings, conforme comentado acima pelo Denis Rudnei de Souza. Para somar, você precisa ainda converter em número:
+valor.replace(',', '.')

ou
parseFloat(valor.replace(',', '.'))

Comment: realmente, funciona mesmo para subtrair, agora neste caso eu teria que criar um Filter? pois o problema é que no final ele escreve com . ou seja, entra 4,5 e sai 3.5 neste caso a virgula virou ponto no resultado final, calculou mas virou ponto, e esta propriedade computada realmente seria o melhor a fazer, só não sei exatamente o que seria ainda, estou começando a fuçar
Comment: Opa @flourigh, só vi agora. Acho que a resposta do fernandosavio esclarece suas dúvidas. No fundo você precisa de lugares separados para tratar os cálculos em si e as entradas/saídas formatadas com vírgula.
Answer: Como o bfavaretto já mencionou você pode trocar a vírgula por ponto para o JS fazer a conversão automática para Number quando for feita a subtração.
Mas você poderia ter uma função para converter esta string para Float e outra função para formatar o Float para String. Depois é só usar estar funções para trabalhar com seus dados. Aí como você aplica no seu código você escolhe!
No código abaixo coloquei exemplos com Filters, Computed Properties e Methods.

let toFloat = str => parseFloat(str.replace(',', '.'));
let toStr = float => ("" + float).replace('.', ',');

const app = new Vue({
  el: '#app',
  data: {
    valor: "2,5",
  },
  filters: {
    sub2(value) {
      let number = toFloat(value) - 2;
      return toStr(number);
    },
  },
  computed: {
      valor_sub2() {
        let number = toFloat(this.valor) - 2;
        return toStr(number);
      },
  },
  methods: {
    method_sub2(value) {
      let number = toFloat(value) - 2;
      return toStr(number);
    }
  }
});

  <input v-model="valor">

Filter: {{ valor }} - 2 = {{ valor | sub2 }}

Computed: {{ valor }} - 2 = {{ valor_sub2 }}

Method: {{ valor }} - 2 = {{ method_sub2(valor) }}

Não entrei no mérito da internacionalização de números por não ser parte do seu problema, mas esta técnica de usar String.replace() só serve para inputs muito restritos. Se você quer que o usuário digite um número e o seu software reconheça é preciso trabalhar melhor o parsing destas strings. No meu exemplo seriam os métodos toFloat() e toStr(). (Dica de leitura: Intl.NumberFormat)
Comment: agradeço demais e irei estudar as referencias citadas, realmente estou precisando estudar estes method e coputed

Calculo valor com Virgula com Vue.JS


Find if there is a number in an array that appears more than n/8 times

Question: The question is:
Describe an algorithm that find in O(n) time if there is in an array of n numbers,a number that appears more than n/8 times.
Now I have the answer which is:
We'll do Select for the numbers in places: n/9,2*n/9,3*n/9,...,8*n/9 , and than check if one of those 8 candidates appears at least n/8 times.
But I don't understand why would this algorithm work.
For example,consider the following array:
[3,3,1,3,2,3,4,3,5,3,6,3,7,3,8,3,9,3].
So here n=18, and if for this algorithm the candidates would be 1,2,4,5,6,7,8,9 and when we'll check if these numbers appear at least n/8 times the answer will be no,but actually for 3 the answer would be yes.
So I don't understand why is this algorithm correct...
Comment: Only makes sense if the repeats are adjacent.
Comment: Could you help me find a correct algorithm?
Comment: This is a *homework question,* isn't it? Like you, I see no reason why the "answer" that you have would actually work, *unless,* perhaps, the vector was known to be **sorted.** I hope that you have a well-thumbed copy of Dr. Djikstra's *Sorting and Searching* on your nearby bookshelf ...
Comment: This is a question from an old exam,and that was the official answer for that question.
Answer: The key insight here is that Select, especially when capitalised, has a special meaning: it references the problem of finding the kth largest entry in an unsorted array. Perhaps somewhat surprisingly a priori, this can be done in linear time, for example using a median-of-5 pivoting strategy in combination with the QuickSelect algorithm. So if you Select-with-an-uppercase-S the n/9, 2n/9, ... entries (cost: 9*linear - which is linear), you definitely find any entries that occur n/8 times. Then iterate through your array again to count the number of occurrences of each of these candidates, and presto you're done.


How to display specific blocks for specific roles alone w.r.t domains and subdomains

Question: I want to display specific blocks for specific roles alone with respect to domains and sub-domains. I know i can give permission for roles in the block to be displayed.How do i differentiate anonymous users with respect to domain and sub-domains in the permission of roles. Help really appreciated.Thanks in advance:)
Answer: Hope this will help you,
In Drupal 7 you can use these modules

Domain Context - It allows administrators to set specific settings for each of their domains that are using the same code base.
Domain Blocks - Enables domain specific visibility settings for blocks.
And for specific roles for each block you can select the roles. Go to your specific BLOCK configuration and select the ROLE in BLOCK VISIBILITY SETTINGS


Como usar Jquery Custom Scrollbar em elementos com display:none

Question: Ele não monta a barra de scroll em elementos que estão com "display: none". Alguém sabe como resolver?
Aqui o plugin do scrollbar
Comment: Por acaso tem algum exemplo de código para nos mostrar que ficaria mais fácil para ajudar?
Comment: Será necessário um exemplo pra entendimento desta pergunta, em teoria se um elemento tem `display: none` o DOM não calcula dimensões e composição desse elemento, sem isso não é possível adicionar um scroll nele.
Answer: Coloca um handler pros seus elementos pra quando eles forem exibidos:
<code>$('.elemento').each(function() {
    if (!$(this).is(':visible')) {
        return;
    }
    $(this).mCustomScrollbar({
        scrollButtons: {
            enable: true
        }
    });
});
</code>
Answer: O elemento só pode ser utilizado pelo jQuery quando o elemento estiver comi display:block ou algo similar, Você poderia tentar aplicar a custom Scrollbar assim que o elemento for exibido.
Faça a pergunta assim mesmo: Qual a ação realizada para que você consiga aplicar o custom scrollbar? "é no evento click de algum elemento que está sendo exibido", logo chame a montagem da custom scrollbar no evento.


SPSS Data Management

Question: I am not an expert of SPSS and I would like to ask a question related to data management.
I need to identify the respondents that answered yes I used it to all of the following question:
I used a car,
I used a bike,
I used a van,
I used a scouter.
My aim is to identify people that used all of the above options.
Can someone help me in identifying the right process to execute?
Many thanks
Comment: Questions solely about how software works are
[off-topic](http://stats.stackexchange.com/help/on-topic) here. I don't think this question is clear enough to be suitable for migration to Stack Overflow. You may be interested in the key words "filter" and "crosstabs".
Comment: Thanks for your useful support. But, I am afraid that it doesn't help me.
Answer: Surely the best way to approach this is to read the base users guide that would have come with SPSS.  However, I would suggest using four separate fields that can be subsequently analysed independently or in combination.
Comment: Thanks for your answer. I already computed the variables. My problem is to create a crosstabs where it shows the percentage of people that contemporarily used: CAR, VAN, Bike and scouter. PS: I would not have asked any question If had found my answer in the base users guide.  Thanks
Comment: Sorry about the delay, I have only just found the messages area.  If your separate variables were coded as 0 and 1 for no and yes respectively, then you could add them to produce another variable, where an answer of 4 would give you what you wanted,  Another way could be with a compound IF statement.

SPSS Data Management


How to find the basis of the kernel of this linear transformation?

Question: Say given the function:
$$ T: \mathbb R_{2}[t] \rightarrow \mathbb R_{1}[t]$$
$$ at^{2} + bt + c \rightarrow at + 2c - b $$
We were tasked to find the basis for the kernel of $T$ and $T(\mathbb R_2[t])$.
Where do I start? Could somebody point me in the right direction? I was told to do these steps:

But I don't even understand the first part. Could somebody explain how the matrix A is generated from writing the polynomials as column vectors? What is the map of T?
Answer: Let's see. You have to understand that $\mathbb{R}_2[t]$ is a vector space. A basis you could choose is $\{t^2, t, 1\}$ (it is easy to check that really it is). Analogously for $\mathbb{R}_1[t]$, a basis is  $\{t, 1\}$.
Now, in order to obtain the matrix of the transformation $T$, you only have to check that the first vector of the first basis ($t^2=1\cdot t^2+0t+0$) get transformed to $1.t+0$, so the first column of the matrix will be $(1,0)$ (as a column!). And so on for the others two element of the basis to create the other columns.
Comment: About the map of $T$, I am not sure what do you mean... Could you be more specific? And respect to the image of $T$, yo know it is generated by $T(t^2)$, $T(t)$ and $T(1)$. So you must write them down and throw out that dependent vector (or vectors), then you will have a basis for $T(R_2[t])$.
Comment: Well, you have three vectors and you know that the dimension of $T(R_2(t))$ is, at most, 2 (because it is a subspace of $R_1(t)$). So at least one of the three vectors must be leaved out. You have the image is generated by $\{t,-1, 2\}$, and is easy to see that -1 and 2 are linearly dependent vectors (so you can remove the "2", for example) and $t$ and $-1$ are independent, so they remain with us. So $T(R_2(t))$ is the whole $R_1(t)$ (and therefore the kernel must be the vector space 0)
Comment: Woah, thanks for this! I understand it now. I have an additional question. What exactly is the map of T? And what does it imply in this problem? And how is it related to the image of T?
Comment: What does throwing out the 'dependent vector' mean? And what are these dependent vectors? I apologize for the many questions and thanks!
Answer: The suggestion just notes that the term $at^2+bt+c $ can be identified with the triple $(a,b,c)$ (that is, the term has the coordinates $(c,b,a)$ with the basis $1,t,t^2$).
I think is is easier to compute directly.
Note that $at^2+bt+c = 0$ iff $a=b=c=0$.
We have
\begin{eqnarray}
\ker T &=& \{ at^2+bt+c | T(at^2+bt+c) = 0 \} \\
&=& \{ at^2+bt+c | at+2c-b = 0 \} \\
&=& \{ at^2+bt+c | a = 0, b=2c \} \\
&=&  \{ 2 ct +c | c \in \mathbb{R} \} \\
&=& \{ c (2t+1) | c \in \mathbb{R} \}
\end{eqnarray}
From this we see that $2t+1$ is a basis for $\ker T$.
The image is computed similarly.
\begin{eqnarray}
{\cal R} T &=& \{ T(at^2+bt+c) | at^2+bt+c \in \mathbb{R}_2[t]\} \\
&=& \{ at+2c-b | at^2+bt+c \in \mathbb{R}_2[t]\} \\
&=& \{ at+2c-b | a,b,c \in \mathbb{R}\} \\
&=& \{ at+d | a,d \in \mathbb{R}\} \\
\end{eqnarray}
And so we see that $t, 1$ form a basis for ${\cal R}T$.
Comment: The range consists of all terms of the form $at+d = a(t)+d(1)$ where $a,d$ are any real numbers. So the terms $1,t$ are sufficient to represent every element of the range and they are linearly independent, hence they form a basis for the range.
Comment: Where did 't,1' came from?


Completion of a Field at a Prime Ideal

Question: Suppose $K$ is a number field and $P$ is some prime ideal of $K,$ i.e. a prime ideal of the ring of integers in $K, \mathcal{O}_K.$
I encountered a term "completion of $K$ at $P$", but I am unsure of what that would mean. I am familiar with completions with respect to a norm, is this something similar?
Comment: A prime $P$ determines a norm on $K$, simply by taking some $0<\epsilon<1$ and defining $|x|=\epsilon^{-v_P(x)}$ where $v_P$ is the valuation of the element with respect to the prime $P$. Now just complete with respect to this norm (try doing this with $p\in\mathbb{Z}$).
Comment: So for an integer $x\in\mathcal{O}_K$, you could define $v_P(x)$ to be the greatest integer $n$ such that $x\in P^n$, so in the rational integers, this just corresponds to the power of $p$ in the prime factorisation of $x$ (in fact if you go away and read about Dedekind domains, you can remove the 'rational' from my previous statement and it still makes sense!). Then for an arbitrary non-zero element of the field, you can write it as a quotient of integers, and take the difference of their valuations.
Comment: So to be explicit in the rationals if you have a prime $p$ and a fraction $x=\frac{a}{b}$, then we can write it uniquely as $x=p^{k}\frac{m}{n}$ where $m,n$ are coprime to $p$. Then $v_p(x)=k$.
Comment: @GeorgeR Thank you! Could you maybe also clarify what $v_P(x)$ would be, since $P$ is an ideal, and $x$ is an element of $K?$
Answer: The completion with respect to P can be defined as "Cauchy sequences in K modulo null sequences"  Both the "Cauchy" and the "null" can be defined either in terms of making $|x_n - x_m|_P$ or $|x_n-y_n|_P$  small or in terms of making $\nu _P(x_n-x_m)$ or $\nu _P(x_n-y_n)$ large. In some contexts it is easier or more natural to work with norms; in other contexts it is easier or more natural to work with valuations. As well as number fields, you can apply these ideas to function fields, where you start with a discrete valuation ring. Note that, for number fields, the $\epsilon$ of George R's comment used to go from a valuation to a norm can in general be chosen arbitrarily between 0 and 1 but if you want certain additional formulae to work, such as Artin's product formula for norms, then $\epsilon$ must be defined in terms of numbers associated with certain field extensions.

Completion of a Field at a Prime Ideal


Use another field value as condition in Entity Query

Question: I'm performing in Drupal 8 an entity query that searches for nodes that have not been changed since x days, where x is a numeric node field (node.field_days).
So I would like to perform a query like:
$query = \Drupal::entityQuery("node")
  ->condition('changed', strtotime('-node.field_days days'), '<=');

I know that condition takes as value a string and not a db column, but is it possible to use entity query with a dynamic value?
Answer: The entity query is a powerful and convenient tool to query for content and config entities that have certain properties/field values/field references.
Yet, it has its limitations. Comparing two fields is not possible using the generic entity query and its condition method.
For such a task, you may need to use the more low level dynamic (select) queries and its where method. An example for your use case:
$connection = \Drupal::database();
// Query node base field table.
$query = $connection->select('node_field_data', 'n');
// Join with the `field_days` field table.
$query->leftjoin('node__field_days', 'd', 'd.entity_id = n.nid');
// Query for the node ID.
$query->fields('n', ['nid']);
// Your condition (a day has 86400 seconds; we multiply them with
// the value of the field_days field, add them to the changed
// timestamp of the node and compare it against the current time).
$query->where('n.changed + (d.field_days_value * 86400) <= :now', [
  ':now' => \Drupal::time()->getCurrentTime(),
]);
// Optional sorting.
$query->orderBy('n.changed', 'DESC');
// Fetch results.
$result = $query->execute()->fetchAllKeyed(0, 0);

Above example assumes:

that you used a numeric field type for field_days, so its database stored value can be multiplied with seconds without any casting,
that the field_days field allows one value only, so we can safely ignore field deltas when joining,
that field_days is present on all nodes/bundles and has a valid value,
that you use one language only in your site/the field_days value is not translatable, so we can also ignore langcodes.

You may have to alter the query accordingly, if any of these assumptions is not true.
Comment: Why do you think this isn't supported by EntityQuery? Is it because it would be ambiguous weather the second argument of the condition referred to a string literal or the a field name?


How to calculate runtime complexity of the nested loops with variable length

Question: Suppose I have a task to write an algorithm that runs through an array of strings and checks if each value in the array contains s character. The algorithm will have two nested loops, here is the pseudo code:
for (let i=0; i < a.length; i++)
  for (let j=0; j < a[i].length; j++)
      if (a[i][j] === 'c')
         do something

Now, the task is to identify the runtime complexity of the algorithm. Here is my reasoning:
let the number of elements in the array be n, while the maximum length of string values m. So the general formula for complexity is
n x m

Now the possible cases.
If the maximum length of string values is equal to the number of elements, I get the complexity:
n^2

If the maximum length of elements is less than the number of elements by some number a, the complexity is
n x (n - a) = n^2 - na

If the maximum length of elements is more than the number of elements by some number a, the complexity is
n x (n - a) = n^2 + na

Since we discard lower growth functions, it seems that the complexity of the algorithm is n^2. Is my reasoning correct?
Answer: Your time complexity is just the total number of characters. Which of the analyses is applicable, depends entirely on which of your assumptions about the relationship between the length of words, and the number of words, holds true. Note in particular, your statement that the time complexity is N x M where M is the largest name in the array, is not correct (it's correct in the sense that it places an upper bound, but that upper bound is not tight, so it's not very interesting; it's correct in the same sense that N^2 x M^2 is correct).
I think certainly in many real cases of interest, your analysis is incorrect. The total number of characters is equal to the number of strings, times the average number of characters per string, i.e. word length (note: average, not maximum!). As the number of strings becomes large, the average sample word length will approach the mean of whatever distribution you are sampling from. So at least for any well behaved distribution where the sampling is iid, the time complexity is simply N.
A good practical example is a database that stores names. It depends of course which people happen to be in the database, but if you are storing names of say American citizens, then as N becomes large, the number of inner operations will approach N times the average number of characters in a name, in the US. The latter quantity just doesn't depend on N at all, so it's linear in N.
Comment: @Maximus A function `0.5x` on `x  >= 1` is bounded above by `x`, `x^2`, `x^3` etc. There's an infinite number of upper bounds, because something bigger than upper bound is still an upper bound. In this case, N x avg word length, multiplied by a suitable constant, is a better (tighter) upper bound than N x max word length.
Comment: thanks, what do you mean by **tight** - _it's correct in the sense that it places an upper bound, but that upper bound is not tight_?
Comment: @Maximus The upper bounds relationship with what actual is can be very loose if all the strings are short and only one is long. It's not a tight relationship. Curious if I got it right, but I think so (not tight means loose).
Comment: @NirFriedman, okay, I understand now that I probably have chosen inappropriate example. Suppose I'm trying to find which elements from array A are not present in array B. Should the logic be different here? This should be `n^2`, not `n`?
Comment: @Maximus Assuming that A and B are both of length N, then yes a brute force solution would be a simple double for loop of N^2. But the for loop in this case is a fixed size so I'm not sure if that's what you are thinking of (of course there is a better solution that's NlogN).


ambiguous overload for 'operator =' in 'authlog = myfile'

Question: I'm trying to make a game that can save your progress.
I already did this and it worked but now it doesn't work anymore.
Error:

43: Ambiguous overload for 'operator=' in 'authlog = myfile'
      note: candidates are: std::basic_string<_CharT,_Traits,_Alloc>& std::basic_string<_CharT,Traits,..........etc

The code that is causing the error:
if ( myfile.is_open() )
    {
         while ( getline ( myfile,line ) )
         {
             cout << "You already have a save file!\n";
         }
         myfile.close();
         myfile.clear();
         authlog = myfile;
         myfile.open("username.txt");
         cout << "Enter your username:\n";
         cin >> auth;
         if( auth == authlog )
         {

         }
    }

Comment: What is the type of `authlog`?
Comment: this is not the code causing error...please submit authlog code..
Comment: Authlog is a string but not shown here.
Answer: In my experience, that error can be solved by casting one operand as the other - in other words, it looks like authlog may not be the same type as myfile.
edit: In this case, you are also clearing the file, so maybe you would rather do authlog = "";
In any case, you cannot treat a file as a string.  You can save strings to it or get strings out of it, but it is not a string.
Comment: Thanks but im trying to identify if string auth is equal to string authlog. Even if i do 'if( auth == myfile ) it still won't work.
Comment: Right - that is because myfile is not a string.
Answer: Thanks to every one that answered.
The problem is that i forgot to put
while ( getline ( myfile,auth ) )

in the code.


cannot visit minio server dashboard from ubuntu

Question: i am working on nginx and minio on the ubuntu.
the minio server is started from
'nohup /usr/local/bin/minio server /data/tenant1 --address :9001   >  /opt/logs/minio.log 2>&1 &#',
and it is working.
then I started the nginx and configure the nginx server with the following configuration.
nano /etc/nginx/sites-available/default
server {
        listen 9000;
        location / {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header   Host      $http_host;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_pass         http://127.0.0.1:9001;
        }
}
sudo systemctl restart nginx

from the opening ports, it is clear to see the minio is running on port 9001
minio      9349            root   12u  IPv6 35833021      0t0  TCP *:9001 (LISTEN)
nginx     12416        www-data    8u  IPv4 36153228      0t0  TCP *:9000 (LISTEN)

At last, the gateway is inactive from the output of ufw status. and my server security group also allows 9000.

however when I tried to visit the minio server dashboard from   http://IP:9000/minio   , it is not working,
any problem with my configuration?
Answer: The MinIO console dashboard listens on a separate port - you need to specify this with the option --console-address :10000 - if you do not specify this, a random port is chosen for you and it will be displayed in MinIO's logs in your /opt/log/minio.log file. The 9001 port in your setup is for the S3 storage API only.


Fixed plot height in scatter chart

Question: I have been searching this but not able to get any solutions for this. I want my scatter chart to be of fixed height regardless of no of legends used.
Please look into below fiddle link:
http://jsfiddle.net/3o982ewu/118/
<code>"chart": {
    "type": "scatter",
    "zoomType": "xy",
    "plotBorderWidth": 2,
    "width": 400,
    "height":400,
.....
</code>
I have set chart height to be 400. If no of legends increase, then scatter chart height gets adjusted (decrease) accordingly. You can try increasing the legends and notice that chart height gets decreased. I have tried other options like setting margin top and bottom (suggested in one post) but no luck.
I see that in highcharts js, there is <code>'plotHeight'</code> variable which is used to set the chart height but I find no means to set it from my code or provide into as chart options. This scatter chart will be displayed in pdf so there is no scope of adding pagination, scrolls or any other stuff which is feasible only in web browser but not in pdf.
Comment: So what do you expect to happen when the legend is too large for the space available? You seem to be asking to allow a legend of any size to fit into a fixed space, which is not plausible. You can play with the legend item style, margin, distance, etc, but you're still going to hit a problem at some point if the number of legend items can reach any limit. If you are talking about a set chart, and not a dynamic one, then provide the actual example that will be used. If it's going to be dynamic, you have to make some decisions.
Comment: Hm. You might be able to capture the size of the legend box in the chart's load event, and expand your chart container size accordingly. Or, if you don't care how tall the total chart is, just make it bigger than it will need to be, and let the legend fill the space as needed.
Comment: Using marginBottom, you should be able to achieve this. Here I have set `marginBottom: 100`: http://jsfiddle.net/ewolden/3o982ewu/147/. Is this the solution you want? If not, what should be different?
Comment: @ewolden With this marginBottom solution, legends are overlapping the scatter chart. I don't want that
Comment: You can also set the `maxHeight` property on the legend. The legend will be paginated if it exceeds the available space. Example: http://jsfiddle.net/3o982ewu/158/
Comment: This topic can be useful: https://stackoverflow.com/questions/33956950/how-to-set-plot-area-width-and-height-in-highcharts
Comment: @jlbriggs I don't want the legends to be paginated either. This scatter chart is shown inside a pdf. So there is no scope of adding pagination, scroll bars. Edited the question.
Comment: @jlbriggs Legends could be of any size. I just want my chart plot size to be fixed. (the square box of the chart). Whole chart area image (incl legends) could be of any size.
Comment: @jlbriggs Added the solution we did as an answer.
Answer: I am answering my own question because I found a way to deal with this scenario.
We hid the legends on the chart, so this way plot height of the chart will be always fixed. (plotHeight will be equal to the height of the chart which we provide in the chart settings considering we don't supply any margins)
We stored the data points (color of the legend and legend name) in the array and printed those outside the chart to make them appear as legends.

Fixed plot height in scatter chart


drush status only showing drush info, not drupal info

Question: I have drush installed globally on my VPS (thanks to a previously answered question on here :D), logging in as root all works fine, but using a different user (let's call it drushuser) if I run:
drush @mysite st

I just get the drush version etc, not the drupal info.
I assume this is down to the 'root' path in my alias:
'root' => '/home/accountname/public_html',

so logged in as root on the VPS that works - but what should I change it to for drushuser? I'm guessing drush is currently looking in /home/drushuser/home/accountname/public_html and not finding drupal (since it doesn't exist there) so just giving the drush info instead?
I've tried '../accountname/public_html' which didn't work.
Answer: If the drushuser account doesn't have read permission to the directory, it won't be able to run and bootstrap Drupal to get information, so it falls back to displaying the status it can which is Drush status.
If drushuser isn't the same as accountname above, it's very unlikely that drushuser will have access to the home directory of accountname. The root user can read files in every directory, so that is probably why it works as root.
You should be able to run drush as accountname or if you can put the public_html files into a shared location and make sure that the permissions are set so that both users share a group that has read access.
Comment: Thanks eporama, OK will do it logging in as each account - I was trying to use a single user for all rather than upload a public key for each account, but it's not a major job so I'll go ahead with that


Java IDE says { expected on the first line starting with public class (program name) despite me already having it

Question: Here's my code:
public class methodAssignment {

  public static void main(String[] args) {
        KeyboardReader reader= new KeyboardReader();
        int num1=reader.readInt("Enter the length of the rectangle: ");
        int num2=reader.readInt("Enter the width of the rectangle: ");

        int perimeter=rectPerimeter(num1, num2);

        System.out.print("\nThe perimeter of the rectangle is "+perimeter+".");
    }

    public static int rectPerimeter(int length, int width)
    {
        return 2*length+2*width;
    }
}

I've tried adding another { to the end of the line, but that just causes more errors as you'd expect. What am I missing?
Comment: 1) There doesn't appear to be anything wrong with the braces in the code you've shown us.  2) Q: Did you show us your *COMPLETE* code???  3) Q: What about "KeyboardReader"?
Comment: @paulsm4 2) Believe me, this is the whole thing, and I have no other errors.
Comment: I believe you - it's just perplexing.  Please update your question: 1) copy/paste the exact error message, 2) specify what Java compiler and/or IDE you're using, and 3) tell us about "KeyboardReader". The fact that your code references it - without any corresponding "import" stateument, is the *ONLY* thing I see in your entire code snippet that could possibly cause a compile error.
Comment: Another suggestion: you could do worse than starting from scratch: typing just your classname (I'd use [CamelCase](https://www.geeksforgeeks.org/java-naming-conventions) `MethodAssignment`) and an empty `static void main (String[] args) {}` into a new, clean file and see if that compiles. Please do let us know what happens
Answer: You are missing absolutely nothing. That code you pasted in this question? Toss it in a text file, call that file methodAssignment.java, and tell javac to compile it, and it'll work fine. You're evidently either not compiling the file you pasted but some other file with syntax errors, or you aren't invoking javac, but invoking shmavac, the java-esque bad sheep of the family. Go for the real deal :)
Comment: I agree: the OP is "missing absolutely nothing".  But ... 1) I've never heard of "shmavac", and 2) my compile fails with "error: cannot find symbol KeyboardReader".  Q: What's shmavac?  Q: Did your "methodAssignment.java" actually compile without any errors?
Comment: shmavac is a jokey way to say: Your javac is corrupted. The error OP is getting is clearly not 'KeyboardReader isn't there'. It's rather obvious that this isn't OP's problem; they have KeyboardReader.java/KeyboardReader.class in the right place. It actually compiled without errors once I created a dummy KeyboardReader. Why are you aggressively questioning this answer?
Comment: Nothing is "obvious" until clearly stated one way or the other.  As an aside - that's precisely the main reason I tend to avoid Lombok like the plague.  I prefer the code to always explicitly state what's happening - I hate "implicit magic" :(
Comment: @paulsm4 Java is not a good language if you hate implicit magic. The sheer amount of implicit magic the VM is doing to your code as it hotspots is orders of magnitude beyond what javac does, which is already impressive (lombok is minor leagues in comparison).


Making A Website With Profiles

Question: I am working on a social network, and I am doing it with php and mysql, I need to know how to make users have customizable profiles...
Like editing status, ect...
Also making it so only friends can veiw their profile..
Also how do I add a user's page/directory to the website directory(example: domainname.com/someonesprofile)
Thank You
-Techy
Comment: This is probably too broad of a question, what you are asking for is for someone to tell you how to design your application and without some very detailed, specific requirements, you probably won't get something of real value.
Comment: I think Techy will benefit for having posted the question.
Comment: He'll also learn from this project. You have to make errors in order to learn. How many "kick ass websites" did I make before I were able to make something good ? xD
Answer: That's a pretty generic question, but I'll give it a whirl.
First of all, you need to determine what a profile should contain and so forth, such as status, relationships, name, addresses, .... The list goes on. You then need to write an interface to a service that provides this information; this can be a PHP function, a class, whatever, really.
Second, you need to access this interface from within your web application. A suitable course of action is probably to have a function that assures that whoever is trying to access the information is logged in, is in the relevant authorization group (friends list), and so on.
The editing part is done quite simply through an HTML form or similar; there's no magick[sic] involved. The function to parse this form would again assure that the logged in user has the appropriate rights to edit the profile (e.g. is the same user or a trustee of some kind, parent, lover, who knows...)
As for the last bit; here mod_rewrite is your friend. You probably would want to have URLs along the line of http://example.org/profile/username , which the server would translate to /?action=profile&user=username, or something to that effect.
The file /profile/username would as such not exist on the server file system in any real sense, but seem to be a completely normal HTML file when viewed from the outside.
Comment: -1  -- no reference to data storage, which is the Heavy Golden Key here.
Comment: so ..after coding all these php ..what i wanna really do ??..I think i just need to upload that php and html file to server ??..is that right methos ?
Answer: You must start with the database.  You will need a table for Person, obviously.  You will need a table that joins Person to Person many-to-many, for viewing privileges.  You will need a table for levels of authorization.  And you will need other tables that serve up what privileges go where.
The interface is secondary.  Some developers would use something simpler than PHP to develop the UI functions that rely on these database resources.
Comment: Oh man ... if you can take the advice of mdorseif and get a working framework, do it.  I'd rather not built the above myself, certainly.
Answer: I know that there are very nice frameworks available which handle the whole profile/login/friends functionality. Pinax for Django springs to mind. Ime quite sure similar things are available in PHP but unfortunatiely I know very little about the PHP community, so I don't have a link.

Making A Website With Profiles


Refresh button after changing style color

Question: So, I have a button template in a resource dictionary. Its colour property in its normal VisualState binds to a DependencyProperty defined in the MainPage C# code. Notice that MainControl is the MainPage name.
Here's the Button template:

Here's the MainPage XAML:
<Page
x:Class="Volumio.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Volumio"
Name="MainControl">
<Grid Background="#FF525C66">
    <Button x:Name="toggle" Content="" HorizontalAlignment="Left" Height="132" Margin="40,146,0,0" VerticalAlignment="Top" Width="132" Style="{StaticResource MyButtonStyle}">
</Grid>

And here is where I define the Property:
public static DependencyProperty ColorProperty = DependencyProperty.Register("ButtonColor", typeof(SolidColorBrush),
        typeof(Page), PropertyMetadata.Create(NormalColor));

    public SolidColorBrush ButtonColor
    {
        get { return (SolidColorBrush)GetValue(ColorProperty); }
        set { SetValue(ColorProperty, value); }
    }

The problem is: whenever I set the ButtonColour property to a different colour, the Button doesn't change its colour automatically, instead I have to change VisualState and then return to normal to make it refresh and change colour. I change the property in async voids. Does this matter?
Where is the problem? Do I have to refresh it manually from the code?
It may be obvious but I'm new to XAML programming. Thanks in advance.
Answer: Setters under a VisualState will only applied once when a VisualState is used as the current state. And when a Setter is applied, it obtains the value from its Value property and set to the target element and property specified in its Target property.
So it won't set your Binding to the Fill property of your ellipse and you button won't change its color unless the button's VisualState become Normal again.
If you want your button change color automatically, you can remove the <Setter Target="ellipse.(Shape.Fill)" Value="{Binding ElementName=MainControl, Path=ButtonColor}"></Setter> in VisualState.Setters and use the Binding in Ellipse like:
<Ellipse x:Name="ellipse" Fill="{Binding ElementName=MainControl, Path=ButtonColor}" />

Or to reuse this Style, we can bind Fill property to Button's Background property like this:
<Ellipse x:Name="ellipse" Fill="{TemplateBinding Background}" />

and in MainPage XAML using:
 <Button x:Name="toggle"
    Width="132"
    Height="132"
    Margin="40,146,0,0"
    HorizontalAlignment="Left"
    VerticalAlignment="Top"
    Background="{Binding ElementName=MainControl,
                         Path=ButtonColor}"
    Style="{StaticResource MyButtonStyle}" />

Comment: Yes Jay Zuo, it worked perfectly. I removed the VisualStates as I'm going to control them through C#. Thanks a lot :-)


How to choose between z and t in 2 sample (non-paired) tests?

Question: I understand that in the one sample case, z is employed where population variance is known and t for where it is unknown.
In the two sample case: we are trying to test $H_0: \mu_x=\mu_y$ against $H_1: \mu_x\not= \mu_y$, for finite variance; $\sigma^2_x$ and $\sigma^2_y$; while $n_x$ and $n_y$ are respective sample sizes
What test would we use if:

(both variance are equal) AND either

(i) both population variance unknown (i.e. we use sample variance $S_x=S_y$)
(ii) both population variance known ($\sigma^2_x=\sigma^2_y$ )

(variance not equal) AND either

(i) both population variance unknown (i.e. we use sample variance, $S^2_x\not=S^2_y$)
(ii) both population variance known ($\sigma^2_x \not=\sigma^2_y$ )
(iii) one population variance known other unknown (i.e. given $\sigma^2_x$ and $ S^2_y$)

My answers:
1. (i) use 2 sample t-test with $n_x+n_y-2$ degrees of freedom and variance: $S_p*\frac{n_x+n_y}{n_xn_y}$  (where $S_p$ is the pooled variance )
1. (ii) use 2 sample z-test with variance: $(\frac{\sigma^2_x}{n_x}+\frac{\sigma^2_y}{n_y})$
2. (i) no idea :(
2. (ii) same as 1. (ii)
2. (iii) no idea :(
Answer: In the unequal variance case with both variance unknown (normal distributions assumed throughout) Welch's test is used.  This is called the Behrens-Fisher problem.  The test statistic under the null hypothesis has an approximate t distribution with degrees's of freedom given by a formula where the df does not have to be integer. It is called the Satterthwaite approximation. In the case where both population variances are known you can normalize by the formula for the variance of the difference of two sample means and the use the z test.
I have never seen the case where one variance is known and the other is not.  You could be conservative and use Welch's test but it may be better to find the exact null distribution when one variance is estimated and the other is a known constant.
Comment: Thank you @chl for enhancing my answer with two well-chosen links.


Proving that if $x\notin\overline{S}$, then $d(x,S)>0$

Question: I have the problem:
Let $S \subset \mathbb{R}$ be any set, and define for any $x\in\mathbb{R}$ the distance between $x$ and the set $S$ by:
$$d(x,S) = \inf\{|x-s| : x \in S\}$$
I'm to prove ($\overline{S}$ being the closure of $S$):

If $x\notin \overline{S}$, then $d(x,S) > 0$.

I can understand this from a common sense way but not sure how to prove it.
Comment: "Proving topology questions" is a completely uninformative title.
Comment: You may want to check the various characterisations of $\overline S$. Is there one about balls intersecting $S$?
Comment: Closely related: http://math.stackexchange.com/questions/385127/in-a-metric-x-d-prove-that-for-each-subset-a-x-in-bara-if-and-only-i
Comment: Sorry didn't know titles could have symbols as well.  Noted for future reference. Thanks for the edits.
Comment: @MathematicianInWorks Even if you want to avoid symbols, saying something like "A point outside the closure has positive distance" would describe the question much better. In general, it is advised to write descriptive titles, see also [meta](http://meta.math.stackexchange.com/questions/9959/how-to-ask-a-good-question/10144#10144).
Answer: If $x\notin \overline{S}$ then there is a number $r>0$ such that the open interval $(x-r,x+r)$ doesn't intersect $S$. So any point of $S$ is at distance $\geq r>0$ of $x$, hence $d(x,S)\geq r>0$.
Other idea: (with sequences)
By contrapositive, if $d(x,S)=0$ then by definition of "inf" as greatest lower bound, we see that $\forall n\in \Bbb N,\;n\geq 1,\;\dfrac 1n$ is not a lower bound of $\{ |x-s| : s\in S\}$, so there is $s_n\in S$ s.t. $|x-s_n|<\dfrac 1n$. Thus there is a sequence $(s_n)$ of elements of $S$ converging to $x$ and $x\in\overline{S}$.


Do I *really* need to reserve a LAN adapter for Hyper-V remote access?

Question: I recently installed the Hyper-V role on a Windows Server 2008 R2 system. As I installed and configured the role, it asked me which Network Adapters I would allow it to use, and I had to check the one-and-only box, because only one adapter is installed.
The setup process recommended I reserve a network adapter for remote access. I was under the impression that this was because it would use the adapters exclusively for the VMs and I would not be able to Remote Desktop in at all!
Well it turns out my virtual machines run great and I can remote into the Hyper-V host no problem. So were they just being conservative, and suggesting I don't waste bandwidth (that the VMs could be using) by having Hyper-V support a Remote Desktop session? At least the adapter I have installed is gigabit.
I do have a dual port Intel Gigabit Lan adapter I could steal from an unused server and swap in. But my "enterprise" is only hobby-sized (40 anonymous web visits per day, VMs generally used only for email, customer testing of web apps, and development). So I don't think it would matter. And is replacing a network card in a Hyper-V host a pain?
What do you think? Is it a big deal not to reserve a network adapter as Hyper-V recommends?
Answer: For that load, probably not a problem.  On a system with many guests maxed out on capacity where contention is an issue, this is almost certainly not a "best practice".
I reckon MS does not consider the requirement for a dedicated adapter significant because most system boards come with dual adapters.  And network adapter cards are inexpensive.  (Available slots are more expensive than network adapters).
The real issue is you are off the reservation with this setup.  If there were some weird problem with no documented solution, MS support would probably recommend that you install a dedicated adapter.  If you have a spare slot, I would not have too much anxiety.  Reconfiguring the network is not that involved.
It could be worse.  Try getting it to work with a wireless adapter.  Not supported (not sure about R2 but in 2008 it is not).  I made it work anyway.  The interesting thing is the final solution was trivial, but there are a lot of planet crackpot articles on how to make it work.


Does Edge Picking Break Strings Faster?

Question: I started learning to play acoustic guitar several months ago, and have been mainly using Fender medium picks. I have noticed that the picks very quickly develop a sort of bevel on one side because I apparently strum with the pick at an angle to the strings instead of perfectly level.
After searching this problem, I found that this is actually a technique and helps some people pick faster because there is less friction, and it is called edge picking, I think anyway.
However, my question is, does edge picking cause strings to break more quickly?
I am playing an acoustic with standard Fender 12 - 52 non coated strings and my high e string has broken twice now within the space of less than three months. Both times it was at the bridge so it could possibly be the bridge itself (I have never gotten the guitar setup), but I am wondering if "sharpening" my pick by playing the way I do might be causing me to break strings.
Answer: No
The material of the picks is much softer than the strings. That's why the pick wears away, because the string is harder.
If you were tuning at the time the strings broke, then it might be improper tuning that caused it.
If you were playing then it's less clear. You could be playing too hard or digging in too much.
I'm assuming your bridge and saddle are wood and plastic, so it's unlikely those are causing the string to break.
Comment: Thank you. Okay yes, I was playing when it broke both times, and the saddle is plastic. It may be the way I was holding the pick, causing me to use more force than necessary, I do grip it pretty tight.
Comment: @NULL Your tone and comfort will improve if you relax your grip and try to just brush the strings with the pick. It takes practice. If you are strumming and you sometimes miss the strings, then you are in the right zone of being close without being too close.
Comment: Those benefits plus breaking less strings...sounds like a win-win. I will definitely incorporate that into my practice schedule for a month or so and hopefully I can correct it. Thanks for the advice

Does Edge Picking Break Strings Faster?


Is restart required after changing operating system configuration and tuning

Question: I have a cassandra cluster where I recently added two new nodes . Looking at the stats I observed that disk I/O in these newly added machines is way higher than the already present machines .
On checking I found that the read_ahead_kb OS configuration on these machines is 4096 whereas other machines it is 4 .
I changed the value but the disk I/O is still same . Do we need to restart the machines for these OS configuration changes to take effect ?
Also if there is any other setting I need to look at .
Answer: It depends how you set the readahead value. The following command will set the readahead for /dev/sda to 4kb, and will take effect immediately (no reboot necessary):
sudo blockdev --setra 4 /dev/sda
I recommend configuring a udev rule (as described here), as otherwise the change will be lost after a reboot.
Read ahead is one of the most important performance tweaks regarding disk I/O & throughput. Some other things that are important for read performance:

ensure you have plenty of free RAM for the OS page cache
disable swap
use SSDs over spinning disks, especially if you have a read-heavy workload

This guide is a few years old, but many of the OS tuning & hardware recommendations still apply to Cassandra 3.x:
https://tobert.github.io/pages/als-cassandra-21-tuning-guide.html


SQL - Counting Rows Per Value

Question: I have a table of Accounts, each with a unique ID. Then I have a table of Transactions, each with a unique ID. Each row of the Transactions table has an Account ID, to show which particular Account it goes with. So there can be multiple rows in the Transactions table with the same Account ID, each pointing to the same Account, to indicate that the Account had multiple transactions.
Each Account can have any number (0-n) transactions.
I'm joining the Transactions table to the Account table fine, with the output showing a row for each Transaction (so there are multiple rows for some Account numbers) or, if there are no Transactions, showing null in the transaction fields:
|Account ID|Account Name|Transaction ID|Transaction Name|
---------------------------------------------------------
|acc1      |Account 1   |tran1         |Transaction 1   |
|acc1      |Account 1   |tran2         |Transaction 2   |
|acc1      |Account 1   |tran3         |Transaction 3   |
|acc2      |Account 2   |tran4         |Transaction 4   |
|acc3      |Account 3   |null          |null            |
|acc4      |Account 4   |tran5         |Transaction 5   |
|acc4      |Account 4   |tran6         |Transaction 6   |

But what I want is to get a count for the number of transactions - I don't care about any information related to each transaction; I just want to get a count of the number of transactions for each account:
|Account ID|Account Name|Number of Transactions|
------------------------------------------------
|acc1      |Account 1   |           3          |
|acc2      |Account 2   |           1          |
|acc3      |Account 3   |           0          |
|acc4      |Account 4   |           2          |

How can I get this count?
FWIW - Microsoft SQL Server
Comment: Possible duplicate of [How does GROUP BY work?](https://stackoverflow.com/questions/7434657/how-does-group-by-work)
Answer: DECLARE @Account TABLE(AccountID INT, AccountName NVARCHAR(50))
DECLARE @Transaction TABLE(AccountID INT, TransactionID INT)
INSERT INTO @Account
VALUES(1,'Acount 1'),
(2,'Acount 2'),
(3,'Acount 3')

INSERT INTO @Transaction
VALUES(1, 1),
(1, 2),
(1, 3),
(2, 4),
(2, 5)

SELECT a.AccountID, a.AccountName, Count(t.TransactionID) AS 'Number Of Transactions' FROM @Account a
LEFT JOIN @Transaction t ON a.AccountID = t.AccountID
Group By a.AccountID, a.AccountName

Answer: Assuming your table structure is this
create table tran (accid varchar, accname varchar, tranid varchar, tranname varchar)

you can simply achieve this using group by clause
select accid,accname, count(tranid) from tran group by accid

Comment: `COUNT([Transaction ID])` "ignores" NULLs and so will return the zero correctly.  No need for two queries.

SQL - Counting Rows Per Value


Custom form, input with ajax autocomplete not working

Question: I have developed a module with a custom form but I don't know why ajax autocomplete doesn't work. The form works good, but in one of the input field I'd like to have a autocomplete function. The next is part of my code:
src\Form\Mycustomform.php
...
public function buildForm(array $form, FormStateInterface $form_state, $parameter = NULL) {
...
    $form['customer'] = array(
      '#type' => 'textfield',
      '#title' => t('Customer'),
      '#id' => 'inpCustomer',
      '#autocomplete_route_name' => 'mymodule.autocomplete',
    );
....

mymodule.routing.yml
mymodule:
  path: 'mycustompath'
  defaults:
    _form: '\Drupal\mymodule\Form\Mycustomform'
    _title: 'Records'
  requirements:
    _permission: mycustompermission

mymodule.autocomplete:
  path: 'autocomplete'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::autocomplete'
    _format: json
  requirements:
    _permission: 'access content'

\src\Controller\MyModuleController.php
...
class MyModuleController extends ControllerBase {

    public function autocomplete(Request $request)
    {
        $string = $request->query->get('q');
        $matches = array();
        \Drupal:logger('autocomplete')->notice($string);
        $query = \Drupal::entityQuery('node');
        $query->condition('type','customers');
        $query->condition('title', '%'.$string.'%', 'like');
        $query->sort('title');
        $query->range(0,20);
        $entity = $query->execute();
        $nodos = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity);
        foreach ($nodos as $row) {
            $matches[] = array('value' => $row->getTitle(), 'label' => $row->getTitle());
        }

        return new JsonResponse($matches);
    }
}

If I see drupal log, I never get a register as expected. But if I see conosole log, I don't see ajax request. How could I find where is the problem? I think there isn't an ajax call when I write some letters on the input field. I don't see the circle on the right of the input that is shown when autocomplete is working.
Comment: Can you try without the _format: json? Btw, I think you could still use entity_autocomplete for this, in combination with a custom selection plugin. You just need that plugin then where you override/customize the query. Using #type entity_autocomplete gives you a bunch of additional things like proper handling of default value/validation to make sure your users can really only select a valid node there.. just having the autocomplete means you still need to parse the string, validate it and so on.
Comment: Thanks for your help. I have found the problem. The code is right. See my answer below.
Answer: After some tests I have found the problem. My code is right and it works good. The problem was the template file input--textfield.html.twig. Input textfield needs some automplete classes to work and this template deleted them to add some other classes. The required classes are: form-autocomplete form-text ui-autocomplete-input. I have changed this template file to add a new class I need but without deleting the other, and then, autocomplete works.
Answer: I do not tested your code but I see that your custom form doing completely the same like entity_autocomplete form element https://www.drupal.org/node/2418529
$form['customer'] = array(
      '#type' => 'entity_autocomplete',
      '#title' => t('Customer'),
      '#id' => 'inpCustomer',
      '#target_type' => 'node',
      '#selection_settings' => array(
        'target_bundles' => array('customers'),
        ),
    );

Comment: Thanks for your help. The autocomplete function I have shown is an extract. It is more complex to filter only some customers with some conditions, but thouse code is not important for my question.


DateTime formatter

Question: I am developing an application and I am stuck in converting string like 01/01/2037 01:00:00 AM
to Date
I used
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa")

Date d = dateFormat.parse(dateString);

but I get an error, any help will be appreciated.
Comment: You should add a tag to specify the language. Is it Java? Plus, when you get an error, post the code that throws it as well as the actual error message.
Answer: you are converting this 01/01/2037 01:00:00 AM
therefore use
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa")
(more info in [documentation])1
then
Date date = dateFormat.parse("01/01/2037 01:00:00 AM");
keep in mind you have to wrap a try-catch around the parse method.
Answer: The problem is that the format you declared is nothing like the String you are trying to parse:

your String uses / to separate day, month, year while in your formatter you use -
your string separates hours with a dot, while in the formatter you use  :
you do not have milliseconds in your string while you declared them in the formatter.

The following code should work:
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S aa");
    try {
        Date date = dateFormat.parse("01-01-2037 01.00.00.000 AM");
        System.out.println(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

DateTime formatter


Reading score. What is a system?

Question: In piano class the teacher told the first pair of students to play the first system and the second pair of students to play the second system.  The piece played was eight measures long, binary form AABB, written out on two lines. The first line A repeated, the second line B repeated. The first pair played AA.  The second pair played BB.  What is meant by term "system."
Comment: Oddly enough,  I made it through over 30 years of lessons and ensemble playing before I bumped into someone who used this term!
Answer: A "system" is just a line of music, and by "line" of music, we mean a staff line.
For a single-staff instrument, the first system will just be the first staff line of music, like so:

For a multi-staff instrument like the piano, the first system will be the line of music shown on the first grand staff. And since it's a grand staff, the first system actually includes two different staves, like so:

I assume the eight-measure piece in piano class was split up across two different lines of music, so the the first pair of students were to play the first line, while the second pair of students were to play the second line.
Comment: Just to make this a bit clearer: a "system" includes *all* the instruments that are playing at the same time, not just the two staves in a Grand Staff. In an orchestra score, often one system takes up the entire page. Also, in English, "staff line" often means "just one of the 5 lines of the staff". The term for the complete 5-line staff is just "staff". Some people use the word "line" when they really mean either "staff" or "system", but that is confusing. It is better *not* to use "line" unless you use another word to say what type of line you mean - there are also bar lines, 8va lines, etc.
Comment: @alephzero Yeah, this was a surprisingly hard answer to write. I've encountered people that also equate "staff" with "clef," and I wanted to make sure I didn't run into that problem.

Reading score. What is a system?


Destruir(Logout) Session_ID Codeigniter

Question: Através do código abaixo eu recupero todos os usuários logados no sistema e os exibo numa tabela.
<?php
        $dados = array(
            'session_id',
            'ip_address',
            'last_activity',
            'user_data'
        );
        $this->db->select($dados);
        $query = $this->db->get("ci_sessions");
?>

  <?php foreach ($query->result() as $linha):?>

     <?php
    $sessao = $linha->user_data;
    $dados = unserialize($sessao);
     ?>
     <?php if(!empty($dados['nome_usuario'])): ?>
     <?php echo htmlspecialchars($dados['nome_usuario'],ENT_QUOTES, 'UTF-8');?>
     <?php echo htmlspecialchars($linha->ip_address, ENT_QUOTES, 'UTF-8'); ?>
     <?php echo date('d/m/Y H:i:s',$linha->last_activity);?>
     <a href="<?php echo site_url('login/deslogar'); ?>"
          class="btn btn-danger btn-flat">
     <?php echo lang('usuarios_deslogar_usuario'); ?>
     <?php endif; ?>

  <?php endforeach;?>

O que eu quero agora, é ter uma opção de deslogar usuário para cada linha exibida, que quando clicado, o usuário seja deslogado.
Através do botão:

  <a href="<?php echo site_url('login/deslogar'); ?>"
          class="btn btn-danger btn-flat"><?php echo 'Deslogar'; ?>

<?php endif; ?>

Então, como faço para destruir somente a sessão do id que desloguei?
Comment: Já fiz isso, e fiz passando o session_id e removia essa linha do banco de dados, assim, qdo esse usuário tentava fazer qualquer outra ação no site ele era redirecionado para a tela de login
Answer: Precisa criar um método e excluir o registro desse usuário pelo session_id da tabela ci_sessions:
Html

  <a href="/login/deslogar/<?php echo $linha->session_id;?>"
          class="btn btn-danger btn-flat">Deslogar

Controller
public function deslogar($id)
{
    $this->db->where('session_id', $id);
    $this->db->delete('ci_sessions');
}

A próxima ação do usuário, o mesmo será direcionado para fazer login novamente, isso impede que ele trabalhe na última sessão, mas, não na criação de uma nova, isso pode ser feito também com um campo status ou active.
Referencias

Database Driver - Sessions
How I can set a session in codeigniter 3 database?
Query Builder Class
Deleting Data
Comment: Obrigado!, Funcionou para mim.

Destruir(Logout) Session_ID Codeigniter


Pivot table in alphabetical order

Question: Am new to  MySQL, I want to pivot a table
Table contains two columns only Name and Occupation Where no null values are inserted
I want to pivot the occupation column so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor
I tried this query, Where am able to get them to the point where the column is pivoted
SELECT ( CASE
           WHEN occupation = 'Doctor' THEN NAME
           ELSE NULL
         END ) AS 'Doctor',
       ( CASE
           WHEN occupation = 'Professor' THEN NAME
           ELSE NULL
         END ) AS 'Professor',
       ( CASE
           WHEN occupation = 'Singer' THEN NAME
           ELSE NULL
         END ) AS 'Singer',
       ( CASE
           WHEN occupation = 'Actor' THEN NAME
           ELSE NULL
         END ) AS 'Actor'
FROM   occupations
ORDER  BY NAME;

My output as:
Aamina NULL NULL NULL
NULL Ashley NULL NULL
NULL Belvet NULL NULL
NULL Britney NULL NULL
NULL NULL Christeen NULL
NULL NULL NULL Eve
NULL NULL Jane NULL
NULL NULL NULL Jennifer
NULL NULL Jenny NULL
Julia NULL NULL NULL
NULL NULL NULL Ketty
NULL NULL Kristeen NULL
NULL Maria NULL NULL
NULL Meera NULL NULL
NULL Naomi NULL NULL
Priya NULL NULL NULL
NULL Priyanka NULL NULL
NULL NULL NULL Samantha

I can't figure a way out how can I can get output like:
Aamina Ashley Christeen Eve
Julia Belvet Jane Jennifer
Priya Britney Jenny Ketty
NULL Maria Kristeen Samantha
NULL Meera NULL NULL
NULL Naomi NULL NULL
NULL Priyanka NULL NULL

If someone could explain it to me, It would be really helpful. Thanks
Comment: Seriously consider handling issues of data display in application code. But, for further help, see https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query
Comment: I have read it now and I'll surely take care of it, Thank you
Comment: I'm not holding my breath
Answer: You can do this with window functions (available in MySQL 8.0) and aggregation:
select
    max(case when occupation = 'Doctor'    then name end) doctor,
    max(case when occupation = 'Professor' then name end) professor,
    max(case when occupation = 'Singer'    then name end) singer,
    max(case when occupation = 'Actor'     then name end) actor
from (
    select o.*,
        row_number() over(partition by occupation order by name) rn
    from occupations o
) o
group by rn

Comment: Thank you, But Can You explain what you did? and why you did?
Comment: @SwapnilPadaya: Sure. The subquery ranks records having the same occupation by ascending name. Then the outer query does the pivoting, and puts each occupation in a different column. You can run the subquery and stare at the results to better understand how this works.
Comment: Thank you have understood what you did and also now I know that I need to improve in subquery and aggregate functions.

Pivot table in alphabetical order


Number of involutions by combinatorial

Question: Let $_$ be the number of involutions in $\sigma_n$. Show that $_0 = _1 = 1$ and for $ \geq 2$
$_ = _{−1} + ( − 1)_{−2}.$
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.  Please edit your question to show what you have attempted and explain where you are stuck so that you receive responses that address the specific difficulties you are encountering.
Answer: Let $f$ be an involution on $\{1,2,...,n\}$.
Then, only two things could happen with $f(n)$:

Either $f(n)=n$ and $f$ restricts to an involution on $\{1,2,...,n-1\}$, or
$f(n) \ne n$ and $f$ restricts to an involution on $\{1,2,...,n-1\} \setminus \{f(n)\}$.

In the first case, there are $i_{n-1}$ involutions on $\{1,2,...,n-1\}$, each of which induces an involution on $\{1,2,...,n\}$ that fixes $n$.
In the second case, there are $n-1$ possible choices for $f(n)$, and each involution on the remaining $n-2$ elements (of which there are $i_{n-2}$ of them) induces an involution on $\{1,2,...,n\}$ that does not fix $n$.
So, $i_n=i_{n-1}+(n-1)i_{n-2}$.
There is just one involution on the empty set or on any singleton set (namely, the identity map), so $i_0=i_1=1$.
Comment: Fine work, but It's better not to give a full answer to somebody that has shown no personal work...

Number of involutions by combinatorial


Basic question on Implication

Question: Could anyone conceive of any predicates and Universe ( in mathematics, in the world, etc ) where we should use $\exists x ( P(x) \to Q(x) )$, and not necessarily $\forall x ( P(x) \to Q(x) )$ ?
I was thinking of some sittuation where the property of P implies property of Q for at least some individual on the domain, but not for all individuals on the domain. i think its non-existant sittuation ?
I tried to think , and the closest i got was to think that since we know that for some $n$, we have that $n$ is prime, plus $ 2^n-1$ is prime. So, i thought of using $\exists n$ ( $n$ is prime $\to$ $2^n -1$ is prime ) .
Would this be correct to use ?
Then i thought i could use  $\exists n$ ( $n$  is  prime $\land$ $2^n - 1 $ is prime ) instead, and those are not semantic equvialent, so now i'm kinda lost.
Answer: It is worth remarking that a claim of the form $\exists x ( P(x) \to Q(x) )$ is typically unlikely to be interestingly informative and worth saying.
Why so?
Well,  $\exists x ( P(x) \to Q(x) )$ is true so long as $P(a) \to Q(a)$ is true for some case where $a$ newly dubs an element of the domain. But that material conditional will be true so long as its antecedent is false.
Hence, so long as there is something $a$ in the domain which doesn't satisfy $P$, we have $\exists x ( P(x) \to Q(x) )$.
So, if you know already that $P$ is not universally true of everything in the domain (so there is something in the domain who can dub $a$ where $P(a)$ is false), and this is probably the typical case, then $\exists x ( P(x) \to Q(x) )$ gives you no new information.
Comment: I think this is exactly the answer the OP was looking for.
Answer: Consider $P(x) \equiv Cube(x)$, $Q(x) \equiv Small(x)$ in a world with a small cube $a$ and a big cube $b$.
Then $\exists x:P(x) \rightarrow Q(x)$ is true (due to $a$ being small), while $\forall x: P(x) \rightarrow Q(x)$ is false (because $b$ is a cube, but is not small).
Comment: Is it always the case that ( ∃x:P(x)→Q(x) )  ->  ∃x:P(x)∧Q(x) ? Or would be the converse that is true ?
Comment: @nerdy The first says: something is (either non-P or Q). The second says that something is (both P and Q). The second, of course, is stronger: if something is (both P and Q), then something is (simply Q), from which it follows that something is (Q or non-P), which is what the first says. The other direction isn't valid: consider a world with one thing that Qs but doesn't P. In that world, the first is true (because the object satisfies Q), but the second is false (because the object doesn't satisfy P).
Comment: @nerdy - as explained by Peter and Hunan, the "interesting" couple is : $\forall x (P(x) \rightarrow Q(x))$ **and** $\exists x (P(x) \land Q(x))$; they are the so-called *restricted* (or *bounded*) quantifiers. We use them when we want to "restrict" the "search for" the objects such that $Q$ holds of them to the "domain" of objects such that $P$ holds. The canonical example is "all men are mortal", which we translate as $\forall x (Man(x) \rightarrow Mortal(x))$. The existential "counterpart" of it need $\land$ just because we want to avoid the "trivial" case ... 1/2
Comment: ... when $P$ holds of **no** objects (i.e. $\exists x P(x)$ is *false*). In order to avoid this we need $\land$, exactly because (as per Hunan's comment) $P \rightarrow Q$ and $P \land Q$ are **not** equivalent. Thus : "some man are wise" is translated as $\exists x (Man(x) \land Wise(x))$. 2/2
Comment: Hmmm i understand.But i'm thinking here we could use $\exists x : P(x) \wedge   Q(x)$  .   Since the $"\wedge"$ one is not equivalent to the $"->"$ one, which should we try to use on that case ??
Comment: @nerdy Sure, you can use $\land$ instead; the existential will be true because there is a small cube, and the universal will remain false because not everything is a small cube (for example, $b$ is a big cube). Did I understand you correctly?
Comment: @MauroALLEGRANZA Thanks for the helpful comments.
Answer: $$P(x)\equiv(x\le 1),\qquad Q(x)\equiv(x=1)$$
$$\exists x(x\le1\implies x=1)$$
is true, but
$$\forall x(x\le1\implies x=1)$$
is false.
Comment: Thanks you two for the wto examples.   Could you share a light on which of the two i should use for the mersenne primes ? since they are non-equivalent
Comment: I'm thinking here we could use ∃x:P(x)∧Q(x) i think to describe roughly the same thing . Since the "∧" one is not equivalent to the "−>" one, which should we try to use on that case ??

Basic question on Implication


Number of integers points on a sphere with radius 25

Question: How to find the number of integer coordinates of the set $\{(x_1,x_2,x_3)\in \mathbb{R}^3:x_1^2+x_2^2+x_3^2=25^2\}$ . Do we have any solution for more generaliized problems in higher dimensional spheres with any radius?
Comment: See Hirshborn, On representations of a number as a sum of three squares - http://www.sciencedirect.com/science/article/pii/S0012365X9800288X#
Comment: Your title suggests you want the radius to be $25$, but the sphere equation you give in your problem statement is for a sphere of radius $5$.  Which are you looking at?
Comment: There has been a lot of investigation of the number of representations of a given integer $n$ as a sum of $k$ squares for various values of $k$. There are formulas for some small values of $k$, formulas which generally depend on the prime factorization of $n$. The Hirschhorn paper is also at http://web.maths.unsw.edu.au/~mikeh/webpapers/paper63.pdf
Comment: Have you had a chance to track down this paper?
Comment: Earth to user90533: Come in, please.
Answer: Lagrange showed that any integer can be written as the sum of four squares. So, for spheres in $\mathbb{R}^n$ with $n \geq 4$, this theorem tells us that we have at least one point with integer coordinates, since we may always find $a, b, c,$ and $d$ such that
$$a^2 + b^2 + c^2 + d^2 = k,$$ for any positive integer $k$ (in your problem, you want $k = r^2$, where $r$ is the radius of your sphere).
It isn't necessarily the case that all of $a, b, c,$ and $d$ are distinct and non-zero, but in what follows, I'll assume they are. Things get messy when they aren't, and need to be handled on a case-by-case basis.
In $\mathbb{R}^4$, this guarantees us at least $4!$ integer points on a given sphere, since we can permute the coordinates (i.e., if $(1, 2, 3, 4)$ works, then $(2, 1, 4, 3)$ must also work, etc). Further, if $(a, b, c, d)$ works, then we can make any entries negative, and there are $2^4$ ways to assign negative signs to a $4$-tuple $(a, b, c, d)$. Thus, when $n = 4$, we have at least $2^4 \cdot 4! = 384$ integer points on our sphere, guaranteed by Lagrange's four-square theorem (again, assuming $a, b, c$ and $d$ are distinct).
If we're in $\mathbb{R}^n$, where $n > 4$, can still apply this four-square theorem, since we can pad any sum of 4 squares with zeros. This means that we'll have at least $2^4 \cdot \frac{n!}{(n - 4)!}$ integer points on a sphere whose radius is the square root of an suitable integer (whose decomposition into a sum of four squares uses four distinct non-zero integers). The $2^4$ comes from assigning signs to our non-zero coordinates, and the $\frac{n!}{(n-4)!}$ comes from permuting the non-zero coordinates.
This is simply a lower bound on the number of integer coordinates in $\mathbb{R}^n$, where $n \geq 4$, in certain situations, but hopefully it's relevant to you.


How to add a menu to Drupal with all external links from module code?

Question: I am writing a module that gets data from a couple sources, mostly XML, and then creates a nested array of values, such as "Title" and "URL"/link.
I'd like to create a new menu and then loop through my nested array and for each entry create a new menu item or child menu item, passing the title and URL to Drupal's menu system. I know that I can create menus with menu_save and items with hook_menu but how to create a new menu that has all external URLs?
Here is a part of the data:
<code>Array
(
    [8CB0A2C5DC3B19401323F1A3F22D5769] => Array
        (
            [id] => 8CB0A2C5DC3B19401323F1A3F22D5769
            [parentId] => CA4CBBBB070F043ACF7FB35FE3FD1081
            [level] => 1
            [link] => http://externallink.com/fjdsklafjdkl
            [title] => Foo
            [orderWeight] => 1
            [children] => Array
                (
                    [259D3A1F1BCB8D601B13742603415970] => Array
                        (
                            [id] => 259D3A1F1BCB8D601B13742603415970
                            [parentId] => 8CB0A2C5DC3B19401323F1A3F22D5769
                            [level] => 2
                            [link] => http://externallink.com/hi
                            [title] => FooFooFoo
                            [orderWeight] => -3
                            [children] => Array
                                (
                                    [23C7938348994922AB879B87A85567DF] => Array
                                        (
                                            [id] => 23C7938348994922AB879B87A85567DF
                                            [parentId] => 259D3A1F1BCB8D601B13742603415970
                                            [level] => 3
                                            [link] => http://externallink.com?jfsdk
                                            [title] => FooFooFooFooFooFoo
                                            [orderWeight] => -1
                                        )

                                    [993EC027EC1342E39F48A30E754621AA] => Array
                                        (
                                            [id] => 993EC027EC1342E39F48A30E754621AA
                                            [parentId] => 259D3A1F1BCB8D601B13742603415970
                                            [level] => 3
                                            [link] => http://externallink.com
                                            [title] => FooFooFooFooFoo
                                            [orderWeight] => 1
                                        )
                                  )
                            )
                      )
                )
          [B7D67ECD8DD382E2A9F6E8F8149011E4] => Array
              (
                  [id] => B7D67ECD8DD382E2A9F6E8F8149011E4
                  [parentId] => CA4CBBBB070F043ACF7FB35FE3FD1081
                  [level] => 1
                  [link] => http://externallink.com
                  [title] => FooFooFoo
                  [orderWeight] => 3
                  [children] => Array
                      (
                          [B18FA5C86281B72BB9914EC541216F21] => Array
                              (
                                  [id] => B18FA5C86281B72BB9914EC541216F21
                                  [parentId] => B7D67ECD8DD382E2A9F6E8F8149011E4
                                  [level] => 2
                                  [link] => http://externallink.com
                                  [title] => Foo Foo Foo
                                  [orderWeight] => 8
                                  [children] => Array
                                      (
                                          [C20086F4FDF627499800D60391C384E3] => Array
                                              (
                                                  [id] => C20086F4FDF627499800D60391C384E3
                                                  [parentId] => B18FA5C86281B72BB9914EC541216F21
                                                  [level] => 3
                                                  [link] => http://externallink.com60391C384E3
                                                  [title] => Foo Foo
                                                  [orderWeight] => 9
                                              )

                                          [E5F00486FC054E78B68A996B30DAC89C] => Array
                                              (
                                                  [id] => E5F00486FC054E78B68A996B30DAC89C
                                                  [parentId] => B18FA5C86281B72BB9914EC541216F21
                                                  [level] => 3
                                                  [link] => http://externallink.commmm
                                                  [title] => Foo
                                                  [orderWeight] => 26
                                              )
                                        )
                                  )
                            )
                      )
)
</code>
Answer: You can create menu programmatically, using menu_save function and after that add links to this menu using menu_link_save function.
Comment: Thanks! I didn't know about menu_link_save() and external links. Worked a treat! :)


Search for a text accross all revision of a file

Question: I have a file which contained some text at some point which was then deleted.
I forgot which exact commit and in what branch it existed.
Is there any way to search all revisions of a file accross all the branches and find a commit where file contains specific text?
Comment: `git log -p FILE` to show the diffenrence (as a patch), then you can easily search the result for the specific text
Answer: For this purpose you can use the -S option to git log:
git log -S'bar' -- foo.rb

This search the text bar in the file foo.rb
if you want to search through all diffs you can do: git log -G'bar' -- foo.rb

When -S or -G finds a change, show all the changes in that changeset, not just the files that contain the change in .

NOTE: This search is casesensitive.
If you add -i you can search case insensitive. Making the complete command:
git log -i -S'bar' -- foo.rb

NOTE 2: This searches only in your current branch.
If you want to search accross all branch you should add the --all flag

Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as .

The complete command will be:
git log --all -i -S'bar' -- foo.rb

The output will be something like this:
$ git log --all -i -S'bar' -- foo.rb

commit 53106e9cd319a2d8f960a3bbf2731acd0699a54f (feature/x)
Author: name <email>
Date:   Fri Jan 18 13:59:32 2019 +0100

    Added word

Comment: It search in current branch history only. E.g. I create another branch where I commit a file with `blablablah`, then I switch back to master and run the command. `git log -S'blablablah'` returns nothing, when I'd expect to see `branch X, commit 124abcf16`
Comment: Also note that if the file was renamed and/or copied, you might look at the `-M` and `-C` command-line options.
Comment: You should add the `--all` option :) i've updated the answer


Options for comparing logistic regression models

Question: I want to choose variables for building a logistic regression model by comparing the GOF of different types. The problem is that some of the candidates have some missing values so I can´t use the likelihood ratio test for comparing models, given that when I want to compare models with those variables they are not nested anymore.
So after exploring some options, I found that AIC or even BIC might be an option for that purpose.  Is either of those a valid option?
I am not familiar with the use of BIC, is it the same as AIC, where the smaller the value is, the better?
Comment: I'm not sure I understand why missing data means your models are not nested. Is it because cases are getting deleted if they don't have values for predictors in one model but not getting deleted in the more minimal models? That would pose a problem for AIC/BIC too, because they only provide meaningful comparisons when used on data sets with the exact same set of observations/cases.
Answer: Two points. First, I think it's a good idea to keep the sample the same across all models that you are comparing. That way it's a not an oranges to orangutans comparison. Maybe that puts you back in the nested world, and that will allow you to use conventional hypothesis testing. Second, the criterion you want to use depends on what you plan to do with the model. The trade-off between complexity and parsimony usually depends on the application. See my post on the AIC for more details.
Answer: You can use AIC to compare them.  The BIC is appropriate if you're doing a Bayesian analysis or it better captures what you theorize to be a good or useful information criterion.  If you don't know what any of that is then use AIC.  Some have recommended using BIC to assist in deciding marginal AIC values.
A lower value is better in both (smaller implies closer to 0?).  Usually the cutoff for deciding better vs. inconclusive is about a difference of 6.  If you need to report values of AIC report delta values because the absolute value of the AIC is relatively meaningless.  In some measures there is some qualitative, and perhaps quantitative, difference between finding values of 1 and 9, and 10001, and 10009.  This isn't so for AIC and the absolute measures just confuse matters.
Answer: The BIC is justified from the Bayesian viewpoint but you din't need to be taking a Bayesian approach to use it.  It is very similar to AIC.  The difference is in the form of the penalty function on the number of parameterrs used. AIC was introduced by Akaike in the mid 1970s.  BIC was introduced by Gideon Schwarz in 1978.
Comment: How do you respond to the [comment made by Anne Z.](http://stats.stackexchange.com/questions/22445/options-for-comparing-logistic-regression-models#comment40708_22445)?


How to count words characters or sentence from uploaded file PDF, Doc, Xls, Csv, etc etc

Question: How to count words from a uploaded file in PDF, Doc, Xls, Csv, etc etc. Either using PHP, Zend Framework or CLI based Java trigger ?
Comment: $wc filename.pdf or whatever gives this >  46   265 13025 file.odt
Comment: @pouncep, yes in linux i have this but which is wrong counter from terminal example: $ wc filename.pdf or filename.doc or filename.csv or filename.xls
Comment: @P.Brian.Mackey: 0.o which one is friendly for ZF and Java ? Is there no open source framework or libraries ?
Comment: Programmatically parsing PDF's is no small task. Your better off going with a 3rd party pdf reader and even those have issues when it comes to word ordering, but if you just need a word count they are pretty effective.  A PDF is laid out something like a collage.  There is no strict definition of a line.  What looks like a perfectly straight line to you, may be a huge mess geometrically speaking.
Comment: csv is easy. so you want tools to reverse-engineer pdf, doc, xls...?
Answer: Here's a third party app that does it http://www.globalrendering.com/download.html. You could create a simple wrapper for it.  As far as wc, its not accurate for those file types.  See http://ubuntuforums.org/showthread.php?t=566407
Comment: Thanks, Oops, its a installation for windows platform. Nothing for CentOS or Fedora ?
Comment: Yes its true, wc is not accurate for other file formats. Seems very complicated part remaining out there under Linux platform for counting word etc, for a real time or interactive solution development.
Comment: Hm, well for the PDF part you could save as text and do a word count on a normal text file. There's a script http://blog.yeticode.co.uk/2009/03/get-pdf-word-count-in-linux/. Similarly for word, not sure how well it will work on excel.
Comment: I have 11 (words) it shows 10, is this how maximum guess we can reach  ?. ex: https://gist.github.com/759888
Answer: First of all, you should have a look at tika
which is written in Java, is free (Apache licensed) and can convert all formats you mentioned to text. After that, word count should be trivial.
You could also use linux command line utilities for converting to text, and write a simple wrapper around them.
(I cannot link to these for lack of reputation. Use your Google-fu.)

pdf: pdftotext (part of xpdf). see also question #221359 on SuperUser.
doc(x): abiword, catdoc, antiword, docxtotxt ... see also question 165978 on SuperUser.
xls (and pretty much everything, but needs OpenOffice): unoconv