Best practise to store total values or to sum up at runtime

Question: I have an application where there a number of calculations for each 'job revision' – this involves the sum of multiple rows linked to that revision.
What I'm wondering is if the best practise is:

Storing a 'total' figure on the job revision, so we can display without summing it up
Calculating the total at runtime when displaying to the user
Comment: If your database supports materialized views (e.g. Oracle) or similar constructs then this is another alternative. Such databases may offer options for query rewrite against the materialized views.
Answer: This is highly dependent on several factors, such as:

How important is accuracy? Does the figure need to be exactly accurate as of the moment the figure is displayed?
How important is speed of retrieval? Is it more important that the figure be displayed promptly, than that it be accurate?
How important is speed of writing? Is it more important that each "row" be written-to quickly?
How much data is involved? Are we talking about millions of rows, or hundreds?
How often are multiple rows updated at the same time? Is it generally the case that many rows of a "job revision" are updated all at once, or is it more-likely that only a single row at a time will be involved?

Each of these has different trade-offs, and there are multiple options for satisfying the balance of each.

You can create triggers wich updates the "cached" total every time a new row is inserted , updated, or deleted. This will ensure both accuracy and fast retrieval, but will slow-down writes, as it involves an extra update of the "cache" table every time, which in-turn involves a row-level lock to ensure the number remains accurate. How much the lock slows down other operations will depend on how often other operations on the same "job revision" happen at the same time.
You can just calculate the value every time. This ensures the value is accurate, and that inserts/updates are fast, but calculating the value may be inefficient and slow.
You can store the value in a cached table, but only update it periodically. This ensures that both reads and writes are fast, at the expense of accuracy.

If you are only dealing with a handful of rows, there is not much difference between any of these, and "just calculate it every time" is fine. If there is no actual need to make things faster, calculating every time is preferred as "more normal"
As always: don't just ask for what's good in the general case. Profile your own code, see where the bottlenecks are, and tend to follow the rule "Don't, yet".
Answer: It depends.
If there's convenient way to work it out as you go along, then you don't need a probably expensive query to calculate it out. The big problem with pre-calculating though is the extra levels of complexity that you can be lumbered with maintaining the totals and the data.
It's design compromise, so there's no right answer about where you'll end up. All I would say is you should treat pre-calculation of totals as an optmisation, so if you don't know you need to do it yet, it's a premature optmisation.
If things get out of step, you can end up with a significant amount of work squaring up your data. If they are getting out of step through unfixed bugs or unplugged gaps, it's a significant and ongoing amount of work.
Not something you should need to or in fact should have to rush into.


HP Blade System Won't Come Up

Question: I recently asked a question on here regarding our HP Onboard Administrator not responding in a C7000 Blade Enclosure.  I was advised it was faulty and after contacting our 3rd line support company was sent a replacement and advised I would need to reboot the entire enclosure.
I've done that this morning and now it won't come back up!  All the NICs on the back aren't showing any activity at all and when I attempt to power up the blades the 'NIC 1' light flashed red.  Does anyone have any idea?  Really concerned now as I can't get in touch with the 3rd line organisation and my faith in them has really taken a hammering.
Any one have any idea why this is happening?  The OBA light is also still inactive so looks like the reboot didn't even fix that.
Answer: The answer here is the same one I provided before at:
HP Blade System 7000 - Fans About to Take Off
Call HP and have them send an authorized technician to your site to diagnose and fix the problem. Even if you're out of support, they will do it for a price.
There's no use in trying to guess ho to fix this at this point.

HP Blade System Won't Come Up


Tor$^{R}_{n+1}(k,k)=0$ implies Pd$_RM\leq n$ for any $R$-module $M$?

Question: Let $R$ be a Noetherian local ring with maximal ideal $m$, $k$ its residue field $R/m$.
Then Tor$^{R}_{n+1}(k,k)=0$ implies Pd$_RM\leq n$ for any $R$-module $M$?(Pd$_RM$ is the projective dimension of $M$ over $R$.)
What I know is that since $k$ is a finitely generated $R$-module, Tor$^{R}_{n+1}(k,M)=0$ for any module $M$. Then Tor$^{R}_{n+1}(M,k)=0$ for any module $M$. So for any finitely generated module $M$, Pd$_RM\leq n$.
I am wondering if this can be extended to the case where $M$ is an arbitrary $R$-module.
Answer: It seems that what you are asking more specifically is

If every fin.-gen. $R$-module $M$ has $\mathrm{pd_R}M\leq n,$ does every $R$-module $M$ have $\mathrm{pd_R}M\leq n$?

The answer is "Yes".
The idea is: Filter your module by an increasing well-ordered chain $(M_{\alpha})_{\alpha < \kappa}$ of submodules such that $M_{0}=0$ and $M_{\alpha}=\bigcup_{\beta < \alpha}M_{\beta}$ at limit ordinals, and such that all the consecutive quotients $M_{\alpha+1}/M_{\alpha}$ are  of $\mathrm{pd}_R \leq n$ (in our case finitely generated). Then by induction (on $n$ and $\alpha$), one shows that each $M_{\alpha}$ is of $\mathrm{pd}_R \leq n$, and, by the same argument, that $M$ is.
The induction step for non-limit ordinals is easy, it's just the fact that modules of $\mathrm{pd}_R \leq n$ are closed under extensions (by the long exact sequence for $\mathrm{Ext}_R$), but the limit case requires more trickery: Namely, given $\alpha$ a limit ordinal, for each $\beta < \alpha$ consider the "canonical" epimorphism from free module
$$0 \rightarrow K_\beta \rightarrow R^{\oplus M_{\beta}} \rightarrow M_{\beta}\rightarrow 0,$$
Then observe that for each $\beta< \beta' < \alpha,$ there are induced compatible injective maps $K_{\beta} \rightarrow K_{\beta'} $ and split-injective maps $R^{\oplus M_{\beta}} \rightarrow R^{\oplus M_{\beta'}}$. Taking directed union (i.e. applying $\varinjlim_{\beta < \alpha}$), one obtains again the canonical epimorphism from free module
$$0 \rightarrow \bigcup_{\beta<\alpha}K_{\beta} \rightarrow R^{\oplus M_{\alpha}} \rightarrow M_{\alpha}\rightarrow 0.$$
But now we expressed $K_{\alpha}=\bigcup_{\beta<\alpha}K_{\beta}$ again in the form of "continuous" filtration with consecutive quotients of $\mathrm{pd}_R\leq n-1$. So from induction on $n$, $\mathrm{pd}_RK_{\alpha}\leq n-1,$ hence $\mathrm{pd}_RM_{\alpha}\leq n.$
Answer: Note that every module $M$ has projective dimension $\leq n$ iff $\operatorname{Ext}^{n+1}(M,N)=0$ for all $M$ and $N$ iff every module $N$ has injective dimension $\leq n$.  Now $N$ has injective dimension $\leq n$ iff the $n$th cokernel $K$ of any injective resolution of $n$ is injective.  By Baer's criterion, this is true iff $\operatorname{Ext}^1(R/I,K)=0$ for any ideal $I\subseteq R$.  But now $R/I$ is finitely generated and hence has projective dimension $\leq n$, and so $\operatorname{Ext}^1(R/I,K)\cong \operatorname{Ext}^{n+1}(R/I,N)=0$.  Thus $K$ is injective, and $N$ has injective dimension $\leq n$ for arbitrary $N$, and thus $M$ has projective dimension $\leq n$ for arbitrary $M$.
More generally, this shows that if every cyclic module over some ring has projective dimension $\leq n$, then every module has projective dimension $\leq n$.
Comment: Thank you very much! Everything is clear.


Como consumir webservice em uma extensão do Chrome?

Question: Opa pessoal,
Blz?
Preciso consumir um webservice em uma extensão do Chrome, alguma dica? Já tentei chamar um programa externo usando NAPI, mas vi que está sendo descontinuada no Chrome 43.
Att,
Valdo
Comment: Agradeço pelas resposta, foram muito úteis..... mas alguém teria um exemplo prático? Eu li muita coisa e entendi... mas a dificuldade está em colocar na prática... se alguém puder ajudar... agradeço....
Answer: Indico a utilização do Postman
É completo e deve atender suas necessidades.
É bem simples e intuitivo, porém se precisar consultar a documentação, segue o link
Answer: Indico a utilização do Advanced Rest Client
O Rest é uma ótima extensão, te ajuda a organizar os seus projetos.

Ele possui funcionalidades para exportar os seus projetos dentre outras.


How to evaluate a summation when index of inner sum cannot be equal to outer sum

Question: I am looking at a summation that resembles the summation below:
$$\sum_{i=1}^n\sum_{\matrix{j=1\\j \not= i}}^n 1$$
What is the best way to think about this summation and thus get the result? Can the sum be broken apart into a more intuitive form?
Comment: Is $\left(\sum_{i=1}^n\sum{j=1}^n f(i,j)\right)-\sum_{k=1}^nf(k,k)$ more intuitive? (I think this is really a question that doesn't respond well to generalization; how you rearrange a sum depends on what you're summing)
Comment: For completeness you might want to specify $j=1$ to $n$, in addition to $j\neq i$ (if that is indeed what it is supposed to mean).
Comment: As an extension, an interesting question would be to evaluate $$\sum_{i=1}^{n}\sum_{\matrix{j=1\\ j\neq i}}^{n}j$$
Comment: An easy way, I think: take a $n\times n$ matrix $A$ with all entries equal to $1$, except the diagonal which is 0. Then sum all terms: you may imagine first that even the diagonal has ones, hence sum $n^2$, and you remove the diaginal which sums to $n$, hence result is $n^2-n$.
Answer: I would rewrite it this way.
$\sum_{i=1}^{n}\bigg[\underbrace{\sum_{j=1}^{i-1}1}_{(i-1)\text{-terms}}+\underbrace{\sum_{j=i+1}^{n}1}_{(n-i)\text{-terms}}\bigg]=\sum_{i=1}^{n}[(i-1)+(n-i)]=\sum_{i=1}^{n}(n-1)$
$\phantom{\sum_{i=1}^{n}\bigg[\underbrace{\sum_{j=1}^{i-1}1}_{(i-1)\text{-terms}}+\underbrace{\sum_{j=i+1}^{n}1}_{(n-i)\text{-terms}}\bigg]}=(n-1)\underbrace{\sum_{i=1}^{n}1}_{n\text{-terms}}=(n-1)n$.
Answer: I would add and remove
the deleted term
from the inside summation:
$\begin{array}\\
\sum_{i=1}^n\sum_{j \not= i} 1
&=\sum_{i=1}^n((\sum_{j=1}^n 1)- 1)\\
&=\sum_{i=1}^n((n)- 1)\\
&=n(n-1)
\end{array}
$
Fortunately,
my answer agrees with
that if bkarpuz.
More generally,
if
$F = \sum_{j=1}^n f(j)$,
$\begin{array}\\
\sum_{i=1}^n\sum_{j \not= i} f(j)
&=\sum_{i=1}^n((\sum_{j=1}^n f(j))- f(i))\\
&=\sum_{i=1}^n\sum_{j=1}^n f(j)-\sum_{i=1}^n f(i)\\
&=\sum_{i=1}^n F-F\\
&=nF-F\\
&=(n-1)F\\
\end{array}
$
Even more generally,
if
$F(i) = \sum_{j=1}^n f(i, j)$,
$G = \sum_{i=1}^n F(i)$,
and
$D = \sum_{i=1}^n f(i, i)$
,
$\begin{array}\\
\sum_{i=1}^n\sum_{j \not= i} f(i,j)
&=\sum_{i=1}^n((\sum_{j=1}^n f(i,j))- f(i,i))\\
&=\sum_{i=1}^n\sum_{j=1}^n f(i,j)-\sum_{i=1}^n f(i,i)\\
&=\sum_{i=1}^n F(i)-D\\
&=G-D\\
\end{array}
$
Answer: Since the summand is $1$, the summation is just the count of the number of elements to be summed. Hence
$$\begin{align}
&\overbrace{\sum_{1\leqslant i\leqslant n}}^n\;
\overbrace{\sum_{\matrix{1\leqslant j\leqslant n,\\ j\neq i}}1}^{n-1}\\
&=n(n-1)\qquad\blacksquare
\end{align}$$


Problemas com url HTACCES - Redirecionamento 301 não funciona em uma página

Question: Fiz redirecionamentos 301 de algumas das url's do meu site recentemente e começou a dar o problema da imagem:

Meu .htacces está assim:
RewriteEngine On
Options All -Indexes

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1

RewriteCond %{HTTP_HOST} ^www.(.*) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,L]

RewriteBase /
RewriteCond %{REQUEST_URI} /+[^.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

ErrorDocument 404 /404

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>

<IfModule mod_headers.c>
 Header unset Etag
 Header unset Last-Modified
</IfModule>

#REDIRECIONAMENTOS ***********

RewriteCond %{HTTP_HOST} ^MEUURLANTIGO\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.MEUURLANTIGO\.com\.br$
RewriteRule ^/?$ "http\:\/\/MEUURLNOVO\.com\.br\/" [R=301,L]

#MATERIAIS

RewriteCond %{HTTP_HOST} ^MEUURLANTIGO\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.MEUURLANTIGO\.com\.br$
RewriteRule ^material\-educativo/?$ "http\:\/\/MEUURLNOVO\.com\.br\/materiais\/" [R=301,L]

#BLOG

RewriteCond %{HTTP_HOST} ^MEUURLANTIGO\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.MEUURLANTIGO\.com\.br$
RewriteRule ^blog/?$ "http\:\/\/MEUURLNOVO\.com\.br\/blog\/" [R=301,L]

#artigos

RewriteCond %{HTTP_HOST} ^MEUURLANTIGO\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.MEUURLANTIGO\.com\.br$
RewriteRule ^blog\/impacto\-da\-internet\-nas\-empresas/?$ "http\:\/\/MEUURLNOVO\.com\.br\/blog\/impacto\-da\-internet\-nas\-empresas\/" [R=301,L]

RewriteCond %{HTTP_HOST} ^MEUURLANTIGO\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.MEUURLANTIGO\.com\.br$
RewriteRule ^blog\/5\-otimos\-motivos\-para\-investir\-em\-social\-media/?$ "http\:\/\/MEUURLNOVO\.com\.br\/blog\/5\-otimos\-motivos\-para\-investir\-em\-social\-media\/" [R=301,L]

obs.: o único que está funcionando é o do blog, os outros urls estão acontecendo isso
P.S.: Me ajudem não acho o porque desse erro em lugar algum :/
Comment: Não seria pq `.htacces[s]` ta faltando um `S`? Só pra ter certeza.
Answer: Talvez nesse formato funcione
Redirect 301 /blog http://meusitenovo.com.br/blog/

Comment: Não funciona porque meus 2 domínios estão na mesma hospedagem e apontam para a mesma pasta, se eu fizer assim ele não funciona ou dá loop infinito.


how to search multiple string (either of the string from the list) in a paragraph (updated with input & output images)

Question: My goal is to merge multiple paragraph based on predefined string (in an arrary) such as period (.) or question mark (?)
My sample sentence is as below (refer the image please):
Input
The expected result will be something like this.
////////////////////////////////////////////////////////
Output
////////////////////////////////////////////////////////
In the below code, I could achieve it using period (.), but for every other end string, I have separate macro. Depends on the end string, I run different macro. Is there way to put all these search string (. / ? / ;) in a single array and ask the code to run until it find either of them and exit from the loop and do the merge?

Blockquote

Sub FindDotToJoinParagraph()
Dim xRange As Range
Dim Srt As Variant
Dim Endee As Variant
Dim currentPosition As Range

Selection.HomeKey Unit:=wdLine, Extend:=wdMove
ActiveDocument.Bookmarks.Add Range:=Selection.Range, Name:="Srt" 'Bookmark

With Selection.Find
    .Text = "." 'Here not just period alone, but others too
    .Replacement.Text = ""
    .Forward = True
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = True
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With

Selection.Find.Execute
Selection.EndKey Unit:=wdLine, Extend:=wdMove
ActiveDocument.Bookmarks.Add Range:=Selection.Range, Name:="Ends" 'Bookmark

ActiveDocument.Range( _
    ActiveDocument.Bookmarks("Srt").Range.Start, _
    ActiveDocument.Bookmarks("Ends").Range.Start) _
    .Select

call MergeParaAndLineBreaks() 'An another sub-routine to merge

End Sub

//////////////////////////////////
    Sub MergeParaAndLineBreaks()
Dim oRng As Range
Set oRng = Selection.Range

Dim oFind As Range
Set oFind = Selection.Range

With oFind.Find
    Do While .Execute(findtext:="[^13^l]{1,}", MatchWildcards:=True)
        If oFind.InRange(oRng) Then
            oFind.Text = ""
        End If
    Loop
End With
Set oFind = oRng

With oFind.Find
    Do While .Execute(findtext:="[ ]{2,}", MatchWildcards:=True)
        If oFind.InRange(oRng) Then
            oFind.Text = Chr(32)
            oFind.Collapse 0
        End If
    Loop
End With

lbl_Exit:
Set oRng = Nothing
Set oFind = Nothing
Exit Sub
End Sub

Blockquote

Could someone help me out, please!
Comment: You need to update your example with a screen shot of the text in Word with the hidden formatting showing.  At the moment it is not clear if you paragraphs are paragraph or just section of text within a paragraph.
Comment: Your description suggests you're trying to clean up the formatting of text that's been copied from websites, e-mails, and/or PDFs. In that case, see, for example: http://www.msofficeforums.com/word/29880-cleaning-up-text-pasted-websites-e-mails.html
Comment: Hi @Freeflow, as per your recommendation, added images for both input and output. Thank you for looking at it
Comment: @macropod The input is not really from PDF, but sort of Yes. Thank you for the link. I checked it. Unfortunately it does not help.
Comment: Did you actually try the code there - and make sure your text is appropriately structured beforehand? Saying only "Unfortunately it does not help" isn't conducive to finding a solution. After all, not every sentence terminating a line in a document also terminates a paragraph. Colons & semi-colons, too, may be in-line and your approach could end up with some items following a colon being put in separate paragraphs and other items following the same colons being put in the same paragraphs.
Comment: @macropod Of course, I actually tested. Haven't tried anything complicated, just one simple sentence -> divided into multiple paragraph with . At the end of every sentence added period, Question mark and semi colon. The output is blank paragraph(s) are deleted, but sentences were not joined. If you copy paste my code, it works well only when there is a period. All I need is look not only for period, but also others such as question mark, semi-colon, etc.
Comment: The code in the link works just fine, regardless of how the sentences are terminated. Most likely you have an empty paragraph between each line of text - which the advice in the link I posted clearly says you should not have...
Answer: As noted in my comments, paragraphs don't necessarily end at punctuations marks. That said, a crude but effective solution to achieve the results you've described would be to use a wildcard Find/Replace, where:
Find = ([!.\!\?;:])^13
Replace = ^32\1

IOW, you don't even need a macro. Since we don't know whether there are spaces preceding the paragraph breaks in your source text, you may end up with some extra spaces - which you could clean up with another Find/Replace (or you might omit the ^32 from the Replace expression).
Comment: That's fabulous. With Replace = ^32\1 I could achieve it. Even though it merges everything into a single paragraph, still its OK. Written a small patch to split them. Thank you very much!!!
Comment: «Even though it merges everything into a single paragraph» - not if you're using the Find expression I posted...


Number of weights to be learnt in the encoder decoder attention in the transformer model

Question: I have a doubt about the number of weights to be learned in the encoder-decoder attention layer in the transformer model (attention is all you need). Some blogs articles say the $K$ and $V$ (key and value) matrices come from the memory (encoder output). This confused me. But If I'm right there should be:

8 matrices $W_K$
8 matrices $W_V$
8 matrices $W_Q$
1 matrix $W_O$

Right?
Answer: You are right that these are the parameters that conceptually belong to the encoder-decoder attention (sometimes called cross-attention).
The implementation can be different. What your goal is fast inference, you can pre-compute the keys and the values for each head because they only depend on the encoder output and do not change during decoding. For each decoded token, there is only one query vector (disregarding beam search and batching) which is compared with constant precomputed keys and values.


why$(\forall x \in U, P(x)) \implies (\exists x \in U, P(x))$ is false?

Question: may I have a complete proof of that "$(\forall x \in U, P(x)) \implies (\exists x \in U, P(x))$ " is false?
thx guys
Comment: What happens when $U=\varnothing$?
Comment: i know that actually but u has no element, i just cannot go further
Comment: Thx for your editing!i will try to tag "logic" next time.
Comment: If $U$ has no elements, can you find an element $x \in U$ such that $P(x)$ is true?
Comment: i think empty belongs to P, so maybe "yes". I'm not sure
Answer: It is true that "every purple elephant-sized duck owns polka dotted socks," for example. But there are no purple elephant-sized ducks.
Answer: Observe that $\forall x\in U \; P(x)$ is defined as $\forall x\;(x\in U\implies P(x))$ and $\exists x\in U \; P(x)$ is defined as $\exists x\;(x\in U \text{ and } P(x))$.
So, when $U=\emptyset$, there is no $x$ such that $x\in U$ and so for all $x$, $x\in U$ is false. Thus the statement $x\in U\implies P(x)$ is vacuously true for any $x$ and thus $\forall x\in U \; P(x)$ is true.
It isn't hard to see that $\exists x\in U\; P(x)\equiv \exists x\;(x\in U \text{ and } P(x))$ is false since there is no $x$ with $x\in U$.
Hence for $U=\emptyset$, your statement is an implication with a true antecedent but a false consequnt.
For $U\not= \emptyset$, your statement is true.
Comment: Why the first sentence is correct? Is it a definition? Thanks for your help.
Comment: @yunichanyeol Yes, it is a definition. But you should convince yourself that both these definitions make intuitive sense.


Is it okay to mix time windows in time series data?

Question: Suppose you are using a tree-based regression model to predict the popularity of things over time.  So if we wanted to predict the popularity of A in 2007, we would use A's popularity in 2006, 2005, and 2004, and if we wanted to predict the popularity of B in 2008, we would use B's popularity in 2007, 2006, 2005, and 2004.
Would it be okay to put both those points in the same training set?  I am concerned that the popularity of A in 2007 might affect the popularity of B in 2007 (so the label on one data point would affect the features on the other).
Answer: Tree-based regression is not a time-series model and it doesn't "know" anything about time structure of your data by default. For non-time-series model to learn about the time dependence you would prepare your data by adding special features to it, e.g. lagged target variable (you predict $y_t$ with $y_{t-1}$, $y_{t-2}$ etc.), or for regression model you could include time index (so you can model trend using $y_t = \beta_0 + \beta_1 t + \varepsilon_t$ model), other variables like dummies for special dates (weekends, holidays etc.), etc. So it is not really a question if you can use such data, but rather it is about how would you prepare features for your model in a way that is meaningful to model the phenomenon of your interest.
You can find nice example of defining clever features for regression-like time-series model in the paper describing the prophet package by Taylor and Letham from Facebook.


A doubt about Schlömilch remainder formula's proof

Question: I'm reading a proof of Schlömilch remainder formula in textbook Analysis I by Amann.

While the remainder function is given by

My questions:

In the author's definition,

I could not see how the hypothesis "perfect interval" is applied in the proof. Please shed me some light!

We have $$R_{n}(f, a)(x)=g(x)-g(a) = 0 - \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k !}(x-a)^{k} = - \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k !}(x-a)^{k}$$

But $R_{n}(f, a)(x)$ given by Taylor theorem is $$f(x) - \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k !}(x-a)^{k}$$
Could you please explain why there is no $f(x)$ as required in the formula?
Thank you so much!
Answer:
The assumption that $I$ is perfect is a fancy way of saying that $I$ contains a nonempty open interval, which is required to define the derivatives. It rules out the case that $I$ contains just a single point; it would be silly to define $C^n(I;\mathbb{R})$ in that case.
You are mistaken in writing $g(x) = 0$. The higher-order terms in the sum do zero out, but the $k=0$ term remains:
$$
g(x) = \sum_{k=0}^n \frac{f^{(k)}(x)}{k!}(x-x)^k = f^{(0)}(x) = f(x).
$$
Comment: Thank you so much :))


creating new partition for backup

Question: I got a  new server form hosting company.  It has 2x2tb hard drives.
I told the provider I would be using one drive for data/OS and the other for backup.Before doing offsite  backup.
I moved all my files and data over from the old server and then i decided to setup a backup.I need to create a mount but i  just realized the server has been setup in this config
df -h shows this.
Filesystem           Size  Used Avail Use% Mounted on
/dev/mapper/vg-root  1.8T   68G  1.7T   4% /
tmpfs                3.9G     0  3.9G   0% /dev/shm
/dev/sda1            243M   94M  137M  41% /boot
/dev/mapper/vg-tmp   976M  1.3M  924M   1% /tmp

lsblk shows this
    NAME               MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda                  8:0    0  1.8T  0 disk
sda1                 8:1    0  250M  0 part /boot
sdb                  8:16   0  1.8T  0 disk
sdb1                 8:17   0  1.8T  0 part
  vg-root (dm-0) 253:0    0  1.8T  0 lvm  /
  vg-swap (dm-1) 253:1    0  7.8G  0 lvm  [SWAP]
  vg-tmp (dm-2)  253:2    0    1G  0 lvm  /tmp

fdisk -l shows
Disk /dev/sda: 2000.4 GB, 2000398934016 bytes
255 heads, 31 sectors/track, 494247 cylinders
Units = cylinders of 7905 * 512 = 4047360 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00062874

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          66      256000   83  Linux

Disk /dev/sdb: 2000.4 GB, 2000398934016 bytes
255 heads, 63 sectors/track, 243201 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00083ac1

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1      243202  1953513472   8e  Linux LVM

Disk /dev/mapper/vg-root: 1991.0 GB, 1990952222720 bytes
255 heads, 63 sectors/track, 242052 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg-swap: 8355 MB, 8355053568 bytes
255 heads, 63 sectors/track, 1015 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg-tmp: 1073 MB, 1073741824 bytes
255 heads, 63 sectors/track, 130 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

pvs shows
 PV         VG   Fmt  Attr PSize PFree
  /dev/sdb1  vg   lvm2 a--  1.82t    0

I have been reading online about LVM and  by what I understand is that the system is installed on sdb while sda has only got the boot partition installed.
As i already  already moved the data across, removing lVM would mean reinstalling OS.
the other option  was to
1. remove  boot partition to  sdb
2. create a large  partition on sda and  use that for backup.
I am not sure which option is better. if i go with option b then how do it .If backup partition sits on the boot partition, as the disk will be used daily for backup, is the risk of failure high..  what happens  to boot partition ?
Answer: Your question comes a-two:
What i recommend: sda contains boot partition sda1 (250MB) + unallocated partition sda (1.8TB), so create your backup on sda, by doing 2. below
boot partition WILL NOT of any significance be affected by your daily backups, this is simply because sda and sda1 themselves are separate partitions, and you will just have the added overhead of backup (perhaps once off a day?), if so, this would be by far better than a an everyday disk where boot and data (OS, Apps etc) reside on the same device. So no worries about overheard from backups
With regards to either take Option A or Option B

Option B: Remove boot partition to sdb:
please have a look at https://askubuntu.com/questions/3402/how-to-move-boot-and-root-partitions-to-another-drive. or lookup "moving boot partition from one drive to the other"
Option A: Create a large partition on sda:

You need to read on "LVM on CentOS", you must have a specific question on this, otherwise your question will not be regarded as "useful, since there will be not much research"

checklist to quickly do LVM: https://www.centos.org/docs/5/html/Cluster_Logical_Volume_Manager/LV_create.html
In-depth article to help you understand LVM in CentOS: https://www.centos.org/docs/5/html/Cluster_Logical_Volume_Manager/LVM_CLI.html

So i'll say, take option 2 on my list above, and lookup for help to do LVM using existing or new partitions to create filesystems.
Comment: thanks for you feedback....i went with option 2 . created a primary partition with  fdisk. formatted the new partition and created a mount point..I didn't use vgextend .. Or should i  use vgextend ?
Comment: No, vgextend would certainly be for adding volumes right? You didn't add a volume right? If the file system (mount point) is now accessible (i.e. you can see it using `bdf` or `df` command, and you followed the steps as prescribed with the option you took (fdisk), thats fine for now, you're welcome

creating new partition for backup


Intuition about f1 score

Question: Let's say I have a data set where half of the data points are labelled as positive and half are labelled as negative. My task is to create a classifier which recognises when a sample from the dataset is positive.
The most useless classifier I could come up with would be to flip a fair coin whenever I get a sample to decide if the sample is positive or negative. One way to quantify the performance of that classifier is the f1 score which is in expectation 0.5 for a large dataset since recall is expected to be 0.5 and precision is expected to be 0.5. Additionally the f1 score should in principle be concentrated. That is intuitively the baseline f1 score I would compare everything to.
Now instead of that useless classifier I could create another classifier which in my opinion is just as useless where I simply say that all the samples I receive are positive. In that case my precision is still 0.5 but the recall is 1. This leads to an f1 score of 2/3 so if I use the f1 score as a measure to decide which classifier is better I should pick this one instead of the random one.
This is perhaps more of a philosophical pondering but in my opinion a way to select a classifier should not distinguish between those two classifiers (why should I prefer the second option?). Therefore I wanted to ask about alternatives that do pass such a test. I'd prefer a single number which is a function of true positive rate, false positive rate, true negative rate and false negative rate.
Answer: So this is a confusion matrix in case any readers haven't seen one:
$$
\begin{array}{l c c}
& Predict + & Predict-\\
Actual + & a & b \\
Actual - & c & d \\
\end{array}
$$
And this is the formula for calculating $F_1$ from a confusion matrix:
$$F_1 = \frac{2a}{2a+b+c}$$
So if half the items are positive in reality and all are predicted positive:
$$\begin{array}{l c c}
& Predict + & Predict-\\
Actual + & 50 & 0 \\
Actual - & 50 & 0 \\
\end{array}$$
Then $F_1$ in this case is equal to $2/3$ as you stated in your question:
$$F_1 = \frac{2(50)}{2(50)+50+0} = 0.67$$
But if half the items are positive in reality and all the items are randomly predicted, then there are many different ways for this to occur and the resulting $F_1$ score will range between $0.00$ and $1.00$. Let's imagine we have just two items, then there are four possible results for the random classifier:
$$\begin{array}{l c c c}
Item & Reality & Predict_1 & Predict_2 & Predict_3 & Predict_4 \\ \hline
1 & + & + & + & - & -\\
2 & - & + & - & + & -\\ \hline
F_1 & & 0.67 & 1.00 & 0.00 & 0.00\\
\end{array}$$
So all that was just to say that the value of $F_1$ for the random classifier is actually quite variable, unlike the always-positive classifier. The alternative I'd suggest is the $S$ score first proposed by Bennett, Alpert, & Goldstein (1954). It assumes a 50% probability of classifying any given item into its correct class "by chance" alone and discounts this from the final score. It also uses all cells of the confusion matrix (unlike $F_1$ which ignores $d$ or the number of "true negatives").
$$p_o = \frac{a+d}{a+b+c+d}$$
$$S = \frac{p_o - 0.5}{1-0.5}=2p_o-1$$
In the first example above, where $F_1=0.67$, the $S$ score would be equal to $0.00$ and would capture the idea that the predictions are doing no better than would be expected by chance.
$$p_o = \frac{50+0}{50+0+50+0}=0.50$$
$$S = 2(0.50)-1 = 0.00$$
In the second example above, where $0.00 \le F_1 \le 1.00$ with a mean of $0.42$, the $S$ score would actually range between $-1.00$ and $1.00$ with a mean of $0.00$. Thus, both classifiers would be deemed equal by the $S$ score:
$$\begin{array}{l c c c}
Item & Reality & Predict_1 & Predict_2 & Predict_3 & Predict_4 \\ \hline
1 & + & + & + & - & -\\
2 & - & + & - & + & -\\ \hline
F_1 & & 0.67 & 1.00 & 0.00 & 0.00\\
S & & 0.00 & 1.00 & -1.00 & 0.00 \\
\end{array}$$
You can find more information about classification reliability at my website, including a history of the S score and functions for calculating it in MATLAB and even generalizing it to multiple classifiers, multiple categories, and non-nominal categories.

Intuition about f1 score


Idiomatic way to get IP addresses of group of containers in ECS?

Question: I'm building an internal proxy service on AWS where a user can

send a request to a server
that server will send the request to one of several proxy containers in an ECS cluster

I'm not sure what's the best way to get the IP addresses of the proxy containers in the ECS cluster.
I could manually list the IPs once every N seconds and check if new containers have joined the ECS cluster, but I wonder if there's a better way?
Answer: You can listen for CloudWatch Events or AWS EventBridge Events related to container spin-up / tear-down. You can probably trigger a lambda for each event that can then do something, like add the container IP to a wherever it needs to be registered.
Alternatively you can use ECS Service Discovery that uses DNS to keep a list of active containers.
And finally you can get the containers to register themselves when they spin up. That's also an option, though a bit more DIY'ish.
Hope that helps :)


Showing different nodes for same taxonomy terms on different URLs

Question: I'm facing this design issue regularly.
For example I've Jobs and Company node types. Both have one common taxonomy term reference field City.
Now when we go to a City term it will show both Jobs and Companies(I don't want this mixing).
I want that it show only Jobs or Companies(in different URL's)
One solution is to duplicate City vocabulary as City Jobs and second as City Companies.  Now I get what I want. But in programming it'll complicate as same city in both Vocabularies will have different term id's.
What is the best way to achieve this?
Comment: i usually use some special modules around this use case,  but I think for the most common use cases the views page solution by Dylan Tack is sufficient.
Comment: I think Dylan's answer is totally fine, and he deserves the bounty. My own situation often has some more requirements, that is: (1) Different views for different vocabularies. (2)  Different views for root-level terms than for lower-level terms (in a hierarchical vocabulary). (3) Having additional elements on the term page, e.g. the list of associated content plus some text field or image. (4)  Having a special layout on the term page. (5) Having a similar behavior for nodes instead of terms. I would share this stuff, but I think it should go into a separate question.
Answer: You can use the Views module to create two different pages:

"Jobs in City %1" at /jobs/%
"Companies in City %1" /companies/%

Your Views will need a filter for content type, and a contextual filter for taxonomy term.  Next, use the Rabbit hole module to make the /taxonomy/term/NNN pages disappear.
Comment: But how to add all those urls at say jobs/% in the XML sitemap?
Answer:
You can create a view based on  City term title
Fields : Taxonomy term: Name -> Configure field: Taxonomy term: Name ->
 REWRITE RESULT -> Output this field as a link -> taxonomy/term/[tid]/job
You can use the view module to create two different pages:
a. view -> Page settings -> path -> taxonomy/term/%/job
b. Contextual filters add  Content: Has taxonomy term ID (with depth)   and    Content: Has taxonomy term ID depth modifier
c.  Content: Type (= job)
a1. view -> Page settings -> path -> taxonomy/term/%/company
b1. b. Contextual filters add  Content: Has taxonomy term ID (with depth)   and    Content: Has taxonomy term ID depth modifier
c1.Content: Type (= company)
when You click  Taxonomy term: Name (title) based on URL like taxonomy/term/1/job that redirect to taxonomy/term/%/job view page that return group of job content.

similarly group of company list
Answer: Dylan Tack's answer is the right and the easiest way to achieve this functionality; If you don't want to use Views module you can solve this by custom module, like this (I didn't test it, correct it, if something is wrong with it):
function myModule_menu() {
  $items = array();

  $items['jobs/%taxonomy_term'] = array(
    'title' => 'Jobs',
    'page callback' => 'custom_page_by_jobs',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  $items['companies/%taxonomy_term'] = array(
    'title' => 'Companies',
    'page callback' => 'custom_page_by_companies',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

// Mimic of taxonomy_select_nodes() function;
function taxonomy_select_nodes_by_type($tid, $type, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->join('field_data_field_city', 'fdfc', 't.tid = fdfc.field_city_tid');
  $query->addTag('node_access');
  $query->condition('t.tid', $tid);
  $query->condition('fdfc.bundle', $type, '=');
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');
  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

function custom_page_by_type($term, $type) {
//  drupal_set_title($term->name);
//
//  $current = (object) array(
//    'tid' => $term->tid,
//  );
//
//  $breadcrumb = array();
//  while ($parents = taxonomy_get_parents($current->tid)) {
//    $current = array_shift($parents);
//    $breadcrumb[] = l($current->name, 'taxonomy/term/' . $current->tid);
//  }
//  $breadcrumb[] = l(t('Home'), NULL);
//  $breadcrumb = array_reverse($breadcrumb);
//  drupal_set_breadcrumb($breadcrumb);
//
//  $uri = entity_uri('taxonomy_term', $term);
//  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
//
//  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);

  $build['term_heading'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    'term' => taxonomy_term_view($term, 'full'),
  );

  if ($nids = taxonomy_select_nodes_by_type($term->tid, $type, TRUE, 20)) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes);
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    $build['no_content'] = array(
      '#prefix' => '
',
      '#markup' => t('There is currently no content classified with this term.'),
      '#suffix' => '
',
    );
  }
  return $build;
}

function custom_page_by_jobs($taxonomy_term) {
  return custom_page_by_type($taxonomy_term, 'jobs');
}

function custom_page_by_companies($taxonomy_term) {
  return custom_page_by_type($taxonomy_term, 'companies');
}

Answer: Simple:

Go to Views administration page: admin/structure/views
Scroll down and clone Taxonomy term view.
Under Page Settings change path to: /taxonomy/term/%/%
Add new contextual filter under Advanced section
Select Content: type and apply default settings
Rearrange contextual filters so that the order is:

Content: Has taxonomy term ID (with depth)
Content: Type
Content: Has taxonomy term ID depth modifier

That's it

If you visit the term page taxonomy/term/%term, you will still see all content types in a list. However, you can now filter this list with the name of the content type, for example:

taxonomy/term/%term/jobs: will only list the jobs tagged with this term
taxonomy/term/%term/company: will only list the companies tagged with this term.


How to solve twisted.internet.error.CannotListenError: Couldn't listen on any:8081: [Errno 98] Address already in use

Question: I have a twisted python server which runs on port 8080, and i have written different API's which runs on this server. so i want all these API's to run on a single port no. but when i try to use same port all API's for ex : 8081 and run at the same time using python interpreter. at that time i am getting this error : twisted.internet.error.CannotListenError: Couldn't listen on any:8081: [Errno 98] Address already in use.
As i am new to twisted so don't know much of the things and there is no proper documentation on twisted . please someone guide me to solve this error :
Here is the Code snippets :
from twisted.internet import epollreactor

epollreactor.install()

from zope.interface import implements
from twisted.internet import reactor,interfaces
from functools import partial
from pymongo import Connection
import json
from bson.objectid import ObjectId
import server_1
import replacePlus_Space

global data, data_new, datadB, coll_auth, coll_person

class Login_user(server_1.HTTPEchoFactory):

    def __init__(self):
        server_1.HTTPEchoFactory.__init__(self,"testsite")
        server_1.HTTPEchoFactory.initResources(self)
        self.initResources()

    def initResources(self):
        print "in Login"
        self.responses["/login_user"] = partial(self.user_login)

    # To connect to DB and Check error cases and insert into mongoDB..!!!
    def user_login(self, client):
        # some functinality..!!!!

d = Login_user()

reactor.listenTCP(8081,d)

reactor.run()

Second code snippet is :
from twisted.internet import epollreactor

epollreactor.install()

from zope.interface import implements
from twisted.internet import reactor,interfaces
from functools import partial
from pymongo import Connection
import json
from bson.objectid import ObjectId
import server_1
import replacePlus_Space

class AddFriendDB(server_1.HTTPEchoFactory):

    def __init__(self):
        server_1.HTTPEchoFactory.__init__(self,"testsite")
        server_1.HTTPEchoFactory.initResources(self)
        self.initResources()

    def initResources(self):
        print "in add friend"
        self.responses["/addFriend_DB"] = partial(self.addFriendDB)

    # To connect to DB and Check error cases and insert into mongoDB..!!!
    def addFriendDB(self, client):
        #some functionality here..!!!

d = AddFriendDB()

reactor.listenTCP(8081,d)

reactor.run()

Answer: Translating the question
Many of the specifics in your question don't make sense, so I'm translating your question into:

I have a twisted python standalone program which runs on port 8080, and i have written a different standalone program which runs on this server. I want both programs to run on a single port no. When i try to use same port for all programs ex : using port 8081 for both programs. I am getting this error :twisted.internet.error.CannotListenError: Couldn't listen on any:8081: [Errno 98] Address already in use. As i am new to twisted i don't know much of the things and there is no proper documentation on twisted. please someone guide me to solve this error.

Twisted has great documentation
You commented that:

[...] there is no proper documentation on twisted

That statement is blatantly false.
Twisted certainly has proper documentation, and as compared to most frameworks it has excellent documentation. To name just a few of the many high quality documentation sources:

Dave Peticola's (krondo) Twisted Introduction - an excellent and deep introduction to twisted that begins by explaining the technology Twisted is built upon.  If you really want to understand twisted, this (long) introduction is the place to start
The high quality and extensive documentation on on Twisted's primary website twistedmatrix.com
The source itself.  Twisted has well commented and surprisingly understand source, if the above documentation doesn't teach you what you need figure it out from the code.

What causes "Address already in use"
As previously answered by Bart Friederichs:

Only one process can listen on a certain port. If you start process 1 to listen on port 8081, and then start another process on that same port, you get this error.
It is an error from the TCP stack, not from python or twisted.

This is a fundament truth of TCP/IP stacks across all operating systems (or at least all process based operating systems that could run Python).
The error is your operating system reminding you that when data comes to a IP port the OS/IP-stack was designed to only forward to one process, a process that is implementing an application level protocol on that port. The error happens when a second program attempts to re-register a port some other program has already registered.
Work-arounds in general
Upon running into a port reuse issue like this you have to ask yourself:

Are the two programs even running the same application-level protocol?
If they are the same protocol, does the protocol have routing such that for any given transaction the correct sub-program/routine be identified?
Are the two programs at a different location in the routing?

If they aren't the same protocol (I.E. one was HTTP and the other is FTP) or they are the same protocol but its a protocol that doesn't have routing (I.E. two instances of NTP) then there is no easy way to mix them because your trying to break the laws of IP (and the way that application protocol implementations are built). The only solution will be to encapsulate one (or both) of the protocol(s) into a common protocol that also has application-level routing (I.E. encapsulating FTP inside of HTTP and using the URI to route)
If they are the same protocol, and the protocol provides for a per-transaction routing (I.E. the URI inside of HTTP transactions) and they aren't at the same routing location, then there are easier solutions, namely:

Merge the two application into one.
If they are the same routable protocol but at a different location (I.E. HTTP protocol with the URI for the first program at /login and second program at /addfriend) it should be trivial to pull out the post-routing logic of the two programs/process and merge them into one program that does both functions
Front-end the programs with a redirector (This solution is only easy with HTTP because of the tools available).
If you have HTTP protocol programs that have routing to separate locations, but for some reason its hard to merge the logic together (I.E. one program is written in Java, the other in Python) then you can look at front-ending both programs with a redirector like nginx
The way you would use a redirector in a case like this is to run your two apps on two different unused ports (I.E. 12001, 12002), and then run the redirector on the port you want the service to be on, running it with a config file that will redirect to your two programs via their unique routing locations (via configs like SF: How to redirect requests to a different domain/url with nginx)

Code example
The following three programs illustrate the process of merging two programs into one, so both sets of logic can be accessed from the same port.
Two separate programs:
If you run the following code a web server will be started up on localhost:8081.  If you then point your web browser at http://127.0.0.1:8081/blah the blah page will be displayed.
#!/usr/bin/python

from twisted.internet import defer, protocol, reactor # the reactor

from twisted.web.server import Site # make the webserver go
from twisted.web.resource import Resource

class BlahPage(Resource):
    idLeaf = True
    def render_GET(self, request):
        return "Blah Page!"

class ShutdownPage(Resource):
    def render_GET(self, request):
        reactor.stop()

webroot = Resource()
webroot.putChild("blah", BlahPage())
webroot.putChild("shutdown", ShutdownPage())

def main():
    # Register the webserver (TCP server) into twisted
    webfactory = Site(webroot)
    reactor.listenTCP(8081, webfactory)

    print ("Starting server")
    reactor.run()

if __name__ == '__main__':
  main()

This code will start a web server on localhost:8082.  If you then point your web browser at http://127.0.0.1:8082/foo the foo page will be displayed.
#!/usr/bin/python

from twisted.internet import defer, protocol, reactor # the reactor

from twisted.web.server import Site # make the webserver go
from twisted.web.resource import Resource

class FooPage(Resource):
    idLeaf = True
    def render_GET(self, request):
        return "Foo Page!"

class ShutdownPage(Resource):
    def render_GET(self, request):
        reactor.stop()

webroot = Resource()
webroot.putChild("foo", FooPage())
webroot.putChild("shutdown", ShutdownPage())

def main():
    # Register the webserver (TCP server) into twisted
    webfactory = Site(webroot)
    reactor.listenTCP(8082, webfactory)

    print ("Starting server")
    reactor.run()

if __name__ == '__main__':
  main()

Merging the logic
This code is the merger of the two previous programs, as you can see it only required copying a small amount of code to glue both of the above into one that allows for access to http://127.0.0.1:8080/blah and http://127.0.0.1:8080/blah.
#!/usr/bin/python

from twisted.internet import defer, protocol, reactor # the reactor

from twisted.web.server import Site # make the webserver go
from twisted.web.resource import Resource

class BlahPage(Resource):
    idLeaf = True
    def render_GET(self, request):
        return "Blah Page!"

class FooPage(Resource):
    idLeaf = True
    def render_GET(self, request):
        return "Foo Page!"

class ShutdownPage(Resource):
    def render_GET(self, request):
        reactor.stop()

webroot = Resource()
webroot.putChild("foo", FooPage())
webroot.putChild("blah", BlahPage())
webroot.putChild("shutdown", ShutdownPage())

def main():
    # Register the webserver (TCP server) into twisted
    webfactory = Site(webroot)
    reactor.listenTCP(8080, webfactory)

    print ("Starting server")
    reactor.run()

if __name__ == '__main__':
  main()

Comment: I have updated the question with the code snippets. please help me out. thanks in advance.
Comment: @G-Coder Your update helps, I'll look at it more in a few hours.  One question that jumps out at me is: what is `HTTPEchoFactory`?  The only ref I can find for something with that name is some sample code in the "twisted network programming essentials" book.  Did you create code following that guide?
Comment: HTTPEchoFactory is a class in another .py file which is a server code written by me following the twisted.python documentation.
Comment: @G-Coder could you please add your `HTTPEchoFactory` code (or at least the twisted calls/classes that are in that code) without that context I can't suggest a way to blend you code.
Comment: HTTPEchoFactory code is no where related with my error. so thats not required.
Answer: Only one process can listen on a certain port. If you start process 1 to listen on port 8081, and then start another process on that same port, you get this error.
It is an error from the TCP stack, not from python or twisted.
Fix it either by choosing different ports for each process, or create a forking server.
Comment: Can u please tel me how to create a forking server
Comment: @G-Coder I am sorry, I can't in twisted or in Python. You'll have to research it yourself.


How to preserve element type validation upon adding custom element validation?

Question: I have ConfigFormBase.
It has a form element with '#type' => 'entity_autocomplete'.
When I add my custom element validation by '#element_validate' => [[get_class($this), 'validateReferencedItemExistence']] the original element validation which comes by the element type (Drupal\Core\Entity\Element\EntityAutocomplete::validateEntityAutocomplete) won't be added anymore.
After spending hours in the jungle of the FormBuilder class code I finally found the corresponding lines:
   if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = $this->elementInfo->getInfo($element['#type']))) {
      // Overlay $info onto $element, retaining preexisting keys in $element.
      $element += $info;
      $element['#defaults_loaded'] = TRUE;
    }

I find this kinda bad approach, that you cannot extend the list of the validation items. What is the reason behind it?
How could I make a workaround / solve this issue?
(Just by calling Drupal\Core\Entity\Element\EntityAutocomplete::validateEntityAutocomplete in my custom validation I would create an unnecessary depedency in my code. (Just think about if they change their way of validation with a different function))
Comment: You need to use the syntax PHP has for adding items to an array. If you use `$array['item'] = [];` you are replacing `$array['item']`; if you use `$array['item'][] = [];` you are adding items (supposing that `$array['item']` is an array).
Comment: Am aware of that, however this is not the situation here, because if the key already exists, the element type validation won't be added anymore by the FormBuilder class.
Answer: You need add the definitions defined in the getInfo() method of that type explicitly yourself, there is currently no other way to do that.


How to display configurable product list with color swatches option in home page Magento?

Question: I have used rwd theme, that theme have default option for color swatches option. that option was displayed from category pages, but am unable to display configurable products with color swatches option in the home page.
My current view
what i expected: this
thanks in advance...
Answer: Login to admin
Go to : System > Configuration > Catalog > Configurable Swatches > General Settings
Do setting as following

Enabled : Yes
Product Attribute to Use for Swatches in Product Listing : Color

Hope this make sense to you
Comment: Check `list.html`. Is it contains configurable swatches code?
Comment: thanks rohit, i have done this but i use below code in cms page->home page ->content:
 {{block type="catalog/product_list" name="product_list" category_id="5" template="catalog/product/list.phtml"}}

configurable product list are visible, but that options are not diplayed.

Please suggest..
Comment: Yes Rohit, Please see below :
if ($this->getChild('name.after')) {
                            $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                            foreach ($_nameAfterChildren as $_nameAfterChildName) {
                                $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                                $_nameAfterChild->setProduct($_product);
                                echo $_nameAfterChild->toHtml();
                            }
                        }

Please suggest


iPhone 5 Video Format

Question: I'm using MPMoviePlayerViewController (for an app that will run on the iPhone 4 AND iPhone 5) as follows:
<code>    NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:videoFile ofType:videoType]];
    MPMoviePlayerViewController *moviePlayerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
    moviePlayerVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:moviePlayerVC animated:YES completion:nil];
    MPMoviePlayerController *moviePlayer = moviePlayerVC.moviePlayer;

    // Register to receive a notification when the movie has finished playing.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:moviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerDidExitFullscreenNotification
                                               object:moviePlayer];

    [moviePlayer prepareToPlay];
    [moviePlayer play];
</code>
but the video editors need to know what video size to use (i.e. to cater for both the iPhone 4 and iPhone 5).
Looking at Apple's docs here: http://developer.apple.com/library/ios/ipad/#documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/MediaLayer/MediaLayer.html
under Video Technologies it states:
640 by 480 pixels
So, what video size would be best for both the iPhone 4 and 5.
E.g, should the video editors export video at 640 x 480 pixels?
Or should they export at 1136 x 640 (i.e the iPhone 5 screen size)?
Or perhaps 960 x 640 (iPhone 4)?
Answer: As you noted from the Apple documentation, the maximum supported resolution is 640 x 480 so there wouldn't be any additional advantage in having the videos exported at any higher resolution than that.

The video technologies in iOS support the playback of movie files with
the .mov, .mp4, .m4v, and .3gp filename extensions and using the
following compression standards:

H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,
Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio
up to 160 Kbps, 48 kHz, stereo audio in .m4v, .mp4, and .mov file
formats

H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per
second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160
Kbps, 48 kHz, stereo audio in .m4v, .mp4, and .mov file formats

MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple
Profile with AAC-LC audio up to 160 Kbps, 48 kHz, stereo audio in
.m4v, .mp4, and .mov file formats

iPhone 5 Video Format


Is it possible to find strings in any integer size?

Question: I am considering stringing my 6-string electric guitar with a series of prime gauges.
e.g. 11,13,17,29,37,47
I am looking on Ernie Ball's site and while I might be able to find the 3 thinner strings, the larger ones almost always fall into the same sizes (which are all composite numbers, not primes).
Has anyone ever seen gauges like this for larger strings?  (29,37,47)
Comment: For a moment, I thought that I had wandered into the maths site but the yellow banner contradicted that.  Why do you care whether the size numbers are prime or composite?  The particular numbers are just a chance effect of the units used.
Comment: I have not seen string gauges you are looking for (29, 37, and 47), but to get close you can order a custom package from String Joy here: https://www.stringjoy.com/guitarstrings/strings/electric-guitar-strings/custom-electric-guitar-strings/
Comment: @JasonPSallinger I am well aware of the connection between music and maths.  I am a member of two stack exchange communities: music and maths.  My point here is that the unit of size for the strings is arbitrary and hence no meaning can be sensibly attached to the numbers.  Is 13cm a prime length?  Does it cease being prime if we measure it in inches instead?
Comment: I just did a bit of Googling and most of the sizes that I see ate not even integers but numbers such as .042.  So, they are only integers if multiplied by 1000.  These sizes appear to be in inches.  If we went metric then the strings wouldn't change but the numbers would.  Here in the UK, I have prime feet: size 11.  In the US, they are 12 so not prime.  In Europe, they are 46, and other numbers in other countries.  Just arbitrary.
Comment: Onto the lower strings I guess the manufacturers just round gauges to the nearest even number - none of which will be prime. Apart from the principle involved, I defy you to tell in a blind test whether a bottom string is 47 or 48. What particular reasoning apart from maths is involved?
Comment: @badjohn - those dimensions are Imperial. They represent inches - .042" = 42 'thou'. (thousandths of an inch). Most strings seem to emanate from U.S., where Imperial measure (except capacity!) is still used.
Comment: @Tim i understand the origin.  Similarly, planes typically cruise at an altitude that is a neat number of feet.  My point is that both are just arbitrary quirks of history with no deep significance.  Today, the official definition of the imperial units refers to the SI system.
Comment: @badjohn - I believed that the imperial measures was peculiarly Engish or British, whereas the SI system, originated in France, comprised metric measure, so how do imperial units fit the SI system?
Comment: @Tim They originated independently but the modern definitions of the Imperial units are by reference to the SI system.  So, today, an inch is 2.54cm by definition.  The official definition of the metre has also changed and it is now defined as a particular number of wavelengths of light from krypton 86.  This is way off topic for a music group.  See https://en.wikipedia.org/wiki/Inch and https://en.wikipedia.org/wiki/Metre.
Comment: Your existence is arbitrary badjohn.  You're a fruitloop.
Answer: Yes, you can find string gauges in the odd sizes, depending on the manufacturer. I've filled odd sets by pulling from a couple different makers. You can check with Dunlop and D'Addario.
As mentioned in the comments, there sometime is very little difference in a single gauge change. I have measured strings with digital calipers and found that there can be some on variance on what .048 means to each manufacturer, some a little bigger, some a little smaller.


paging in gridview get same data for all pages

Question: I had gridview which get data from database according to two event .The first from method ,the second when selected ddl.it worked well ,I made paging and when I go through paging pages I must click two click on number of page to go to this page also all pages get same data for firt page .So plaes any one help me.
<aspx>

                                                        Dealers list

                                                        Select City

                                                        <asp:SqlDataSource ID="SDSGetDealerArea" runat="server" ConnectionString="<%$ ConnectionStrings:ElarabyGroup %>"
                                                            ProviderName="System.Data.SqlClient" SelectCommand="SELECT [AREA_ID], [AREA_ENG] FROM [DealerArea]">
                                                        </asp:SqlDataSource>
                                                        <%--  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                                                                <ContentTemplate>--%>
                                                        <asp:DropDownList CssClass="ad_mun_font_h" ID="DDlCity" runat="server" AutoPostBack="True"
                                                            DataSourceID="SDSGetDealerArea" DataTextField="AREA_ENG" DataValueField="AREA_ID"
                                                            OnDataBound="DDlCity_DataBound" OnSelectedIndexChanged="DDlCity_SelectedIndexChanged">
                                                        </asp:DropDownList>
                                                        <%-- </ContentTemplate>
                                                                <Triggers>
                                                                    <asp:AsyncPostBackTrigger ControlID="DDlCity" EventName="SelectedIndexChanged" />
                                                                </Triggers>
                                                            </asp:UpdatePanel>--%>

                                                        <asp:Label ID="LblResult" runat="server" Text="Result" Font-Bold="True" ForeColor="#006699"
                                                            Visible="false"></asp:Label>

                                            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
                                                AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None"
                                                CellPadding="3" DataKeyNames="DEALER_ID,LOC_ID,CAT_ID,AREA_ID" CellSpacing="3"
                                                GridLines="Horizontal" Width="510px" BorderWidth="1px" OnPageIndexChanging="GridView1_PageIndexChanging">
                                                <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                                                <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                                                <Columns>
                                                    <asp:TemplateField HeaderText="Name" SortExpression="NAME_ENG">
                                                        <ItemTemplate>
                                                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("NAME_ENG") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NAME_ENG") %>'></asp:TextBox>
                                                        </EditItemTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Address" SortExpression="ADR_ENG">
                                                        <ItemTemplate>
                                                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("ADR_ENG") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("ADR_ENG") %>'></asp:TextBox>
                                                        </EditItemTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Telephone" SortExpression="TEL_ENG">
                                                        <ItemTemplate>
                                                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("TEL_ENG") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("TEL_ENG") %>'></asp:TextBox>
                                                        </EditItemTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Mobile" SortExpression="TEL_ARA">
                                                        <ItemTemplate>
                                                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("TEL_ARA") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("TEL_ARA") %>'></asp:TextBox>
                                                        </EditItemTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Location" SortExpression="LOC_ENG">
                                                        <ItemTemplate>
                                                            <asp:Label ID="Label5" runat="server" Text='<%# Bind("LOC_ENG") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("LOC_ENG") %>'></asp:TextBox>
                                                        </EditItemTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Category" SortExpression="CAT_NAME">
                                                        <ItemTemplate>
                                                            <asp:Label ID="Label6" runat="server" Text='<%# Bind("CAT_NAME") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("CAT_NAME") %>'></asp:TextBox>
                                                        </EditItemTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Area" SortExpression="AREA_ENG">
                                                        <ItemTemplate>
                                                            <asp:Label ID="Label7" runat="server" Text='<%# Bind("AREA_ENG") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <EditItemTemplate>
                                                            <asp:TextBox ID="TextBox7" runat="server" Text='<%# Bind("AREA_ENG") %>'></asp:TextBox>
                                                        </EditItemTemplate>
                                                    </asp:TemplateField>
                                                </Columns>
                                                <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                                <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                                                <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                                                <AlternatingRowStyle BackColor="#DCDCDC" />
                                            </asp:GridView>
                                            <asp:Panel ID="pnlModal" runat="server" Style="display: none" CssClass="modalPopup">
                                                Our Valued Customer You Are Not Registered Are You Want To Register?

                                                            Username :

                                                                <asp:TextBox ID="TxtUser" runat="server" Width="125px"></asp:TextBox>

                                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
                                                                ControlToValidate="TxtUser" Display="Dynamic" SetFocusOnError="True">*</asp:RequiredFieldValidator>

                                                                            <asp:CheckBox ID="CBRemeber" runat="server" class="tx_s" OnCheckedChanged="CBRemeber_CheckedChanged" />

                                                                        Remember me

                                                            Password :

                                                                <asp:TextBox ID="TXTPassword" runat="server" TextMode="Password" Width="125px"></asp:TextBox>

                                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"
                                                                ControlToValidate="TXTPassword" Display="Dynamic" SetFocusOnError="True">*</asp:RequiredFieldValidator>

                                                            <asp:ImageButton ID="IBLogin" runat="server" ImageUrl="images/home-d_login.jpg" OnClick="IBLogin_Click" />

                                                            <asp:Label ID="Label8" runat="server" CssClass="ad_mun_font" Text="result" Visible="false"></asp:Label>

                                                            Close

                                                            Register

                                            </asp:Panel>
                                            <cc1:ModalPopupExtender TargetControlID="btnYes" ID="pnlModal_ModalPopupExtender"
                                                runat="server" Enabled="True" BackgroundCssClass="modalBackground" PopupControlID="pnlModal"
                                                CancelControlID="btnYes" DropShadow="true">
                                            </cc1:ModalPopupExtender>
                                            <asp:HiddenField ID="btnYes" runat="server" />

 protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

           BindGridFunction();
        }

    }

    private void BindGridFunction()
    {

        DataTable DT = new DataTable();
        using (SqlConnection con = Connection.GetConnection())
        {
            SqlCommand Com = new SqlCommand();
            if (DDlCity.SelectedIndex < 0)
            {
                Com = new SqlCommand("GetDealers", con);
                Com.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter DA = new SqlDataAdapter(Com);
                DA.Fill(DT);
                GridView1.DataSource = DT;
                GridView1.DataBind();
            }
            else
            {
                Com = new SqlCommand("GetDealersByArea", con);
                Com.CommandType = CommandType.StoredProcedure;
                Com.Parameters.Add(Parameter.NewNVarChar("@AREA_ENG", DDlCity.SelectedItem.Text));
                SqlDataAdapter DA = new SqlDataAdapter(Com);
                DA.Fill(DT);
                GridView1.DataSource = DT;
                GridView1.DataBind();
            }

        }
    }

    protected void DDlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGridFunction();

    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
    }
}

Answer: Try rebinding after GridView1.PageIndex = e.NewPageIndex; call GridView1.DataBind();
.
--EDIT--
DataSet and then DataBind(), try it like:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    BindGridFunction();
}

Comment: It worked well.when I refreshed the page when select from ddl it go to previous page where I selected .
Comment: Upon page index change, you can keep the page index in `ViewState`; so whenever the `ViewState` has a value, then set it as page index; otherwise let the usual pageload work it for you.
Comment: please I couldnot do that if you can help me with ex.


Extracting a number that occurs after a specific word from a longer text/file

Question: I have a text file of 5631 lines. I want to extract and store the number which appears after the word bytes at
Sample line form middle of the file is below :
debug3: In write loop, ack for 1606 32768 bytes at 52527104

Here I want the value 52527104. Each line this value increases and my goal is to calculate the percent completion based on each lines value. By using the formula ((obtained*100)/total).
Thanks.
Comment: Is every line of this format, or only some of them?
Comment: In this specific case you can just do `String[] splits = string.split(" ");` and to access it, `splits[splits.length-1];`.
Comment: Are you forced to use java? There are a number of unix command line tools that would be far better for this specific case
Comment: Some of them. I am concern only when "byte at" occurs.
Comment: As I am beginner to unix it could be a mess. But any help will be highly appreciated. @DiegoMartinoia
Answer: You can simply split the read lines by bytes at and use the value at index 1. I have used Long parser, you can use Integer as per your requirement. The code will ignore lines, which doesn't contain the pattern provided.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class BytesAt {
  public static void main(String[] args) throws FileNotFoundException {
    Scanner read = new Scanner(new File("input.txt"));
    while (read.hasNextLine()) {
      String line = read.nextLine();
      String parts[] = line.split("bytes at");
      if(parts.length > 1) {
        System.out.println("Value as String: " + parts[1].trim());
        System.out.println("Value as Long: " + Long.parseLong(parts[1].trim()));
      }
    }
  }
}

Comment: @Keppil Thanks. I missed it.
Comment: This answer is correct only if `bytes at %NUMBER%` appears at the end of the line.`read.hasNextLine()` is more suitable.
Comment: @s-das updated with a conditional check, to handle other lines of the file which doesn't contain pattern.
Comment: @TAsk Thanks. Updated it.
Answer: How about:
long totalBytes = //Whatever source.
long currValue = 0;
for (String line: lines) {
  if (line.contains("bytes at")) {
    long currValue = Long.parseLong(line.split("bytes at\\s")[1]);
  }
  System.out.println("Completed % = "+(float)(currValue/totalBytes*100);
}


Como abrir do MVC3 uma aplicação externa em MVC5?

Question: Tenho uma aplicação em MVC3 e tenho que chamar uma outra aplicação hospedada no mesmo servidor, esta em MVC5.
Devo usar um ajax?
Devo fazer um iframe?
Assim: tem um menu que é do MVC3 e que tem que ficar aparecendo. Então pensei que poderia ser Iframe ou uma div com chamada ajax do conteúdo da outra aplicação, o que devo usar?
Comment: Acho que `iframe` pode ser uma solução, sobretudo se são duas aplicações diferentes, sem acessos a dados uma da outra.
Comment: Esse é o meu problema, Cigano eu tenho que passar para MVC5 quem esta logado teria que passar via get eu pensei que teria algo diferente de Iframe não estou pesquisando dois dias não achei nada.
Answer: A resposta para isso não é nada simples. Ela se baseia em Single Sign On (SSO) entre dois sites diferentes, usando alguma biblioteca de SSO como a SSOLib.
Aqui tem um (enorme) tutorial de como fazer. Este outro link seria o projeto da proposta do primeiro link. Em ASP.NET MVC, haverá algumas pequenas adaptações para que a aplicação se adeque a usar um Controller ao invés de uma Page.
Comment: Show como Sempre fera Cigando, kara muito obrigado mesmo.


Dúvida sobre retorno de dados em POO PHP

Question: Eu estou aprendendo sobre a programação orientada a objetos no PHP, as classes, hierarquias e etc.
Lendo alguns tópicos aqui mesmo no stackoverflow eu encontrei a solução para o meu problema com a classe de controle de usuários, mas eu fiquei com uma dúvida em relação a isso.
A classe seria:
class UserService
{
protected $_email;    // using protected so they can be accessed
protected $_password; // and overidden if necessary
protected $_user;     // stores the user data

public function __construct($email, $password)
{
   $this->_email = $email;
   $this->_password = $password;
}
public function login()
{
    $user = $this->_checkCredentials();
    if ($user) {
        $this->_user = $user; // store it so it can be accessed later
        $_SESSION['user_id'] = $user['id'];
        return $user['id'];
    }
    return false;
}

protected function _checkCredentials()
{

    /* Faz a rotina para verificar se o usuário está no banco de dados*/
    /* e se a senha confere */

    /* Se OK retorna os dados do usuário, se não, retorna false */

}
}

Eu estou em dúvida em como usar essa classe caso eu queira retornar apenas o nome de usuário por exemplo.
Para logar o usuário eu entendi, seria:
session_start();
include("class.user.php");

$user = new UserService($_POST['email'], $_POST['pass']);

Mas e se eu quiser retornar apenas o nome (ou algum outro dado) do usuário já logado, sem ter que passar os parâmetros "email" e "password" novamente?
Eu teria que criar uma função dentro da classe para que eu passasse o ID do usuário armazenado na $_SESSION e a classe retornaria os dados, mas eu teria que instanciar a classe usando o "new" novamente?
Por exemplo, na classe, acrescentar:
public function getUserName($uID)
{
   /* Verifica se o usuário está logado e busca o nome no DB */
}

E no arquivo principal (considerando que o usuário já tenha sido logado anteriormente):
session_start();
include("class.user.php");

$user = new UserService();

$userName = $user->getUserName($_SESSION['user_id']);

echo $userName;

Isso está correto?
EDIT: Essa classe é só um rascunho do que eu pretendo fazer, eu compreendo que é necessário corrigir alguns trechos, sanitizar os campos, encriptar a senha e etc, essa é apenas para demonstrar minha dúvida.
Answer: Basta você setar session_start() no __construct, caso após login você já colocar a $_SESSION['nome'] aí ficaria assim:
  public function getUserName()
  {
    return $_SESSION['nome'];
  }

Comment: Certo, mas ao chamar a classe eu preciso chamar o "new" ou instanciar a classe diretamente?
Comment: Se a classe não for static você sempre tem que instanciar com o new. se ela for static você só precisa fazer assim UserService::getUserName(); não esquecer que tem que da um include no classe no começo do arquivo.


Custom handler for custom message

Question: I have a Webform (6.x) with style Cards, and Ajax.
I would like the users to be able to personalize the message shown as confirmation of the form, with paragraphs and the like.
With a regular webform we have implemented a custom handler with a redirect to a node.
With the Cards/Ajax it would be interesting to show the content of that node (configured in the handler) as a confirmation message.
Any suggestion on how we could, from a custom handler, I guess that with the confirmForm function, "catch and replace" the confirmation message?
Answer: I have found the solution myself after debugging. Leaving it here for further reference: based on https://git.drupalcode.org/project/webform/-/blob/6.1.x/src/Plugin/WebformHandlerBase.php#L607
public function preprocessConfirmation(array &$variables) {}

Implementing this we can easily modify the message as a simple "markup" element in
$variables['message']

Comment: It works is most cases except when I've to show message in modal dialog box.

Custom handler for custom message


What does a confidence interval around a p-value mean when using a permutation test?

Question: I am using the coin package in R to do a permutation test and it gives output that looks like this:
<code>> pvalue(pt)
[1] 0.1479615
99 percent confidence interval:
0.1450811 0.1508754
</code>
Why would one want a confidence interval for a p-value? How should it be interpreted, and how should it be used?
Comment: That's because the permutations were not exhaustive in your case, that was a Monte Carlo permutation significance test. In such a test, p-value is not a precise (point) probability but rather an interval about the obtained value of p.
Comment: http://cran.r-project.org/web/packages/coin/vignettes/coin_implementation.pdf
Answer: The theory of permutation tests (and bootstraping) is based on the idea of looking at every possible permutation.  If you can look at every possible permutation then you have an exact p-value.
For most cases it is impractical to compute every possible permutation so instead we sample from the "population" of possible permutations and compute a p-value from this "sample".  So since we take a sample from the population we can use standard techniques (the binomial proportion in this case) to calculate a confidence interval for the true p-value that we would have calculated from every possible permutation.
How to use this confidence interval:  If the value of alpha (your significance cutoff or probability of type I error) is in the interval then you are not sure whether to reject or not since a different sample of permutations could have given a different result.  This means that you should probably rerun the analysis using a much larger number of permutations to get a better estimate of the true p-value.
If the entire interval is far from your alpha value then you can be confident in your rejection or nonrejection of the null hypothesis.  Some people will report the bound of the confidence interval that is closest to alpha as a conservitive p-value.  If you have done a large number of permutations then generally the bounds will be close enough together that it will not matter much either way.
Answer: The pure frequentist interpretation: If your were to do this experiment $N$ times, you should expect $X$ percent of the time (99% in your case) or $N * X$ times, that the true $p$ value falls inside the range provided by this 99% confidence interval that percentage or number of times.


How can I construct polynomials with "small" coefficients generating a prime "late"?

Question: Let $f(x)$ be a polynomial with degree $5$, integer coefficients and positive leading coefficient. Let $M$ be the maximum of the absolute values of the coefficients. Assume the smallest non-negative integer $n$ such that $f(n)$ is prime is greater than $10\ 000$, but that such an $n$ exist.

Can I construct polynomials with the desired property and "small" $M$ ?
Can the smallest possible $M$ be determined efficiently ?

Idea : Construct an irreducible polynomial such that the $\gcd$ of its values is $1$. This should generate at least one prime due to the Bunyakovsky-conjecture. The problem is to avoid an "earlier" prime.
Motivation : Constructing "hard cases" for the bunyakovsky conjecture.
Comment: Primes are plentiful; it's really, *really*, ***really*** hard for a relatively slow growing sequence like a polynomial to miss the primes so often.
Comment: $M=10^6+1$ works with $f=X^5-(10^6+1)X^4+2$
Comment: @Shalom $12$ is the smallest $x$ giving a prime.
Comment: For what is worth, with $M=8$ the record is $6-3 x-6 x^2+7 x^3+5 x^4+6 x^5$. The first prime value comes at $x = 827$.
Comment: With the problem changed to the first $10^4$ values, the estimate I was making drops to $M= 10^{18}$. But I *know* this time I'm outside the domain where my estimates are good, because the size of $x^5$ is no longer negligible as compared to the size of $M$.
Comment: I checked all of them (if my program is correct). Now I am doing the calculation with $M=10$ and $f(0)$ even. At this moment the record holder is $-10-10 x-7 x^2+9 x^3+2 x^4+x^5$; the first prime appears at $x=1000$.
Comment: @Hurkyl Do you have a guess how large $M$ must be ?
Comment: @Mastrem $n=0$ is allowed as well, but I understand the point. If the polynomial is negative upto a high limit, we have of course a good chance for a "late" prime.
Comment: @Peter When a first prime occurs in $x^5+3x^4+3x^2+1$?
Comment: @Mastrem But $f(0)=2$ is prime.
Comment: @JuliánAguirre Yes, my mistake. I'll delete the comment shortly? EDIT: It's better not to delete it, since that would make that the two replies unclear
Comment: I have started a computer search. With $M=5$, I found that the first prime value of $-4-5 x+4 x^2+4 x^3-5 x^4+5 x^5$ appears at $x = 205$.
Comment: @JuliánAguirre Not bad, way larger than the coefficients.But I think Hurkyl is right, $10^6$ will only work if the polynomial gets greater than $1$ very late.
Comment: @JuliánAguirre Thank you, did you check all polynomials or just random polynomials and this was the record-holder ?
Comment: Since $10^6$ is probably too difficult , unless the polynomial gets large "very late" ,  I reduced to $10\ 000$
Comment: @Peter: My first back-of-the-envelope estimate suggests something like $M=10^{600}$ if you want the first $10^6$ values not to be prime. However, I have not checked how plausible by estimations are with values of this magnitude. I am modeling this as the odds that a "random" collection of $10^6$ numbers of size similar to the values of the polynomial is entirely composite. I am, however, counting the negative primes too. As Mastrem noted, if you are allowing $f$ to take negative prime values, you can reduce this by picking functions that are mostly negative.
Comment: @Hurkyl Does the question become more interesting , if I replace $f(n)$ by $|f(n)|$ ?
Comment: Julian's polynomial also remains valid if we replace $f(n)$ by $|f(n)|$. Moreover, it is positive for all non-negative $n$.
Comment: If we do not count negative primes, then $f(x)=7x^5 - 4x^4 - 5x^3 + 3x - 6$ is best with $M=8$, the first prime appearing at $1495$
Comment: The current best polynomial (even if negative primes count) is $$5x^5 - 11x^4 - 5x^3 + 10x - 9$$ with first prime occuring at $1990$ followed by $$4x^5 + 9x^4 + 10x^2 + 6x + 6$$ with first prime occuring at $1945$ and non-negative coefficients.
Comment: New record with $M=10$ (although I looked at $M=12$) : $$9x^5 - 8x^4 - x^3 + 3x^2 - 8x - 10$$ First prime occuring at $2337$ , possible negative primes considered.
Comment: If we consider negative primes, $2337$ is the optimum for $M=12$ and for $M=8$ the optimum is $827$ as already found out by Julian.
Comment: With $M=14$, the best polynomial is $$11x^5 - 4x^4 + 14x^3 + 11x^2 - 7x - 10$$ with first prime occuring at $3129$
Answer: Let's start by generalizing the notation a little ($d$ and $B$ will be positive integers):

$H(P)$ will denote the height of a polynomial (maximum of absolute values of its coefficients).
$S_d(B)$ will denote the set of polynomials $P(x)$ of degree $d$ with integer coefficients for which:

$|P(k)|$ is prime for some positive integer $k$ but
$|P(k)|$ is not prime for $0\leq k\leq B$.

Finally, define $M_d(B)=\min\limits_{P\in S_d(B)} H(P)$

In this notation, the original question was asking for $M_5(10^6)$ and the simplified version is looking for $M_5(10^4)$.
Note that the definition of $M_d(B)$ relies on $S_d(B)$ being non-empty; a property that is not as obvious as it may seem (or I might have missed the easy proof of it). Since we are only going to focus on a few specific cases, we can overlook this as a technical detail.
Using computer-assisted search, I found the polynomial $$P_5(x)=39x^5 + 6x^4 + 21x^3 - 44x^2 + 47x + 15$$ which doesn't produce a prime until $x=13076$ and thus belongs to $S_5(10^4)$. This implies $M_5(10^4)\leq 47$. Note that the search was not exhaustive, so the bound is not necessarily the optimal one.
As expected, if we let the degree increase, the coefficients of the polynomial can be lowered: For example, another search found $$P_6(x)=25x^6 + 24x^5 + 11x^4 + 10x^3 + 25x^2 - 4x + 14$$ which is non-prime until $x=10905$, so $M_6(10^4)\leq 25$ (again, the search was non-exhaustive, thus the inequality).
On the other hand, going down to degree $4$ yields polynomial $$P_4(x)=11x^4 - 146x^3 - 99x^2 + 19x + 105$$ which isn't prime until $x=10774$. Thus, $M_4(10^4)\leq 146$.


Getting SSL certificate from remote server with OpenSSL

Question: I encountered a strange problem and I cannot spin my head around it.
I'm trying to validate a SSL certificate using OpenSSL from command line:
openssl s_client -showcerts -connect server.org:443

But no matter which domain on this server I call that way it delivers always the certificate of the first (alphabetically) domain on that server even if this particular domain do have own certificate. Also when I call any of this urls in browser everything works correctly
Any idea what have I done wrong?
Regards,
Radek
Answer: You are likely using an older version of openssl, i.e. version 1.0.2 or lower. With these you have to explicitly use the -servername option so that the SNI extension is used to announce the expected hostname in the TLS handshake:
openssl s_client -connect example.com:443 -servername example.com

With later versions of openssl this option is enabled by default.
Comment: Thanks a lot. That was it of course.


Is there a bug in numpy when using the += operator

Question: When using a function in phyton, I am taught that actually a copy of my value is parsed. In the example shown below apply a function onto a Parameter a. Here, I expected that a copy of a is sent to the function fun. In this function, only the copy of a is available, not parameter a on a global scope. I even gave it another Name: b. When I modify the value b in my function, then also the Parameter a on the global scope is changed. Is this supposed to be correct?
import numpy as np

def fun(b):
    b += np.array([1,1])

a = np.array([1,1])

fun(a)

print(a)

I expected to get np.array([1,1]), but I get np.array([2,2])
This happens only, when I use the += Operator in the function fun. If I use b = b + np.array([1,1]) instead, the value of a on global scope stays the same.
Comment: In `def fun(b)`, the paramter `b` was passed in by reference. While you run the following, you will understand the issue:

```
import numpy as np

def fun(b):
    print(['in def fun(b)', id(b)])
    b += np.array([1, 1])

a = np.array([1, 1])

print(id(a))

fun(a)

print(id(a))

print(a)

```
Comment: @Till Hoffmann the [duplicate] mark is kinkd of wrong.
Answer: In python the list datatype is mutable, that means that every time you run your function, a list will keep growing.
The key moment is here: b += np.array([1,1])
You already got a, which is [1, 1] and you adding it to another array which is [1, 1] and you are getting [2, 2] which is how it should be.
You are ending up modifying the a
Answer: When you call fun() you don't make a copy of a and modify b, rather, a itself is passed to fun() and refered to as b in there.
As such,
b += np.array([1,1])

modifies a.